Showing posts from 2009

Opening and Closing Menu Programmatically

API for opening menu programmatically is openOptionsMenu(). If we are in a different context, then we can use this method by,

((Activity) mContext).openOptionsMenu();

For closing menu programmatically, if it opens use this,

((Activity) mContext).closeOptionsMenu();

Reasons for getting java.lang.StackOverflowError

java.lang.StackOverflowError occurs when it does an infinitive autoinvoke.

This StackOverflowError occurs because of two conditions.

-> One is a function calling itself infinite times and
-> When first function calls a second function and second inturn calls the first function. This is a kind of deadlock.

RelativeLayout Programmatically in Android

This article aimed at understanding how we can implement RelativeLayout programmatically. We can initialize the layout normally like

RelativeLayout layout = new RelativeLayout(this);

To position the child to left, right, top or botttom, we have to add rules to the layout params as,


Parsing XML and storing elements in Database in Android

For one of my project I parsed XML file and stored each element in database according to ID. First of all, about parsing, there are three different types of parsing are there in Android as,

-DOM (Document Object Model)
-SAX (Simple API for XML)

A DOM parser works by parsing an XML file into a native data structure matching the hierarchy of the XML file. Most of the processing is done up front and the entire file is looked at, so a DOM parser typically uses the most memory of the three parsers.

A Pull Parser works by creating a loop that continually requests the next event and can then handle that event directly within the loop. The idea with the Pull Parser is that it can easily be stopped at any point, only do processing on demand, and remove the overhead of extra method calls and classes.

SAX parser is an event driven parser. Events are fired, when XML features such as XML text nodes, XML element node etc. are encountered. SAX parsing is uni directional, previously parsed data cann…

Setting Margin for widgets Programmatically

In this tutorial, I am going to explain how we can set margin for widgets programmatically. Using XML, its through layout_marginLeft, layout_marginRight, layout_marginTop and layout_marginBottom.

Actually, I spent a quite some time in this. I tried with this class "android.view.ViewGroup.LayoutParams". But after trying for quite sometime, I realized the actual class, for that is "android.widget.LinearLayout.LayoutParams". We can use any layout, not only LinearLayout. But, it should be from widget package.

The function is setMargins(left, top, right, bottom); the four arguments shows the margin for four sides respectively.

TextView tv = new TextView(this);
LayoutParams params = new LayoutParams(WRAP_CONTENT, WRAP_CONTENT);
params.setMargins(100, 20, 0, 0);
layout.addView(tv, params);

The screenshot of the result is,

Creating EditText Programmatically in Android

In this tutorial, I am going to explain how to create a EditText programatically, and the different properties, that we can assign to it in Android.

If we want, our EditText to take only numbers. Then the code is,


For password style implementation, for the editText, the code is,

edit.setTransformationMethod(new android.text.method.PasswordTransformationMethod()

For putting, all letters in caps, the code

InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.AllCaps();

For restricting, only upto this much characters to enter in the editText, the code is,

InputFilter[] filter = new InputFilter[1];
filter[0] = new InputFilter.LengthFilter(15);

In this, I am restricting the characters upto 15 characters.

For moving the editText horizontally or vertically, the code is, Runnablepublic void run() {

Creating Menu & SubMenu in Android

In this tutorial, I am going to explain, how to create options menu, subMenu etc..

From Activity class, just override the method, onCreateOptionsMenu(). Then inside the method, create the menu, according to our wish.

Then, override another method called, onOptionsItemSelected. In this, if we select any, menu, what we have to do, will code in this. That means, menu events will be handled in this method.

public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case 0: Toast.makeText(this, "clicked Menu 1",
case 1: Toast.makeText(this, "clicked Menu 2",
case 2: Toast.makeText(this, "clicked Menu 3",
return true;

The screenshot will be look like this.

For adding submenu, we have to use the function called addSubMenu(), in the Me…

Creating SubActivity, Passing data to SubActivity and Retrieving data from SubActivity

In this tutorial, I am going to explain about the subactivity in Android.

The basic thing that I am going to explain in this tutorial is,

From a main activity calling another activity or subActivity, passing data to the subActivity using startActivityForResult() and retrieving information from the subActivity using the callback function called onActivityResult().

The UI contains TextView, EditText and a button. Whatever we type in the editText will appear in the next activity.

First we will pass data from main Activity to subActivity using Bundle. We can put all primitive data types and String to bundle. Bundle will take data as Key/Value pair. Then we will put this bundle into the Intent using intent.putExtras(bundle). We will pass this intent object to startActivityForResult() with a REQUEST_CODE.

In subActivity, we will retreive the data using

Bundle bundle = this.getIntent().getExtras();

Then by passing the desired key, we will get the values using get method.

Seems so easy, right ??


Blinking effect on an Image

In this tutorial, I am going to explain blinking an image using Handler. Actually, this is an extension of SplashScreen.

In nutshell, what this tutorial is going to explain is,
An Image will be visible for one second and for the next second, it will be invisible. I am doing this using two handlers. One for making the image visible and another for making the image invisible.

First in onCreate() method, I am calling the first handler called "splashHandler" using sendMessageDelayed() method. I am passing an object of Message and variable of data type "long", its for how long the image has to invisible. Then from "splashHandler", I am calling another handler called "resumeHandler" for making the image visible. In this also, I am passing an object of Message and a variable of long type to the sendMessageDelayed() function.

Then from "resumeHandler", again calling "splashHandler with the message object and a variable of long type. So this…

Setting Wallpaper

In this tutorial, I am going to explain, how to set wallpaper through android application. The code for this is,

Intent intent = new Intent();

We have to give permission also in Manifest file as

uses-permission android:name="android.permission.SET_WALLPAPER/>

The screen-shot for the above program will be as,

Calling a Number

In this tutorial, I am going to explain, how to call to a number through android application. The code for that is,

Intent intent = new Intent();

The code is self explanatory, nothing big in it. Then, in the Manifest file we have to give permission too.

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

The screen-shot of the program - Emulator 5554 calling emulator 5556 in this application as,

Sending SMS in Android

In this tutorial I am going to explain sending text message from one android mobile to another.

The UI of our application contains just two Editexts, one for sender's number and another for the message body. Then one "SEND" button.

I am going to demonstrate this by opening two different emulators(5554 & 5556). The phone number is the number that we see on top left side of the emulator, ie, here, 5554 & 5556 respectively.

Launch the SMS application on both emulators and start SMSing. You will get the notifcation on top of other emulator.

Now, how to implement the SMS Application. The main part of the application is the method sendSMS() and it takes two parameters, Sender's number and the content of the SMS.

sendSMS() contains, one object of PendingIntent and a BroadCastReceiver to send SMS.
PendingIntent contains an Intent and a target action and the return object can be handed on a different application, so that, the action that we described can be performed at a …

Rotating a bitmap in Android

Here, we have an image of globe and I am going to rotate it.

In Android, we can rotate a bitmap in canvas. Its simple, but we have to know the save() and restore() methods in Canvas class.

We can load a bitmap using

Bitmap globe = BitmapFactory.decodeResource(context.getResources(), R.drawable.globe);

in onDraw() method,

we can rotate the bitmap using

canvas.roatate() method. But here the problem is, the whole canvas will rotate. But by using, save() and restore() we can solve this problem.

Before rotating the, just call then, call

then, draw the image. After drawing the image, just call canvas.restore().

This will solve the problem of rotating the whole canvas.

To show, canvas is restored, I am drawing a text after drawing bitmap in canvas by,
canvas.drawText("Here our globe is rotating", 50, 400, textColor);
In the end of onDraw, just call invalidate();

Now, our globe will rotate.

and the text under the globe is stati…

Include attribute in Android

Include tag in android is used to add an layout XML file to another file. Here I am showing a simple way, to do this.

<include layout="@layout/newfile"/>

Here, "newfile" is the name of another layout file

Happy Coding...

Reading Contacts from mobile and calling

Before coming to Contacts, first I will touch a bit on Content provider in Android

Content Provider

ContentProvider in android is mainly used to share data between applications. Android has some built-in ContentProviders. They are


We store data into contentProvider using contentprovider base class. We will store data in any way, generally, using Sqlite database.

We will retrieve data from contentprovider using a single interface called ContentResolver. We can get a object of contentResolver using getContentResolver().

One main thing we require for retrieving data from content provider is the URI.
To get contact list, to the query(), just pass "People.CONTENT_URI".

Cursor c = getContentResolver().query(People.CONTENT_URI, null, null,
null, null);

We will receive the contact details in a cursor. Its better to use startManagingCursor(c). Because then Android ,itself will take care of the cursor, means when activity is stopped, it wi…

Gradient In Android

Gradient are drawn in android using GradientDrawable.

The code is,

GradientDrawable grad = new GradientDrawable(Orientation.LEFT_RIGHT,
new int[]{0xffffffff, 0xffff00ff, 0xffffff00,
0xff0000ff, 0xf0f0f0f0, 0xfefefefe});
grad.setBounds(0, 0, 320, 480);

then, in onDraw(), just call


The entire source code is,

public class AndGradient extends Activity {

public void onCreate(Bundle savedInstanceState) {
setContentView(new ViewGradient(this));

class ViewGradient extends View {

GradientDrawable grad;
public ViewGradient(Context context) {
grad = new GradientDrawable(Orientation.LEFT_RIGHT,
new int[]{0xffffffff, 0xffff00ff, 0xffffff00,
0xff0000ff, 0xf0f0f0f0, 0xfefefefe});
grad.setBounds(0, 0, 320, 480);

public void onDraw(Canvas canvas) {

Creating dashed circle and bulls eye(Marker)

In this tutorial, I am going to explain how to create dashed line or circle.

All we have to do for dashed circle, create a paint object with some special settings. To paint object we have to set some properties. Android have a class called "DashPathEffect".

DashPathEffect dashPath = new DashPathEffect(new float[]{5,5}, 1};

Then to paint object, we have to attach this "dashPath" by,




Then in onDraw(), use this paint object in the drawCircle().

The complete source code is,

public class AndDashedLine extends Activity {

public void onCreate(Bundle savedInstanceState) {
setContentView(new ViewDashedLine(this));

class ViewDashedLine extends View {

Context mContext;
Paint linePaint;
Paint dotPaint;
Paint linePaint1;
DashPathEffect dashPath;
public ViewDashedLine(Context context) {

Creating Static Label

In this tutorial, I am going to explain custom label.

For drawing label, we have to draw two same round rectangle with two differnt paint objects. First paint object will fill the inside color

Paint textDialog = new Paint();
textDialog.setARGB(255, 220, 220, 220);

and second paint object for the border color, here I am giving green color for border,

Paint borderDialog = new Paint();
borderDialog.setARGB(255, 0, 255, 0);

Now, for drawing in onDraw(), we have to draw two round rectangle as,

canvas.drawRoundRect(rectDialog, 7, 7, textDialog);
canvas.drawRoundRect(rectDialog, 7, 7, borderDialog);

rectDialog, is the area on which, I am going to draw, here its

RectF rectDialog = new RectF(100, 100, 200, 130);

and 7 is the radius for the round rectangle.

For drawing inside the label, I am creating another Paint with some other funcionalities.

Paint textPaint = new Paint();
textPaint.setARGB(255, 0, 0, 255);

Creating View from XML layout

We can create a view from the XML layout file. the way to do this is using,

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflater(R.layout.main, true);

Drawing customized shapes and basic shapes in Android

By extending the View Class, we can draw lot of shapes like circle, triangle, rectangle, rounded rectangle, bitmap, gradientdrawable, customized shape etc. Here I am explaining a few things about that.

Drawing circle, rectangle are straight forward, triangle we can draw using three lines. For customized shapes, we can use "Path" class in Android.

Example :

Path path = new Path();
path.moveTo(160.0f, 240.0f);
path.lineTo(140.0f, 200.0f);
path.addArc(new RectF(140, 180, 180, 220), -180, 180);
path.lineTo(160.0f, 240.0f);

This path, we will draw in canvas using,

canvas.drawPath(path, paint);


Intent objects are a bundle of information. It is used to launch the essential components of an android application, like

-startActivity(intent) for launching an activity
-startService(intent) for launching a service
-sendBroadcast(intent) for launching a Broadcast Receiver

The primary pieces of information of an Intent are

-action and

Action means the action to be performed by the intent like, ACTION_DIAL, ACTION_SET_WALLPAPER etc.

Data means, the data to be operate on.

Two types of intent are
-Explicit Intent
-Implicit Intent

In explicit intents, we explictly define the target component
eg: Intent intent = new Intent();
intent.setClass(this, NextScreen.class);
In this, we explicitly define to go to the NextScreen activity.

In implicit intents, no target component will be there. Actually, it is launching components of other application.

eg: Intent intent = new Intent(Intent.ACTION_SET_WALLPAPER);

Database Creation in Android

Steps for creating a database , creating table into it, inserting value and fetching the values and displaying in a listActivity


First of all, create an object of a database, using,

SQLiteDatabase myDB = null;
myDB = databaseAct.this.openOrCreateDatabase("MyDatabase",

Here, "MyDatabase" is the name of database. MODE_PRIVATE is file creation mode. In this mode, only created file can be accessed by the calling application or all application sharing the same userID.

Step - II

Next step is, creating a table in the database. Here, our table name is "MyTable". The command is,

myDB.execSQL("CREATE TABLE IF NOT EXISTS MyTable (lastName varchar, "
+ "firstName varchar, age INT(3));");

Now, we created a table with three fields such as lastName, FirstName and Age.

Step - III

Inserting values into the table using the function, execSQL() executes a SQL statement, not a query

myDB.execSQL("INSERT INTO MyTable VALUES ('Guna&#…