Saturday, June 7, 2014

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

I was using Google map API version2 with for one of my application.In layout I was using "com.google.android.gms.maps.MapFragment".

 <RelativeLayout
                        android:id="@+id/relative_disc_nyc_map"
                        android:layout_width="fill_parent"
                        android:layout_height="fill_parent" >

                        <fragment
                            android:id="@+id/frg_disc_nyc_map"
                            android:layout_width="fill_parent"
                            android:layout_height="fill_parent"
                            class="com.google.android.gms.maps.MapFragment" />
             </RelativeLayout>

And while executing I was using the above layout and adding it into fragment.....

public class DiscoverNYCActivity extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_discover_nyc, container, false);
        lbl_poi_title = (TextView) rootView.findViewById(R.id.lbl_poi_title);
        lbl_rate_count = (TextView) rootView.findViewById(R.id.lbl_rate_count);
return rootView;
}

But when I was travesing to the sam e screen twice.I was giving me below error

06-07 14:41:41.496: E/AndroidRuntime(21037): FATAL EXCEPTION: main
06-07 14:41:41.496: E/AndroidRuntime(21037): android.view.InflateException: Binary XML file line #120: Error inflating class fragment
06-07 14:41:41.496: E/AndroidRuntime(21037): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:719)
06-07 14:41:41.496: E/AndroidRuntime(21037): at android.view.LayoutInflater.rInflate(LayoutInflater.java:761)
06-07 14:41:41.496: E/AndroidRuntime(21037): at com.wf.wholesale.nymta.DiscoverNYCActivity.onCreateView(DiscoverNYCActivity.java:101)
06-07 14:41:41.496: E/AndroidRuntime(21037): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1500)
06-07 14:41:41.496: E/AndroidRuntime(21037): Caused by: java.lang.IllegalArgumentException: Binary XML file line #120: Duplicate id 0x7f090058, tag null, or parent id 0x7f090057 with another fragment for com.google.android.gms.maps.MapFragment
06-07 14:41:41.496: E/AndroidRuntime(21037): at android.app.Activity.onCreateView(Activity.java:4971)
06-07 14:41:41.496: E/AndroidRuntime(21037): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:695)
06-07 14:41:41.496: E/AndroidRuntime(21037): ... 24 more


The problem is that what I was trying was wrong. You shouldn't be inflating fragments inside other fragments. From Android's documentation:

Note: You cannot inflate a layout into a fragment when that layout includes a <fragment>. Nested fragments are only supported when added to a fragment dynamically.

I have resolved the error with below changes.....

public class DiscoverNYCActivity extends Fragment {
View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
 if (rootView != null) {
           ViewGroup parent = (ViewGroup) rootView.getParent();
           if (parent != null)
               parent.removeView(rootView);
       }
       try {
        rootView = inflater.inflate(R.layout.activity_discover_nyc, container, false);
       } catch (InflateException e) {
            map is already there, just return view as it is 
       }
        lbl_poi_title = (TextView) rootView.findViewById(R.id.lbl_poi_title);
        lbl_rate_count = (TextView) rootView.findViewById(R.id.lbl_rate_count);
return rootView;
}

Monday, June 2, 2014

Eclipse Error : Using 1.7 requires using Android Build Tools version 19 or later; currently using 17.0.0 ?

The project shows this error when relevant build tool is not set for the Project.
First goto Eclipse-->Windows--->Android SDK Manager and installed the relevant build tool required by the application.After installation is completed close the SDK manager.

Then add the below line in "project.properties" file of then prject.Error will be resolved.

sdk.buildtools=19.1

Tuesday, May 27, 2014

Android Host Card Emulation(HCE) in 4.4 ?

 FAQ

Q> What is HCE?
A> Host-Based Card Emulation

Er... whats that??
Before we talk about HCE (Host-Based Card Emulation) we must understand what is CE (Card Emulation)

Card Emulation is as it says emulation of a card (CreditCard/ ID Card/ Loyalty Card / any card) over NFC interface of a mobile phone.

In this mode a mobile NFC can exchange APDU (Data) with the a POS (Payment Terminals) or any other Terminal (eg. Security Machine on Doors or a Time punching machine for your office )

Alright!! I understand NFC but whats Card Emulation?
A card in this refers to a an environment which is created with the help of secure element, and applets.

Woaahhh 2 NEW TERMS!!!
Secure Element:  In simplest words.. Its a memory + processor + Mini OS which is out of phone OS, is highly restricted for access and is believed to be non-hackable!
Applets: Nothing more than small Java Programs which can run on this Mini OS of Secure Element. Which communicates based on Hexadecimal Commands also known as APDU.

So when you use your credit card or even a sim card remember "YOU GOT THE POWER" of secure element in your hands. Yeah that a freaking complete Operating system which is super secure in your hand.

Ok.. so??

So Card Emulation basically says that in order to communicate with this Card (Secure Element + Applets) the Phone NFC will accept the commands, will send these commands to Card residing somewhere in the phone and then will forward the responses generated from this Card over NFC interface back to the terminal.(See Dig.2)

Now to ease things up Card can be present in 3 of these location
1. Embedded Secure Element
2. SDCard based Secure Element
3. UICC (SIM Card)

Kool!! then why do we need HCE?
The biggest advantage is also the biggest disadvantage for Secure Element, being highly restricted, any addition of deletion of data needs heck of approvals from the provider of these.
For example: In case of UICC based Secure Element, only the MNO (mobile Network Operator) who owns a SIM card is authorised to put your CreditCard data inside the secure element, BUT, the CreditCard belongs to a Issuer (Bank) therefore in-order to put one simple CreditCard inside a secure element you need Bank and MNO to come together and work together. No wonder you don't see many application which uses any of these technologies.

Now with HCE, there is no need for Secure Element, I mean you can work even without them.
Now the data can directly be sent and received by an application, your own phone application.(See Dig.3)

Overview on Host Card Emulation (HCE)
HCE is an open architecture that allows mobile applications to emulate a contactless smartcard. Unlike traditional NFC transactions that rely an embedded or SIM card Secure Element (SE), HCE is a purely software-based solution. This new approach is significant for the industry because: 1) it takes control away from mobile network operators (MNOs) who control access to a mobile device’s SE and, 2) it creates new possibilities for using a phone’s NFC feature.

Host Card Emulation (HCE) as an exciting development for the NFC market because it provides an additional means by which to perform NFC transactions. With HCE, transactions take place using credentials stored in the cloud or on the host processor of the NFC-enabled mobile device rather than a tamper resistant Secure Element, such as an embedded security chip, SIM, or microSD card.

HCE works by storing payment credentials on a remote cloud rather than the SE (see Figure 1). Conceptually, a mobile application could be programed to send requests to allow access to these credentials via a secure token. This token would then be passed via the phone’s NFC antennae to another contactless reader to complete a payment transaction. A key requirement is ensuring that the token is recognized by the reader as a valid payment credential.

Dig.1

This development may prove troubling to some mobile wallets, like the Mobile Network Operator-led Isis, which relies on the SE approach.Isis currently requires card issuers to integrate with a Trusted Service Manager (TSM) to facilitate access to a device’s SE.HCE provides an alternative to TSM integration, which can be expensive and time consuming. To date, only a few European banks have explored HCE deployment, but there are service providers that are prepared to enable similar solutions in the U.S. market. Visa and MasterCard have also independently announced their intentions to provide software development kits (SDKs) that would allow issuers and other potential wallet providers to write HCE applications that conform to the existing contactless payment specifications.

Host Card Emulation (HCE) as an exciting development for the NFC market because it provides an additional means by which to perform NFC transactions. With HCE, transactions take place using credentials stored in the cloud or on the host processor of the NFC-enabled mobile device rather than a tamper resistant Secure Element, such as an embedded security chip, SIM, or microSD card.As the definition suggests, it is an emulation of a contactless smart card. What is the capability of a contactless smart card? Mainly payment, identification and transportation. What happens when one of these cards, say your id card, which you use for entering your office building is just an app on your mobile phone? Or your contactless credit/debit card? Sounds intriguing.

Before HCE, contactless smart card was being emulated by a hardware chip and software (mobile app) was needed for the hardware to be activated. Hardware component was either a chip embedded on the phone or the SIM card. Either way, a few more parties other than the owner of the handset itself was involved in the game and it was quite complicated to activate and use the NFC app. Now with the HCE, smart card is still being emulated but this time it is software rather than the hardware.

In the hardware mode, contactless (NFC) reader was working with the secure element.
 Dig.2

Now with the HCE, hardware component -SE or the embedded chip is not needed. Android itself emulates the hardware. Apps will use the interface provided by the operating system again but this time there is no hardware below the API.
Dig.3

Tuesday, December 17, 2013

How to Load Apps or Apk on Google Glass ?

For this tutorial we will show you how install Google Sky (also known as stardroid) without rooting your Glass or swapping roms. This is the same basic procedure you would go through to manually load an app on an Android phone, but since Google Glass has a limited amount of input, the specific app you install matters. 

Before we begin it is important that you already have the Android SDK, most importantly you need ADB (android debug bridge). You also need to be somewhat familiar with opening a new terminal window. We will work for Linux and might need a little modification for Windows. We also assume you download files to your home Download directory, but you can change this as needed. (~/Downloads)

Download and Install the Android SDK (http://developer.android.com/sdk/index.html). We find it helpful to have adb in your PATH so you can call it from anywhere (you may want to add it to your .bashrc or whatever you are using).

export PATH=$PATH:~/Downloads/adt-bundle-mac-x86_64-20130514/sdk/platform-tools

First things first, Put your Glass in “Debug Mode” in the settings on the Glass itself. Locate the device info and scroll right to turn Debug Mode on. Then plug your Glass into your computer using the USB micro cable.

Now grab a version of Google Sky that you want to install (this is the same for any Android .apk file).

wget http://file.appsapk.com/wp-content/uploads/apps-2/Google%20Sky%20Map.apk

Simply load the .apk file onto the Glass with adb.

adb install ~/Downloads/Google\ Sky\ Map.apk

After the .apk is loaded onto Glass you now need to use adb shell to run it. The trick here is that you need to figure out what Activity to run. You can use the adb command dumpsys to discover a plethora of information about your Glass. You can figure out the main activity for the .apk with a little help from grep, and since it was the last thing loaded we can also narrow this information down with a tail command.

adb shell dumpsys | grep android.intent.action.MAIN | tail -n 2

This might take some time depending on your system, but it will eventually return something similar to this:

intent={act=android.intent.action.MAIN flg=0×10000000 cmp=com.google.android.stardroid/.activities.SplashScreenActivity}
android.intent.action.MAIN:

You now have the right information to start the app on Glass. We use the am command to start the app on Glass. Simply reformat the Activity call to follow the same format as the stardroid example call below:

adb shell am start -a android.intent.action.MAIN -n com.google.android.stardroid/com.google.android.stardroid.activities.SplashScreenActivity

At this point tap your Glass on and the app should be running. You will need to “down swipe” on your glass to cancel the agreement window. If you see the app running, disconnect, go outside, and check this out at nighttime! Warning: you may feel like a terminator with some kind of super power.

Note: this is not part of the Official Glass Mirror API that is displayed on your timeline and running apps full time like this is a drain on the battery, which is not in Google’s application design guidelines. It merely demonstrates how to sideload an app on Glass in your terminal without voiding your warranty.

Friday, November 22, 2013

How to get SHA certificate in Windows ?

C:\Program Files (x86)\Java\jdk1.6.0_06\bin>keytool -v -list -keystore C:\Users\sshukla\.android\debug.keystore -alias androiddebugkey -storepass android -keypass android
Alias name: androiddebugkey
Creation date: Apr 18, 2013
Entry type: PrivateKeyEntry
Certificate chain length: 1
Certificate[1]:
Owner: CN=Android Debug, O=Android, C=US
Issuer: CN=Android Debug, O=Android, C=US
Serial number: 64bbfdff
Valid from: Thu Apr 18 14:56:16 IST 2013 until: Sat Apr 11 14:56:16 IST 2043
Certificate fingerprints:
         MD5:  75:73:CC:22:4C:C0:EB:04:6A:C5:63:89:57:66:DC:DB
         SHA1: 8A:C7:3A:96:2E:4E:D2:F0:C6:B0:AB:1D:A2:FE:DA:6E:E2:71:8F:CD
         Signature algorithm name: SHA256withRSA
         Version: 3

Extensions:

#1: ObjectId: 2.5.29.14 Criticality=false
SubjectKeyIdentifier [
KeyIdentifier [
0000: EF 85 F0 F3 11 65 7A D3   C7 66 10 21 BE 85 DB 69  .....ez..f.!...i
0010: 8B 9A 7A 07                                        ..z.
]
]


C:\Program Files (x86)\Java\jdk1.6.0_06\bin>

Thursday, June 20, 2013

APNS SSL Error - javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure?


1. Created certificates from mac machine
2. in tomcat server application using JavaPNS to send the notification
Used Push.alert(...) used .p12 file


javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

I finally find the problem is due to the p12 certificate. We should not use the private key p12 file, instead we
should generate a p12 from your private key and the cert download from Apple.

Please execute the following OpenSSL command to get the correct p12 file

developer_identity.cer <= download from Apple
mykey.p12 <= Your private key

1) openssl x509 -in developer_identity.cer -inform DER -out developer_identity.pem -outform PEM
- developer_identity.cer = the .cer file obtained from developer.apple.com site.
- developer_identity.pem = the "PEM" output file name.

2) openssl pkcs12 -nocerts -in mykey.p12 -out mykey.pem.
- mykey.p12 = the (.p12) file obtained initially from exporting (.cer) file.
- mykey.pem = the "PEM" output file name.

3) openssl pkcs12 -export -inkey mykey.pem -in developer_identity.pem -out iphone_dev.p12
- mykey.pem = the "PEM" file obtained in step (2).
- developer_identity.pem = the "PEM" file obtained in step (1).
- iphone_dev.p12 = the final (.p12) file, to be used at backend server side.

After that, you should use iphone_dev.p12 to communicate with apple server.

Tuesday, December 18, 2012

Convert Seconds into HH:MM:SS in java?

Below are the methods to convert seconds into minute seconds format...


int day = (int)TimeUnit.SECONDS.toDays(seconds);      
long hours = TimeUnit.SECONDS.toHours(seconds) - (day *24);
long minute = TimeUnit.SECONDS.toMinutes(seconds) - (TimeUnit.SECONDS.toHours(seconds)* 60);
long second = TimeUnit.SECONDS.toSeconds(seconds) - (TimeUnit.SECONDS.toMinutes(seconds) *60);
 System.out.println("Random Element "+minute+":"+second);

OR 

public static void calculateTime(long seconds) {
   int day = (int) TimeUnit.SECONDS.toDays(seconds);
   long hours = TimeUnit.SECONDS.toHours(seconds) -
                TimeUnit.DAYS.toHours(day);
   long minute = TimeUnit.SECONDS.toMinutes(seconds) -
                 TimeUnit.DAYS.toMinutes(day) -
                 TimeUnit.HOURS.toMinutes(hours);
   long second = TimeUnit.SECONDS.toSeconds(seconds) -
                 TimeUnit.DAYS.toSeconds(day) -
                 TimeUnit.HOURS.toSeconds(hours) -
                 TimeUnit.MINUTES.toSeconds(minute);
   System.out.println("Day " + day + " Hour " + hours + " Minute " + minute + " Seconds " + second);
}

Monday, December 10, 2012

Android serialization of Objects ?


We can also see below links...
http://www.dreamincode.net/forums/topic/248522-serialization-in-android/

I'm going to go through the process of serializing and deserializing an object.

What this means is that we're going to convert an object into an array of bytes, which can easily be moved around or stored (for later use). And for deserialization we just take those bytes and convert them back into an Object.

The first one we have below is the serialization method, which just takes in a generic Object.


  public static byte[] serializeObject(Object o) {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {
      ObjectOutput out = new ObjectOutputStream(bos);
      out.writeObject(o);
      out.close();

      // Get the bytes of the serialized object
      byte[] buf = bos.toByteArray();

      return buf;
    } catch(IOException ioe) {
      Log.e("serializeObject", "error", ioe);

      return null;
    }
  }

The second one is the deserialization method, which takes in an array of bytes;


  public static Object deserializeObject(byte[] b) {
    try {
      ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(b));
      Object object = in.readObject();
      in.close();

      return object;
    } catch(ClassNotFoundException cnfe) {
      Log.e("deserializeObject", "class not found error", cnfe);

      return null;
    } catch(IOException ioe) {
      Log.e("deserializeObject", "io error", ioe);

      return null;
    }
  }

If you're wondering how to use these, well here is an example.


  public class Bla implements Serializable {
    public String blaDate;
    public String blaText;
  }
 
  Bla bla = new Bla();
 
  // assuming that both those serialize and deserialize methods are under the SerializerClass
  byte[] blaBytes = SerializerClass.serializeObject(bla);
 
  Bla deserializedBla = (Bla) SerializerClass.deserializeObject(blaBytes);

You've probably noticed that I implemented Serializable - you need this in order to serialize an object. Some of the built in objects already have this implemented - for example the ArrayList object.

When deserializing you need to cast it back to what the object was, since it's returning it as a generic Object - hence the (Bla).
Anyways, hope this helped someone, and if you noticed any mistakes, please let me know.

Thursday, November 22, 2012

Resource Folder Content ?


Check this link http://developer.android.com/training/multiscreen/index.html
http://developer.android.com/guide/practices/screens_support.html
http://developer.android.com/guide/practices/ui_guidelines/icon_design.html
http://developer.android.com/guide/topics/resources/more-resources.html#Dimension
http://android-ui-utils.googlecode.com/hg/asset-studio/dist/index.html
http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html
http://jayxie.com/mirrors/android-sdk/resources/samples/MultiResolution/index.html
http://tools.android.com/recent/dealingwithdependenciesinandroidprojects
http://developer.android.com/about/dashboards/index.html

Taken from Here

In the /res folder you can have:

anim/ - XML files that define tween animations

color/ - XML files that define a state list of colors.

drawable/ - Bitmap files / Nine-Patches (re-sizable bitmaps) / State lists / Shapes / Animation drawables / Other drawables

layout/ - XML files that define a user interface layout.

menu/ - XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.

raw/ - Arbitrary files to save in their raw form.

values/ - XML files that contain simple values, such as strings, integers, and colors.

arrays.xml for resource arrays (typed arrays).
colors.xml for color values
dimens.xml for dimension values.
strings.xml for string values.
styles.xml for styles.
xml/ - Arbitrary XML files

Also see Accessing Alternative Resources for more specific device configurations (locale, dpi, size, aspect, orientation, etc



Also We can have value folder like : -

res/values-ldpi/dimens.xml
res/values-mdpi/dimens.xml
res/values-hdpi/dimens.xml
res/values-sw720dp/dimens.xml

Drawable folders can be of : -

xhdpi: 720x1280
large-hdpi: 640x960
hdpi: 480x640
mdpi: 320x480
ldpi: 240x320

res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)



The size ratios should match the nominal pixel densities as Android defines them:

ldpi - 120 pixels/inch; dpi scale = .75 (4 dpi = 3 pixels)
mdpi - 160 pixels/inch; dpi scale = 1 (1 dpi = 1 pixel)
hdpi - 240 pixels/inch; dpi scale = 1.5 (2 dpi = 3 pixels)
xhdpi - 320 pixels/inch; dpi scale = 2 (1 dpi = 2 pixels)

So if you make your xhdpi images twice the size (in pixels) of the mdpi resources, they will be the same dpi, meaning they will be the same physical size on their respective screens.








Thursday, November 1, 2012

How to show dialog yes/No before leaving the app via Back button ?



private boolean isLastActivity() {
   final ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
    final List<RunningTaskInfo> tasksInfo = am.getRunningTasks(1024);

    final String ourAppPackageName = getPackageName();
    RunningTaskInfo taskInfo;
    final int size = tasksInfo.size();
    for (int i = 0; i < size; i++) {
        taskInfo = tasksInfo.get(i);
        if (ourAppPackageName.equals(taskInfo.baseActivity.getPackageName())) {
            return taskInfo.numActivities == 1;
        }
    }

    return false;
}

You wil also require below permission in manifest....

<uses-permission android:name="android.permission.GET_TASKS" />

Thus in your Activty you can just use the following:

public void onBackPressed() {
    if (isLastActivity()) {
         showDialog(DIALOG_EXIT_CONFIRMATION_ID);
    } else {
         super.onBackPressed(); // this will actually finish the Activity
    }
}

Wednesday, October 17, 2012

List Chart API ?

How to view the android.jar source code in eclipse?



This plugin helps you to add source to android libraries in Eclipse.

In ADT >=8.0.0 you can add Android sources to Android container for all your project with installing the Android source feature using...

http://adt-addons.googlecode.com/svn/trunk/source/com.android.ide.eclipse.source.update/

After downloading the com.android.ide.eclipse.source_16.0.0.201112171909.jar file in plugin folder, unzip it.We will get the below sources for the following API levels:

14 - Android 4.0.1
10 - Android 2.3.4
9 - Android 2.3
8 - Android 2.2
7 - Android 2.1
6 - Android 2.0.1
4 - Android 1.6
3 - Android 1.5

The plugin is about 240 MB size.

Each folder will contain the sources.zip file within it.Copy zip file from "10" folder and paste it into below path of corresponding version...

android-sdk-linux/platform/android-10/"paste here"

i.e sources.zip and android.jar both file will be in same folder.

Now restart you eclipse and browse to android.jar file,now you can view the source code....


How to restart service with AlarmManager ?

Supposed you are running the below service......We just need to register and unregister the alarm,in service lifecycle.



package com.example.differentlayout;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;

class PersistentService extends Service {

private static final String TAG = "PersistentService";

// support persistent of Service
void registerRestartAlarm() {
Log.d(TAG, "registerRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
long firstTime = SystemClock.elapsedRealtime();
firstTime += 10 * 1000; // 10 seconds after the alarm event occurs
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime,10 * 1000, sender);
}

void unregisterRestartAlarm() {
Log.d(TAG, "unregisterRestartAlarm");
Intent intent = new Intent(PersistentService.this, RestartService.class);
intent.setAction(RestartService.ACTION_RESTART_PERSISTENTSERVICE);
PendingIntent sender = PendingIntent.getBroadcast(PersistentService.this, 0, intent, 0);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.cancel(sender);
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onCreate() {
unregisterRestartAlarm();
super.onCreate();
}

@Override
public void onDestroy() {
registerRestartAlarm();
super.onDestroy();
}

}



Write the receiver which wake ups our above service....


package com.example.differentlayout;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class RestartService extends BroadcastReceiver {
 public static final String ACTION_RESTART_PERSISTENTSERVICE = "ACTION.Restart.PersistentService";

@Override
 public void onReceive(Context context, Intent intent) {
   Log.d("RestartService", "RestartService called!@!@@@@@#$@$@#$@#$@#");
   if(intent.getAction().equals(ACTION_RESTART_PERSISTENTSERVICE)) {
     Intent i = new Intent(context, PersistentService.class);
     context.startService(i);
 }
}
}


In manifest file don't forgot to mention the RestartService as remote.....


<receiver android:name="RestartService" android:process=":remote">
       <intent-filter>
                       <action android:name="ACTION.Restart.PersistentService"></action>
        </intent-filter>
</receiver>


Commonly Utilized intents ?

Following are the list of intent call which is called mostly....


//Offset / Web page
Uri uri = Uri.parse("http://www.google.com");
Intent it = new Intent(Intent.ACTION_VIEW,uri);
startActivity(it);

// Google Offset
Uri uri = Uri.parse("geo:38.899533,-77.036476");
Intent it = new Intent(Intent.Action_VIEW,uri);
startActivity(it);

// Google pathfinding offset
//http://maps.google.com/maps?f=d&saddr = source address & daddr = destination address & hl = en
Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=출발지주소&daddr=도착지주소&hl=ko");
Intent it = new Intent(Intent.ACTION_VIEW,URI);
startActivity(it);

// Dialing
Uri uri = Uri.parse("tel:xxxxxx");
Intent it = new Intent(Intent.ACTION_DIAL, uri);
startActivity(it);

Uri uri = Uri.parse("tel.xxxxxx");
Intent it = new Intent(Intent.ACTION_CALL,uri);
//  <uses-permission id="android.permission.CALL_PHONE" />

// SMS/MMS Sent
Intent it = new Intent(Intent.ACTION_VIEW);
it.putExtra("sms_body", "The SMS text");
it.setType("vnd.android-dir/mms-sms");
startActivity(it);

// SMS Sent
Uri uri = Uri.parse("smsto:0800000123");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
it.putExtra("sms_body", "The SMS text");
sms.putExtra("exit_on_sent", true);
startActivity(it);

// MMS Sent
Uri uri = Uri.parse("content://media/external/images/media/23");
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra("sms_body", "some text");
it.putExtra(Intent.EXTRA_STREAM, uri);
it.setType("image/png");
startActivity(it);

// Send an email
Uri uri = Uri.parse("mailto:xxx@abc.com");
Intent it = new Intent(Intent.ACTION_SENDTO, uri);
startActivity(it);

Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.setType("text/plain");
startActivity(Intent.createChooser(it, "Choose Email Client"));

Intent it = new Intent(Intent.ACTION_SEND);
String[] tos = {"me@abc.com"};
String[] ccs = {"you@abc.com"};
it.putExtra(Intent.EXTRA_EMAIL, tos);
it.putExtra(Intent.EXTRA_CC, ccs);
it.putExtra(Intent.EXTRA_TEXT, "The email body text");
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.setType("message/rfc822");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// extra Add
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// Play media files
Intent it = new Intent(Intent.ACTION_VIEW);
Uri uri = Uri.parse("file:///sdcard/song.mp3");
it.setDataAndType(uri, "audio/mp3");
startActivity(it);

Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

// Removing the installed application
Uri uri = Uri.fromParts("package", strPackageName, null);
Intent it = new Intent(Intent.ACTION_DELETE, uri);
startActivity(it);

// APK-To remove the file
Uri uninstallUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_DELETE, uninstallUri);

// APK Install files
Uri installUri = Uri.fromParts("package", "xxx", null);
returnIt = new Intent(Intent.ACTION_PACKAGE_ADDED, installUri);

// Playing a music file
Uri playUri = Uri.parse("file:///sdcard/download/everything.mp3");
returnIt = new Intent(Intent.ACTION_VIEW, playUri);

//Add attachments to E-mail
Intent it = new Intent(Intent.ACTION_SEND);
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/eoe.mp3");
sendIntent.setType("audio/mp3");
startActivity(Intent.createChooser(it, "Choose Email Client"));

// Search application from the Market
Uri uri = Uri.parse("market://search?q=pname:pkg_name");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// The package name, you must enter the full package name of the application.

// Market Application Details screen
//market://details?id=application ID
Uri uri = Uri.parse("market://details?id=어플리케이션아이디");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
// ID of the publishing market if you look at the URL to the site of application after the selection.

// Google Search
Intent intent = new Intent();
intent.setAction(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY,"searchString")
startActivity(intent);

//Sending attachement through email Intent
Intent emailIntent = new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, "emailId");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, "Subject");
emailIntent.setType("text/*");
emailIntent.putExtra(Intent.EXTRA_TEXT, "Body Messgae"+ "\n\nPlease Find attached log File");
emailIntent.setType("text/*");
File path = new File("sdcard/filePath");
emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(path));
emailIntent.putExtra(Intent.EXTRA_TEXT,Html.fromHtml("\nStep Email Launch:"));
emailIntent.setType("text/*");
// emailIntent.setType("message/rfc822");
// emailIntent.setType("message/rfc822");
// emailIntent.setType("text/xml");
// emailIntent.setType("text/html");
// emailIntent.setType("text/plain");
emailIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
emailIntent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(emailIntent);

How to manage Dynamic Height of SlidingDrawer in android ?

Create the custom layout into the main.xml....


<?xml version="1.0" encoding="utf-8"?>
<FrameLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <ViewFlipper
        android:id="@+id/ImageFlipper"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <ImageView
            android:id="@+id/imageView0"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:scaleType="centerCrop" />
    </ViewFlipper>

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="bottom"
        android:orientation="vertical" >

        <com.example.differentlayout.WrappingSlidingDrawer
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:content="@+id/content"
            android:handle="@+id/handle" >

            <!-- Sliding drawer handle -->

            <ImageView
                android:id="@+id/infoDrawerHandle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@+drawable/info_handle_closed" />

            <!--
        Sliding drawer content: a scroller containing a group of text views
        laid out in a LinearLayout
            -->

            <ScrollView
                android:id="@+id/infoDrawerContent"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:background="@+drawable/info_background"
                android:fillViewport="false" >

                <LinearLayout
                    android:id="@+id/infoDrawerContent"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:orientation="vertical"
                    android:paddingRight="5dip" >

                    <TextView
                        android:id="@+id/infoTitle"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffffff"
                        android:textSize="16dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoCreator"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip"
                        android:textStyle="italic" />

                    <TextView
                        android:id="@+id/infoDescription"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:paddingBottom="10dip"
                        android:textColor="#ffffff"
                        android:textSize="14dip" />

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="@+string/heading_pro_tip"
                        android:textColor="#ffcc00"
                        android:textSize="14dip"
                        android:textStyle="bold" />

                    <TextView
                        android:id="@+id/infoProTip"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:textColor="#ffcc00"
                        android:textSize="14dip" />
                </LinearLayout>
            </ScrollView>
        </com.example.differentlayout.WrappingSlidingDrawer>
    </LinearLayout>

</FrameLayout>



Then create the class for WrappingSlidingDrawer.java......
It will manage the height of the drawer based on the number of elements binded in adapter........


package com.example.differentlayout;

import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.SlidingDrawer;

public class WrappingSlidingDrawer extends SlidingDrawer {

    public WrappingSlidingDrawer(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    public WrappingSlidingDrawer(Context context, AttributeSet attrs) {
        super(context, attrs);

        int orientation = attrs.getAttributeIntValue("android", "orientation", ORIENTATION_VERTICAL);
        mTopOffset = attrs.getAttributeIntValue("android", "topOffset", 0);
        mVertical = (orientation == SlidingDrawer.ORIENTATION_VERTICAL);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize =  MeasureSpec.getSize(widthMeasureSpec);

        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize =  MeasureSpec.getSize(heightMeasureSpec);

        if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
            throw new RuntimeException("SlidingDrawer cannot have UNSPECIFIED dimensions");
        }

        final View handle = getHandle();
        final View content = getContent();
        measureChild(handle, widthMeasureSpec, heightMeasureSpec);

        if (mVertical) {
            int height = heightSpecSize - handle.getMeasuredHeight() - mTopOffset;
            content.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(height, heightSpecMode));
            heightSpecSize = handle.getMeasuredHeight() + mTopOffset + content.getMeasuredHeight();
            widthSpecSize = content.getMeasuredWidth();
            if (handle.getMeasuredWidth() > widthSpecSize) widthSpecSize = handle.getMeasuredWidth();
        }
        else {
            int width = widthSpecSize - handle.getMeasuredWidth() - mTopOffset;
            getContent().measure(MeasureSpec.makeMeasureSpec(width, widthSpecMode), heightMeasureSpec);
            widthSpecSize = handle.getMeasuredWidth() + mTopOffset + content.getMeasuredWidth();
            heightSpecSize = content.getMeasuredHeight();
            if (handle.getMeasuredHeight() > heightSpecSize) heightSpecSize = handle.getMeasuredHeight();
        }

        setMeasuredDimension(widthSpecSize, heightSpecSize);
    }

    private boolean mVertical;
    private int mTopOffset;
}

Saturday, September 1, 2012

Tower of Hanoi program in Java ?



The towers of hanoi is a popular problem. You have three poles and n disks which fit on the poles. All disks have different size. They are stacked on pole 1 in the orders of their size. The largest disk is on the bottom, the smallest is on the top.

The task is to move all disk from pole 1 to pole 3 under the following restrictions.

Only one disk can be moved

A larger disk can not be placed on a smaller disk.

The recursive algorithm works like the following: move n-1 disk from the starting pole to the pole which is neither start nor target (intermediate), move disk n to the target pole and then move n-1 disk from the intermediate pole to the target pole. The n-1 disks are moved recursively.


public class MinimumWindow {

public static void move(int n, int startPole, int endPole) {
if (n == 0) {
return;
}
int intermediatePole = 6 - startPole - endPole;
move(n - 1, startPole, intermediatePole);
System.out.println("Move " + n + " from " + startPole + " to "
+ endPole);
move(n - 1, intermediatePole, endPole);
}

public static void main(String[] args) {
move(5, 1, 3);
}

}


Below is the output...

Move 1 from 1 to 3
Move 2 from 1 to 2
Move 1 from 3 to 2
Move 3 from 1 to 3
Move 1 from 2 to 1
Move 2 from 2 to 3
Move 1 from 1 to 3

Prime Factorization in Java ?


import java.util.ArrayList;
import java.util.List;

public class PrimeFactorization {

public static List<Integer> primeFactors(int numbers) {
int n = numbers;
List<Integer> factors = new ArrayList<Integer>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
if (n > 1) {
factors.add(n);
}
return factors;
}

public static void main(String[] args) {
for (Integer integer : primeFactors(44)) {
System.out.println(integer);
}

System.out.println("---------");

for (Integer integer : primeFactors(3)) {
System.out.println(integer);
}
}

}

Below is the Output....

2
2
11
---------
3

Determine Prime number with the sieve of Eratosthenes in Java in java ?


import java.util.ArrayList;
import java.util.List;

public class DeterminePrime{

public static List<Integer> calcPrimeNumbers(int n) {
boolean[] isPrimeNumber = new boolean[n + 1]; // boolean defaults to
// false
List<Integer> primes = new ArrayList<Integer>();
for (int i = 2; i < n; i++) {
isPrimeNumber[i] = true;
}
for (int i = 2; i < n; i++) {
if (isPrimeNumber[i]) {
primes.add(i);
// Now mark the multiple of i as non-prime number
for (int j = i; j * i <= n; j++) {
isPrimeNumber[i * j] = false;
}
}

}

return primes;
}

public static void main(String[] args) {
List<Integer> calcPrimeNumbers = calcPrimeNumbers(21);
for (Integer integer : calcPrimeNumbers) {
System.out.println(integer);
}
System.out.println("Prime counting function (Pie(N)) : "
+ calcPrimeNumbers.size());
}

}


Below is the output...

2
3
5
7
11
13
17
19
Prime counting function (Pie(N)) : 8

Euclid's Greatest Common divisor alogorithmn ?


public class EuclidGCdAlgorithmn {

public static int gcd(int p, int q) {

if (q == 0) {
return p;
}

return gcd(q, p % q);
}

// Test enable assert check via -ea as a VM argument

public static void main(String[] args) {
System.out.print(" "+gcd(4, 16));

System.out.print(" "+gcd(16, 4));

System.out.print(" "+gcd(15, 60));
System.out.print(" "+gcd(15, 65));

System.out.print(" "+gcd(1052, 52));
}

}


Below is the output....

 4
 4
 15
 5
 4

Odd even Transposition algorithmn in Java ?



public class OddEvenTransposition {

public static void main(String a[]) {

int i;
int array[] = { 12, 9, 4, 99, 120, 1, 3, 10, 13 };

System.out.println(" Odd Even Transposition Sort\n\n");

System.out.println("Values Before the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

System.out.println();

odd_even_srt(array, array.length);

System.out.print("Values after the sort:\n");

for (i = 0; i < array.length; i++){
System.out.print(array[i] + "  ");
}

}

public static void odd_even_srt(int array[], int n) {
for (int i = 0; i < n / 2; i++) {
for (int j = 0; j + 1 < n; j += 2)
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
for (int j = 1; j + 1 < array.length; j += 2)
if (array[j] > array[j + 1]) {
int T = array[j];
array[j] = array[j + 1];
array[j + 1] = T;
}
}
}
}


Below is the output....

Values Before the sort:

12  9  4  99  120  1  3  10  13  

Values after the sort:

1  3  4  9  10  12  13  99  120