How to setUp a repeating Alarm in Android?

Hello everyone…….

Today I am going to show you how to set up a repeating alarm in android. In the previous post I showed you how to set up a simple alarm. An in this post I will show you how to set Up a Repeating Alarm.

For this you need an extra class just to notify that the repeating alarm is called.
Let’a look at the java code.

package pack.coderzheaven;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AlarmDemo extends Activity {
	Toast mToast;
	  @Override
		protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);

	        Button button = (Button)findViewById(R.id.one_shot);
	        button.setOnClickListener(mOneShotListener);
	        button = (Button)findViewById(R.id.start_repeating);
	        button.setOnClickListener(mStartRepeatingListener);
	        button = (Button)findViewById(R.id.stop_repeating);
	        button.setOnClickListener(mStopRepeatingListener);
	    }

	    private OnClickListener mOneShotListener = new OnClickListener() {
	        public void onClick(View v) {

	            Intent intent = new Intent(AlarmDemo.this, MyAlarmReceiver.class);
	            PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this,
	                    0, intent, 0);

	            // We want the alarm to go off 10 seconds from now.
	            Calendar calendar = Calendar.getInstance();
	            calendar.setTimeInMillis(System.currentTimeMillis());
	            calendar.add(Calendar.SECOND, 10);

	            // Schedule the alarm!
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

	            // Tell the user about what we did.
	            if (mToast != null) {
	                mToast.cancel();
	            }
	            mToast = Toast.makeText(AlarmDemo.this,"Alarm Started",
	                    Toast.LENGTH_LONG);
	            mToast.show();
	        }
	    };

	    private OnClickListener mStartRepeatingListener = new OnClickListener() {
	        public void onClick(View v) {

	            Intent intent = new Intent(AlarmDemo.this, RepeatingAlarm.class);
	            PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this,
	                    0, intent, 0);

	            // We want the alarm to go off 5 seconds from now.
	            long firstTime = SystemClock.elapsedRealtime();
	            firstTime += 5*1000;

	            // Schedule the alarm!
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
	                            firstTime, 5*1000, sender);

	            // Tell the user about what we did.
	            if (mToast != null) {
	                mToast.cancel();
	            }
	            mToast = Toast.makeText(AlarmDemo.this, "Rescheduled",
	                    Toast.LENGTH_LONG);
	            mToast.show();
	        }
	    };

	    private OnClickListener mStopRepeatingListener = new OnClickListener() {
	        public void onClick(View v) {
	            // Create the same intent, and thus a matching IntentSender, for
	            // the one that was scheduled.
	            Intent intent = new Intent(AlarmDemo.this, RepeatingAlarm.class);
	            PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this,
	                    0, intent, 0);

	            // And cancel the alarm.
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.cancel(sender);

	            // Tell the user about what we did.
	            if (mToast != null) {
	                mToast.cancel();
	            }
	            mToast = Toast.makeText(AlarmDemo.this,"Repeating Alarm Unscheduled.",
	                    Toast.LENGTH_LONG);
	            mToast.show();
	        }
	    };
	}

Here we have three buttons one to set up a simple Alarm that is a one shot alarm and other button is for starting a repeating alarm and the third button for stopping the repeating alarm.

Now let’s see how the layout looks like.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="Alarm Demo from CoderzHeaven"/>

    <Button android:id="@+id/one_shot"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Start Alarm">
        <requestFocus />
    </Button>

    <Button android:id="@+id/start_repeating"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Start Repeating Alarm" />

     <Button android:id="@+id/stop_repeating"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Stop Repeating Alarm" />

</LinearLayout>

Now create a new class named “RepeatingAlarm.java” and copy this code into it. This class receives the repeating alarm intent.
The “MyAlarmReceiver.java” file is included in this post. Please copy that also

package pack.coderzheaven;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class RepeatingAlarm extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context,"Repeating Alarm Received", Toast.LENGTH_SHORT).show();
    }
}

Here is the AndroidManifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
	<receiver android:name=".MyAlarmReceiver" android:process=":remote" />
	<receiver android:name=".RepeatingAlarm" android:process=":remote" />
    </application>
</manifest>

Now run it and see the result.



How to use Alarm Service in android?

Today in this tutorial I will show you how to use AlarmService in android.
For this you have to first create a project named AlarmDemo and copy this code into it.

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class AlarmDemo extends Activity {
	Toast mToast;
	  @Override
		protected void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.main);

	        Button button = (Button)findViewById(R.id.one_shot);
	        button.setOnClickListener(mOneShotListener);

	    }

	    private OnClickListener mOneShotListener = new OnClickListener() {
	        public void onClick(View v) {

	            Intent intent = new Intent(AlarmDemo.this, MyAlarmReceiver.class);
	            PendingIntent sender = PendingIntent.getBroadcast(AlarmDemo.this,
	                    0, intent, 0);

	            // We want the alarm to go off 10 seconds from now.
	            Calendar calendar = Calendar.getInstance();
	            calendar.setTimeInMillis(System.currentTimeMillis());
	            calendar.add(Calendar.SECOND, 10);

	            // Schedule the alarm!
	            AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE);
	            am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

	            // Tell the user about what we did.
	            if (mToast != null) {
	                mToast.cancel();
	            }
	            mToast = Toast.makeText(AlarmDemo.this,"Alarm Started",
	                    Toast.LENGTH_LONG);
	            mToast.show();
	        }
	    };
}

We use the AlarmManager class for creating an Alarm service.
Here we are setting the time to 10 seconds so after 10 seconds a Toast pops up.
For receiving the Broadcast we have to create a class the extends the BroadcastReceiver class on which the onReceive function gets called when the service ends.
So create a class named “MyAlarmReceiver.java” and copy this code into it.

package pack.coderzheaven;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;

public class MyAlarmReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent)
    {
        Toast.makeText(context, "Alarm Received after 10 seconds.", Toast.LENGTH_SHORT).show();
    }
}

This is the layout file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:padding="4dip"
    android:gravity="center_horizontal"
    android:layout_width="fill_parent" android:layout_height="fill_parent">

    <TextView
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="0"
        android:paddingBottom="4dip"
        android:text="Alarm Demo"/>

    <Button android:id="@+id/one_shot"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:text="Start Alarm">
        <requestFocus />
    </Button>
</LinearLayout>

This class will be called after 10 seconds.

Now the important thing for receiving the Brodcast events you have to register with the AndroidManifest.

This is the AndroidManifest file for the above code

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AlarmDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
	<receiver android:name=".MyAlarmReceiver" android:process=":remote" />
    </application>
</manifest>

Alarm Demo

Alarm Demo


Alarm Demo

Alarm Demo

How to call a function after fixed time interval in Cocos2D ?

Hi,

For calling a function after a definite time interval in Cocos2D, use the following code.


[self performSelector:@selector(yourFunction) withObject:nil afterDelay:7.0];

this will call the function ‘yourFunction’ after 7 seconds. :)

How to add a custom font with size in a UITextView ?

Hi,

For adding a custom font in a UITextView, use the following code.


IBOutlet UITextView *myTextField;

[myTextField setFont:[UIFont fontWithName:@"Helvetica" size:20]];


:)

How to Show Cocos2D Particle Effects Repeatedly ?

Hi,

For showing particle effects repeatedly in Cocos2D, use the sample code.

CCParticleSystemQuad *yourParticleEffect = [CCParticleSystemQuad particleWithFile:@"yourEffect.plist"];

[self addChild:yourParticleEffect z:5];

This will show the effect ‘yourEffect’ repeatedly in your game. :)

Android phpmySQL connection redone.

Hi all..
Most of our visitors had problem with one of our previous post on Android-php connection. So here I am posting another simple example to connect with a php file. Here I am simply putting an echo in the php file which ehoes back the data from the android side.
Here are the things you need to remember.

1. Make sure your server is running(Xampp or Wampp).
2. Make sure you give right path of your php file inside your android program.
3. Make sure you have put the internet permission in the android manifest file.
4. And the last one the android side and php side posting variables should be the same.

Here is the android main java file contents.

package pack.coderzheaven;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidPHPConnectionDemo extends Activity {
	Button b;
    EditText et;
    TextView tv;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    List<NameValuePair> nameValuePairs;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        b = (Button)findViewById(R.id.Button01);
        et= (EditText)findViewById(R.id.EditText01);
        tv= (TextView)findViewById(R.id.tv);
 
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	
            	final ProgressDialog p = new ProgressDialog(v.getContext()).show(v.getContext(),"Waiting for Server", "Accessing Server");
            	Thread thread = new Thread()
            	{
            	    @Override
            	    public void run() {
            	    	 try{
                         	
                             httpclient=new DefaultHttpClient();
                             httppost= new HttpPost("http://10.0.0.2/my_folder_inside_htdocs/connection.php"); // make sure the url is correct.
                             //add your data
                             nameValuePairs = new ArrayList<NameValuePair>(1);
                             // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
                             nameValuePairs.add(new BasicNameValuePair("Edittext_value",et.getText().toString().trim()));  // $Edittext_value = $_POST['Edittext_value'];
                             httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                             //Execute HTTP Post Request
                             response=httpclient.execute(httppost);
                             
                             ResponseHandler<String> responseHandler = new BasicResponseHandler();
                             final String response = httpclient.execute(httppost, responseHandler);
                             System.out.println("Response : " + response);
                             runOnUiThread(new Runnable() {
                            	    public void run() {
                            	    	p.dismiss();
                            	    	 tv.setText("Response from PHP : " + response);
                            	    }
                            	});
                            
                         }catch(Exception e){
                        	 
                        	 runOnUiThread(new Runnable() {
                         	    public void run() {
                         	    	p.dismiss();
                         	    }
                         	});
                             System.out.println("Exception : " + e.getMessage());
                         }
            	    }
            	};

            	thread.start();
            	
               
            }
        });
    }
}

Here is the main.xml the layout for the above file.

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

<EditText
	android:text=""
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content"
	android:singleLine="true">
</EditText>
<Button
	android:text="Send to php side"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
<TextView
	android:id="@+id/tv"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text=""
    />
</LinearLayout>

Here is the android manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
      <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidPHPConnectionDemo"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Here is the PHP side. I am simply echoing back the value send from the android side.
connection.php

$val = $_POST['Edittext_value'];
echo $val;

here I have a Edittext on my android side and after entering something in it and hitting the button to send, the textbox data will be send to the server and the server echoes back the same data.
My php file is saved in a folder named “my_folder_inside_htdocs” and named “connection.php”
I am working in localhost so it is given as “10.0.2.2″ please replace your domain name here.
However you have a MySQl-connection in that php file and fetch some data from the database and echo back from the php side. You will get that data as string in the php side in this line

ResponseHandler<String> responseHandler = new BasicResponseHandler();
					String response = httpclient.execute(httppost, responseHandler);
					System.out.println("Response : " + response); </blockquote>

You can manipulate this string as you want.
Any problem with this post please leave your comments.If this post was useful then click on the +1 button on top to share it across the web.
Please leave your valuable comments.

Here is another more detailed explanation.

How to create Simple Login form using php in android? – Connect php with android.

Change TabBar text and Image Dynamically in android.

In one of the previous example I have showed you how to use the Tabbars. In this example I will show you how to change the Tabbar name and image when you click the tab.

Copy the same example from this post and change the tabbars.java to this.
After running it click on the tabbar to see the text changing.

package com.coderzheaven;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TabHost;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.TabHost.TabSpec;

public class tabbar extends TabActivity {
	TabWidget tw;
	TabHost tabHost;
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        /** TabHost will have Tabs */
        final TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);

        /** TabSpec used to create a new tab.
         * By using TabSpec only we can able to setContent to the tab.
         * By using TabSpec setIndicator() we can set name to tab. */

        /** tid1 is firstTabSpec Id. Its used to access outside. */
        TabSpec firstTabSpec = tabHost.newTabSpec("tab_id1");
        TabSpec secondTabSpec = tabHost.newTabSpec("tab_id2");
        TabSpec thirdTabSpec = tabHost.newTabSpec("tab_id3");

        /** TabSpec setIndicator() is used to set name for the tab. */
        /** TabSpec setContent() is used to set content for a particular tab. */
        firstTabSpec.setIndicator("First").setContent(new Intent(this,FirstTab.class));
        secondTabSpec.setIndicator("Second ").setContent(new Intent(this,SecondTab.class));
        thirdTabSpec.setIndicator("Third").setContent(new Intent(this,ThirdTab.class));

        /** Add tabSpec to the TabHost to display. */
        tabHost.addTab(firstTabSpec);
        tabHost.addTab(secondTabSpec);
        tabHost.addTab(thirdTabSpec);

        tw = getTabWidget();
        View tab1View = tw.getChildAt(0);
        tab1View.setId(1);

        View tab2View = tw.getChildAt(1);
        tab2View.setId(2);

        View tab3View = tw.getChildAt(2);
        tab3View.setId(3);

        tab1View.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				((TextView)tabHost.getTabWidget().getChildAt(v.getId()-1).findViewById(android.R.id.title)).setText("my Tab " + v.getId());
			}
		});

        tab2View.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				((TextView)tabHost.getTabWidget().getChildAt(v.getId()-1).findViewById(android.R.id.title)).setText("my Tab " + v.getId());
			}
		});

        tab3View.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				((TextView)tabHost.getTabWidget().getChildAt(v.getId()-1).findViewById(android.R.id.title)).setText("my Tab " + v.getId());
			}
		});
    }

}

Please leave your valuable comments.

How to avoid OutOfMemory Exception in android- Second Method?

In the previous tutorial I showed you one method to avoid OutOfMemory Exception in android.
And In this tutorial I will show you another method.
The reduceImageSize function in this code reduces the image to the desired size you want.
Create a fresh project and copy this code into it.
How to put images inside the emulator is shown in this example.

This example shows how to get an image from inside the gallery.
And this example show how to copy images from gallery to another location in SDCARD.

Give your requred size in the varisble REQUIRED_SIZE to change according to your wish.

package pack.coderzheaven;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class GetImageActivity extends Activity {

	private static final int SELECT_PICTURE = 1;

	private String selectedImagePath;
	private ImageView img;

	public void onCreate(Bundle savedInstanceState) {
	    super.onCreate(savedInstanceState);
	    setContentView(R.layout.main);

	    img = (ImageView)findViewById(R.id.ImageView01);

	    ((Button) findViewById(R.id.Button01))
	            .setOnClickListener(new OnClickListener() {
	                public void onClick(View arg0) {
	                    Intent intent = new Intent();
	                    intent.setType("image/*");
	                    intent.setAction(Intent.ACTION_GET_CONTENT);
	                    startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	                }
	            });
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
	    if (resultCode == RESULT_OK) {
	        if (requestCode == SELECT_PICTURE) {
	            Uri selectedImageUri = data.getData();
	            selectedImagePath = getPath(selectedImageUri);
	            System.out.println("Image Path : " + selectedImagePath);
	            Bitmap bm = reduceImageSize(selectedImagePath);
	            if(bm != null)
	            	img.setImageBitmap(bm);
	        }
	    }
	}

	public String getPath(Uri uri) {
	    String[] projection = { MediaStore.Images.Media.DATA };
	    Cursor cursor = managedQuery(uri, projection, null, null, null);
	    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
	    cursor.moveToFirst();
	    return cursor.getString(column_index);
	}

	public Bitmap reduceImageSize(String mSelectedImagePath){

	    	Bitmap m = null;
		    try {
	      	  File f = new File(mSelectedImagePath);

	      	//Decode image size
	          BitmapFactory.Options o = new BitmapFactory.Options();
	          o.inJustDecodeBounds = true;
	          BitmapFactory.decodeStream(new FileInputStream(f),null,o);

	          //The new size we want to scale to
	          final int REQUIRED_SIZE=150;

	          //Find the correct scale value. It should be the power of 2.
	          int width_tmp=o.outWidth, height_tmp=o.outHeight;
	          int scale=1;
	          while(true){
	              if(width_tmp/2 < REQUIRED_SIZE || height_tmp/2 < REQUIRED_SIZE)
	                  break;
	              width_tmp/=2;
	              height_tmp/=2;
	              scale*=2;
	          }

	          //Decode with inSampleSize
	          BitmapFactory.Options o2 = new BitmapFactory.Options();
	          o2.inSampleSize=scale;
	          m = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
	      } catch (FileNotFoundException e) {
	    	  Toast.makeText(getApplicationContext(), "Image File not found in your phone. Please select another image.", Toast.LENGTH_LONG).show();
	      }
	      return  m;
	}
}


Click the +1 button on the top to share it with your friends and please leave your valuable comments also.

How to avoid OutOfMemory Exception in android?

Hello all..

The OutofMemory exception is a common exception in android when you select an image from a gallery or load Big Images in android.
There are different methods to solve this problem.
Today I will show you one of the method to solve this problem.

The method I am going to explain here is to create a virtual device with more

1. RAM
2. Heap Size
3. SDCard support.

The main reason for this problem is that if the virtual device you created has less configuration, then it will not allocate more heap size for bigger images.
In this tutorial I will show you how to create a Virtual device with higher configuration.

Follow these steps

1. Open Eclipse -> Window -> Android SDK and AVD Manager.
2. Click new -> Give a Virtual device name and other details like Target and SDCARD size.
3. In the Hardware tab below click on new
4. See the options in the combobox.
5. Give appropriate values after selecting values from the Box after clicking ok. Try to give bigger values than default


See the figure below.




In the coming posts I will explain another two methods to avoid this exception. Keep in touch.

Click the +1 button on the top to share it with your friends and please leave your valuable comments also.

How to create a transparent activity in android?

The following example shows a simple method to make an activity transparent in android.

For this first create a fresh project and copy this java code into it.

package pack.coderzheaven;

import android.app.Activity;
import android.os.Bundle;

public class TranslucentActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

Now the main layout file main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:textColor="@drawable/red"
    android:textStyle="bold"
    />
<Button
	android:text="This is Translucent Activity Demo From CoderzHeaven"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content"
	android:textColor="@drawable/red"
    android:textStyle="bold">
</Button>
</LinearLayout>

OK Now here is the style that has to be applied to make the activity transparent.
create a file named style.xml inside res/values folder and copy this code into it.

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.Transparent" parent="android:Theme">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
  </style>
</resources>

Now where to apply this theme. It is applied in the AndroidManifest.xml
This file is shown below.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="pack.coderzheaven"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".TranslucentActivity"
        		  android:theme="@style/Theme.Transparent"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Check this line in the manifest where this style is applied.

android:theme=”@style/Theme.Transparent”

The appname and different colors are in the strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">TranslucentActivity! From Coderzheaven</string>
    <string name="app_name">TranslucentActivity</string>
    <drawable name="white">#ffffff</drawable>
	<drawable name="black">#000000</drawable>
	<drawable name="blue">#2554C7</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="orange">#ff9900</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
	<string name="select_Category">Select Category</string>
	<drawable name="darkgrey">#606060</drawable>
</resources>

Change the color as you want.

translucentDemo

translucentDemo

Click the +1 button on top to share it with your friends and please leave your valuable comments also.

How to set your Android phone in Silent Mode or Vibrate Mode or Normal Mode programatically?

First create an instance of the AudioManager Class using which you can set the phone in Normal, Silent and Vibration Mode.

AudioManager audio_mngr = (AudioManager) getBaseContext().getSystemService(Context.AUDIO_SERVICE);

For setting the phone in Silent mode..

audio_mngr .setRingerMode(AudioManager.RINGER_MODE_SILENT);

For setting the phone in Normal mode..

audio_mngr .setRingerMode(AudioManager.RINGER_MODE_NORMAL);

For setting the phone in Vibrate mode..

audio_mngr .setRingerMode(AudioManager.RINGER_MODE_VIBRATE);

Customizing a spinner in android.

Hello everyone………

You all knew that a spinner or combobox is an inbuilt widget in android. And Like any other widgets spinners are also customizable.
Here is a simple example to customize a spinner. First we will look at the java code.
The getView method is called for each row in the spinner. So with the help of an Layout Inflater you can inflate any layout for each row.
At extreme you can have each layout for each row.

Check these older posts about spinner.

1. How to get a selected Item from a spinner in ANDROID?

2. How to set an item selected in Spinner in ANDROID?

3. How to create a custom ListView in android?

Check out these of ListViews

1. Simplest Lazy Loading ListView Example in Android with data populated from a MySQL database using php.

2. How to add checkboxes and radio buttons to ListView in android? OR How to set single choice items in a ListView in android?

Custom Spinner Demo

Custom Spinner Demo

Custom Spinner Demo

Custom Spinner Demo

Now we will look at the source code

Resources needed.
These are images I am using in this example. Put these images inside the res/drawable folder.

apple.png
bkg.png
coderzheaven.png
google.png
icon.png
microsoft.png
samsung.png
yahoo.png

package         pack.coderzheaven;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class CustomSpinnerDemo extends Activity {
	String[] strings = {"CoderzHeaven","Google",
			"Microsoft", "Apple", "Yahoo","Samsung"};

	String[] subs = {"Heaven of all working codes ","Google sub",
			"Microsoft sub", "Apple sub", "Yahoo sub","Samsung sub"};


	int arr_images[] = { R.drawable.coderzheaven,
						 R.drawable.google, R.drawable.microsoft,
						 R.drawable.apple, R.drawable.yahoo, R.drawable.samsung};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
        mySpinner.setAdapter(new MyAdapter(CustomSpinnerDemo.this, R.layout.row, strings));
    }

    public class MyAdapter extends ArrayAdapter<String>{

    	public MyAdapter(Context context, int textViewResourceId,	String[] objects) {
    		super(context, textViewResourceId, objects);
    	}

    	@Override
    	public View getDropDownView(int position, View convertView,ViewGroup parent) {
    		return getCustomView(position, convertView, parent);
    	}

    	@Override
    	public View getView(int position, View convertView, ViewGroup parent) {
    		return getCustomView(position, convertView, parent);
    	}

    	public View getCustomView(int position, View convertView, ViewGroup parent) {

	    	LayoutInflater inflater=getLayoutInflater();
	    	View row=inflater.inflate(R.layout.row, parent, false);
	    	TextView label=(TextView)row.findViewById(R.id.company);
	    	label.setText(strings[position]);

	    	TextView sub=(TextView)row.findViewById(R.id.sub);
	    	sub.setText(subs[position]);

	    	ImageView icon=(ImageView)row.findViewById(R.id.image);
	    	icon.setImageResource(arr_images[position]);

	    	return row;
    		}
    	}
   }

Now the main.xml which defines the main layout.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
      android:background="@drawable/bkg"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:prompt="@string/prompt"
    />
</LinearLayout>

Now the layout for each row in the spinner.
row.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
	<ImageView
		 android:id="@+id/image"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"
		 android:src="@drawable/icon"/>
	<TextView
		 android:layout_toRightOf="@+id/image"
		 android:padding="3dip"
		 android:layout_marginTop="2dip"
		 android:textColor="@drawable/red"
		 android:textStyle="bold"
		 android:id="@+id/company"
		 android:text="CoderzHeaven"
		 android:layout_marginLeft="5dip"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"/>
	 <TextView
		 android:layout_toRightOf="@+id/image"
		 android:padding="2dip"
		 android:textColor="@drawable/darkgrey"
		 android:layout_marginLeft="5dip"
		 android:id="@+id/sub"
		 android:layout_below="@+id/company"
		 android:text="Heaven of all working codes"
		 android:layout_width="wrap_content"
		 android:layout_height="wrap_content"/>
</RelativeLayout>

Now the strings.xml.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">CustomSpinner Demo from CoderzHeaven!</string>
    <string name="prompt">  Select your Favourite  </string>
    <string name="app_name">CustomSpinner Demo</string>
    <drawable name="white">#ffffff</drawable>
	<drawable name="black">#000000</drawable>
	<drawable name="green">#347C2C</drawable>
	<drawable name="pink">#FF00FF</drawable>
	<drawable name="violet">#a020f0</drawable>
	<drawable name="grey">#778899</drawable>
	<drawable name="red">#C11B17</drawable>
	<drawable name="yellow">#FFFF8C</drawable>
	<drawable name="PowderBlue">#b0e0e6</drawable>
	<drawable name="brown">#2F1700</drawable>
	<drawable name="Hotpink">#7D2252</drawable>
	<string name="select_Category">Select Category</string>
	<drawable name="darkgrey">#606060</drawable>
</resources>

Please click the +1 button on top to share it with your friends and leave your valuable comments also.

How to read webpage contents as a string in Android?

This is a simple example to read a webpage content as a string in android.
This example can also be used to get the response as a string when you make a call to a webpage.
For example a php script. You can have a http script that will call a php script and get the response.
Let the response be a Json String then you can parse the string as JSON and decode it. This code helps you to do this.
Remember that TextView can only display few html tags if displayed as HTML. However I am displaying it as simple text here.

Here is the java code for doing this.

package pack.coderzheaven;

import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ReadWebPage extends Activity {
	private EditText url_text;
	private TextView textView;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		url_text = (EditText) findViewById(R.id.address);
		textView = (TextView) findViewById(R.id.tv);
	}

	public void myButtonClickHandler(View view) {
		switch (view.getId()) {
		case R.id.ReadWebPage:
			try {
				if(!url_text.getText().toString().trim().equalsIgnoreCase("")){
					textView.setText("");
					HttpClient client = new DefaultHttpClient();
					HttpGet request = new HttpGet(url_text.getText().toString());
					// Get the response
					ResponseHandler<String> responseHandler = new BasicResponseHandler();
			        String response_str = client.execute(request, responseHandler);
			        textView.setText(response_str);
				}else{
					Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
				}
			}
			catch (Exception e) {
				System.out.println("Some error occured.");
				textView.setText(e.getMessage());
			}
			break;
		}
	}
}

The Layout main.xml

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

	<EditText android:layout_height="wrap_content"
		android:layout_width="fill_parent"
		android:id="@+id/address"
		android:hint="http://www.google.com"
		android:singleLine="true">
	</EditText>
	<Button android:layout_width="wrap_content"
		android:layout_height="wrap_content"
		android:text="Read Webpage"
		android:id="@+id/ReadWebPage"
		android:onClick="myButtonClickHandler">
	</Button>

	<ScrollView
		android:id="@+id/ScrollView01"
		android:layout_width="wrap_content"
		android:layout_height="wrap_content">
		<TextView
			android:layout_width="fill_parent"
			android:layout_height="fill_parent"
			android:id="@+id/tv"
			android:scrollbars="vertical">
		</TextView>
	</ScrollView>
</LinearLayout>

Note : This code may not work if you working in SDK 3.0 and above where network operation is made to crash if it is one in the main Thread. So do this in a thread to avoid it.

Read Webpage as string Demo

Read Webpage as string Demo


Click the +1 button on top to share it with your friends.
Please leave your valuable comments.

How to read Logcat contents programmatically in Android?

This is an example to read Logcat contents programmatically in Android.
Normal developers won’t need this, but still it is a good thing to know how to do it.

package pack.coderzheaven;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class ReadLogDemo extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	 super.onCreate(savedInstanceState);
    	 setContentView(R.layout.main);
    	    try {
    	      Process process = Runtime.getRuntime().exec("logcat -d");
    	      BufferedReader bufferedReader = new BufferedReader(
    	      new InputStreamReader(process.getInputStream()));

    	      StringBuilder log=new StringBuilder();
    	      String line = "";
    	      while ((line = bufferedReader.readLine()) != null) {
    	        log.append(line);
    	      }
    	      TextView tv = (TextView)findViewById(R.id.textView1);
    	      tv.setText(log.toString());
    	    } catch (IOException e) {
    	    }
    	  }
}
Read Logcat Demo

Read Logcat Demo

if you like the post then click on the plus button to share it with your friends and leave your valuable comments.

How to create a Vanity URL for Google Plus ?

Hi,

For creating a Vanity URL, which is easy to remember, for your Google Plus profiles, follow the steps.

1. Go to your Google Plus profile page
2. Copy your Google Plus ID from the URL (Your ID is the Long Digits between ‘plus.google.com’ & ‘posts’!)
3. Now go to ‘http://gplus.to/’
4. Enter the Nick Name you wanted and the ID in the boxes and Add
5. Done.
:)

Note : gplus.to is not a Google Product.

FREE Google Plus Invitations

Hi,

Anyone who wants a Google Plus Invitation, post your gmail id in the comments. We will sent you an invitation.

Post your feedback as well.
:)

How to invite / transfer all your facebook friends to google plus ?

Hi,

As most of you know already, Facebook won’t allow direct transfer of your Facebook contacts to gmail or to Google Plus. Yup, they are rivals!

But there is a very simple and easy way to transfer all your facebook contacts to gmail and invite all of them via google plus.

Follow the simple and easy steps to invite all of your Facebook friends to Google Plus.

1. Go to your Yahoo Mail (If you don’t have one yet, create one with in 3 minutes!)
2. Go to Contacts and Click Import Contacts
3. Now Click the Facebook Logo and Click ‘OK’ to share with Yahoo (It will import all your Facebook contacts!)
4. Then, Select All Your Contacts
5. Click Actions and Export
6. Export them as Yahoo CSV format.
7. Done. Now you have exported all your Facebook Contacts
8. Open your Gmail and go to Contacts Tab
9. Create a New group, say FaceBook
10. Click ‘FaceBook’ label and then ‘More Actions’
11. Import the Yahoo file you have just exported. (Remember to select ‘FaceBook’ group from dropdown! or any other group)
12. Done. Now all your Facebook friends are in your gmail account.
13. Now go to your Google Plus and click on the circles
14. Google Plus must have already identified them in your ‘Find and Invite’
:)

How to enable new gmail theme similar to google plus ?

Hi,

Gmail now offers us with a new, elegant, clean and pretty Google Plus look to our Gmail. It’s all new look. Just like Google Plus.

Follow these steps to enable new gmail theme similar to google plus in your gmail.

1. Click on the ‘gears’ icon on the top bar (Top Right)
2. Select Mail settings
3. Click the Themes tab
4. Now choose from the two new themes, Preview OR Preview Dense, seen at the bottom
5. Done.
:)

Regex validation for removing invalid characters in Android.

This is a simple example in Android to allow only valid characters to enter in a textBox or EditText.

I am using this regex pattern to allow only valid characters.

“^[a-z_A-Z0-9 ]*$”;

This expression allows only characters from a-z, A-Z and numbers from 0-9 and a ‘ ‘(space) character.
Here is the java code

package pack.coderzheaven;

import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegexDemo extends Activity {
	EditText tbox;
	Button but;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tbox = (EditText)findViewById(R.id.EditText01);
        but  = (Button)findViewById(R.id.Button01);
        but.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isValid(tbox.getText().toString().trim())){
					Toast.makeText(getApplicationContext(), "Text entered is OK.", Toast.LENGTH_SHORT).show();
				}else{
					Toast.makeText(getApplicationContext(), "Oops!! Text entered is Invalid.", Toast.LENGTH_SHORT).show();
				}
			}
		});
    }
    public static boolean isValid(String str)
	{
	    	boolean isValid = false;
	    	String expression = "^[a-z_A-Z0-9 ]*$";
	    	CharSequence inputStr = str;
	    	Pattern pattern = Pattern.compile(expression);
	    	Matcher matcher = pattern.matcher(inputStr);
	    	if(matcher.matches())
	    	{
	    		isValid = true;
	    	}
	    	return isValid;
	 }
}

Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<EditText
	android:text=""
	android:hint="enter some text"
	android:id="@+id/EditText01"
	android:layout_width="fill_parent"
	android:layout_height="wrap_content">
</EditText>
<Button
	android:text="Test"
	android:id="@+id/Button01"
	android:layout_width="wrap_content"
	android:layout_height="wrap_content">
</Button>
</LinearLayout>

Strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Regex invalid character validation from <b>CoderzHeaven.</b></string>
    <string name="app_name">Regex Validation Demo From CoderzHeaven</string>
</resources>
Regex Validation

Regex Validation

Regex Validation

Regex Validation

Binary Search in C Arrays – An Example

Hi,

Want to search for an item in C Arrays, using Binary Search ? Use the following sample of code to search in C Arrays using Binary Search.


#include <stdio.h>
#define SIZE 10

int binarySearch( const int b[], int searchKey, int low, int high );

int main() {
   int arr[ SIZE ];
   int i;
   int key = 5;
   int result = -1;

   for ( i = 0; i < SIZE; i++ ) {
      a[ i ] = 2 * i;
   }

   result = binarySearch( arr, key, 0, SIZE - 1 );

   if ( result != -1 ) {
      printf( "n%d is in the array %dn", key, result );
   } else {
      printf( "n%d Not in the array!n", key );
   }

   return 0;

}

int binarySearch( const int b[], int searchKey, int low, int high )
{
   int middle;

   while ( low <= high ) {
      middle = ( low + high ) / 2;

      if ( searchKey == b[ middle ] ) {
         return middle;
      } else if ( searchKey < b[ middle ] ) {
         high = middle - 1;
      } else {
         low = middle + 1;
      }
   }
   return -1;

}

Guess the output! :)

How to listen to the softkeyboard done button in android?

Instead of using a button on the view we can use the softkeyboard done button to trigger an action. The action can include calling another activity or retrieving the data from the EditText etc.

The main.xml contains an Edittext

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello"
		/>
	<EditText android:layout_width="match_parent"
		android:singleLine="true"
		android:inputType="textNoSuggestions"
		android:layout_height="wrap_content"
		android:id="@+id/editText1">
			<requestFocus></requestFocus>
		</EditText>
</LinearLayout>

For listening to the keyboard event we need onKeyListener

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

public class TesstActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

		EditText text = (EditText) findViewById(R.id.editText1);
		text.setOnKeyListener(onSoftKeyboardDonePress);

    }

    private View.OnKeyListener onSoftKeyboardDonePress=new View.OnKeyListener()
    {
        public boolean onKey(View v, int keyCode, KeyEvent event)
        {
            if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
            {
            	Toast.makeText(TesstActivity.this, "checking event", Toast.LENGTH_LONG).show();
            }
            return false;
        }
    };
}

How to check whether your Android device has Bluetooth support?

Hello all..

This is a simple example to check whether your android device supports Bluetooth or not.
May be currently all devices may have bluetooth support, but still ………….

package pack.coderzheaven;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.os.Bundle;

public class BluetoothExample extends Activity  {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            System.out.println("Device do not support Bluetooth..");
        }
    }
}

How to replace a substring in C Sharp/C# ?

Hi,

For replacing a substring in C Sharp/C#, use the following lines of code.

using System;

  class Class1
  {
    static void Main(string[] args)
    {
            string newStr = "Heaven";

            string finalStr = "CoderzWorld";

            finalStr = finalStr.Replace( "World", newStr);

            Console.WriteLine( finalStr);

    }
    }

How to search for a particular character in a C++ string ?

Hi,

In order to search for a particular character in a C++ string, use the following code.

#include <iostream>
#include <cstring>

using namespace std;

int main() {

  const char *testStr= "coderz@heaven";

  const char *temp;

  // Searching
  temp = strchr(testStr, '@');

  if(temp )

      cout << "Found";

  return 0;
}

How to find the device ID or Serial Number of an android device?

Here is a simple API to find the device ID of an android device.
There are many ways to get the device ID in android

    String serial_no = null;

    try {
        Class<?> c = Class.forName("android.os.SystemProperties");
        Method get = c.getMethod("get", String.class);
        serial_no = (String) get.invoke(c, "ro.serialno");
       System.out.println("Device serial ID : " + serial_no);
    } catch (Exception e) {
        System.out.println("Some error occured : " + e.getMessage());
    }

Note : Try this in a real device, then only you will get the device ID.
Also put this permission in the AndroidManifest file

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