Android DOM Parser Example



In this example we will see how to parse an XML file using DOM Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view. When compared to SAX Parser(refer : Android SAX Parser Example ) , DOM is slow and will consume a lot of memory when it loads an XML document which contains a lot of data.


Okay let us start:

1.Create an xml file (file.xml) like below

file.xml
<?xml version="1.0"?>
<food>
<item>
<name>French Toast</name>
<price>$4.50</price>
</item>
<item>
<name>Strawberry Belgian Waffles</name>
<price>$7.95</price>
</item>
<item>
<name>Berry-Berry Belgian Waffles</name>
<price>$8.95</price>
</item>
</food>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as DOMParserActivity(DOMParserActivity.java). Copy and paste the xml file inside the assets folder of the android project.

DOMParserActivity.java:
package com.aj.dom;

import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

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

public class DOMParserActivity extends Activity {
 TextView tv1;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv1 = (TextView) findViewById(R.id.textView1);
  try {
   InputStream is = this.getAssets().open("file.xml");

   DocumentBuilderFactory dbFactory = DocumentBuilderFactory
     .newInstance();
   DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
   Document doc = dBuilder.parse(is);
   doc.getDocumentElement().normalize();
   NodeList nList = doc.getElementsByTagName("item");
   for (int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
     Element eElement = (Element) nNode;
     tv1.setText(tv1.getText() + "\n\nName : "
       + getValue("name", eElement) + "\n");
     tv1.setText(tv1.getText() + "Price : "
       + getValue("price", eElement) + "\n");
     tv1.setText(tv1.getText() + "-----------------------");

    }
   }
  } catch (Exception e) {
   e.printStackTrace();
  }

 }

 private static String getValue(String sTag, Element eElement) {
  NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
    .getChildNodes();
  Node nValue = (Node) nlList.item(0);
  return nValue.getNodeValue();
 }

}

3. Now in the main.xml, add the id attribute for the TextView to be used in the DOMParserActivity


main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="DOM Parser Example"
        tools:context=".DOMParserActivity" />

</RelativeLayout>
4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:

Android SAX Parser Example


In this example we will see how to parse an XML file using SAX Parser in Android. What we do here is load the .xml file in the assets folder and parse the content inside and show them in a text view.

To do parsing we use the following callback methods :
  • startDocument() and endDocument() is called at the start and end of the document.
  • startElement() and endElement() is called at the start and end of the element.
  • characters() is called with the text contents between the element.
So let us start:

1.Create an xml file (file.xml) like below

file.xml

<?xml version="1.0"?>
<contacts>
<contact>
<firstname>Sachin</firstname>
<lastname>Tendulkar</lastname>
<email>sachin@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Brain</firstname>
<lastname>Lara</lastname>
<email>lara@xyz.com</email>
<phone>9999999999</phone>
</contact>
<contact>
<firstname>Steve</firstname>
<lastname>Waugh</lastname>
<email>steve@xyz.com</email>
<phone>9999999999</phone>
</contact>
</contacts>
2. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project give activity name as SAXParserActivity(SAXParserActivity.java). Copy and paste the xml file inside the assets folder of the android project. In the activity we parse the xml file using the org.xml.sax.helpers.DefaultHandler.

SAXParserActivity.java:
import java.io.InputStream;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class SAXParserActivity extends Activity {
 TextView tv;

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  tv = (TextView) findViewById(R.id.textView1);
  try {
   SAXParserFactory factory = SAXParserFactory.newInstance();
   SAXParser saxParser = factory.newSAXParser();
   DefaultHandler handler = new DefaultHandler() {
    boolean bfname = false;
    boolean blname = false;
    boolean bemail = false;
    boolean bphone = false;

    public void startElement(String uri, String localName,
      String qName, Attributes attributes)
      throws SAXException {
     if (qName.equalsIgnoreCase("FIRSTNAME")) {
      bfname = true;
     }
     if (qName.equalsIgnoreCase("LASTNAME")) {
      blname = true;
     }
     if (qName.equalsIgnoreCase("EMAIL")) {
      bemail = true;
     }
     if (qName.equalsIgnoreCase("PHONE")) {
      bphone = true;
     }
    }

    public void endElement(String uri, String localName,
      String qName) throws SAXException {
    }

    public void characters(char ch[], int start, int length)
      throws SAXException {
     if (bfname) {
      tv.setText(tv.getText() + "\n\n First Name : "
        + new String(ch, start, length));
      bfname = false;
     }
     if (blname) {
      tv.setText(tv.getText() + "\n Last Name : "
        + new String(ch, start, length));
      blname = false;
     }
     if (bemail) {
      tv.setText(tv.getText() + "\n Email : "
        + new String(ch, start, length));
      bemail = false;
     }
     if (bphone) {
      tv.setText(tv.getText() + "\n Phone : "
        + new String(ch, start, length));
      bphone = false;
     }
    }
   };
   InputStream is = this.getAssets().open("file.xml");
   saxParser.parse(is, handler);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
3. Now in the main.xml, add the id attribute for the TextView to be used in the SAXParserActivity


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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="SAX Parser Example" />

</LinearLayout>
4.Run the project by rightclicking project Run as → android project. This project is tested with amdroid API level 8

Output:

The output of this example would be similar to the one as follows:


Android Face Detection Example


In this sample application we will detect the faces in the given photograph. The application will detect the number of faces in the image and draws a rectangle around each face in the image. So here we will load an image into our project and detect if it has faces or not. In real life you would probably
want to capture the image using the camera, or choose the image from a Gallery to detect face in it.

To do face detection we use android.media.FaceDetector class which identifies the location of the face in a bitmap.

So lets start:

1. Create a new project File -> Android Project. While creating a new project give activity name as FaceDetection(FaceDetection.java).

2. A custom class myView is created which extends View where the face detection is done. It would be used to serve as UI for our Activity.

FaceDetection.java
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.os.Bundle;
import android.view.View;

public class FaceDetection extends Activity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(new myView(this));
 }

 private class myView extends View {

  private int imageWidth, imageHeight;
  private int numberOfFace = 5;
  private FaceDetector myFaceDetect;
  private FaceDetector.Face[] myFace;
  float myEyesDistance;
  int numberOfFaceDetected;

  Bitmap myBitmap;

  public myView(Context context) {
   super(context);

   BitmapFactory.Options BitmapFactoryOptionsbfo = new BitmapFactory.Options();
   BitmapFactoryOptionsbfo.inPreferredConfig = Bitmap.Config.RGB_565;
   myBitmap = BitmapFactory.decodeResource(getResources(),
     R.drawable.jennifer_lopez, BitmapFactoryOptionsbfo);
   imageWidth = myBitmap.getWidth();
   imageHeight = myBitmap.getHeight();
   myFace = new FaceDetector.Face[numberOfFace];
   myFaceDetect = new FaceDetector(imageWidth, imageHeight,
     numberOfFace);
   numberOfFaceDetected = myFaceDetect.findFaces(myBitmap, myFace);

  }

  @Override
  protected void onDraw(Canvas canvas) {

   canvas.drawBitmap(myBitmap, 0, 0, null);

   Paint myPaint = new Paint();
   myPaint.setColor(Color.GREEN);
   myPaint.setStyle(Paint.Style.STROKE);
   myPaint.setStrokeWidth(3);

   for (int i = 0; i < numberOfFaceDetected; i++) {
    Face face = myFace[i];
    PointF myMidPoint = new PointF();
    face.getMidPoint(myMidPoint);
    myEyesDistance = face.eyesDistance();

    canvas.drawRect((int) (myMidPoint.x - myEyesDistance * 2),
      (int) (myMidPoint.y - myEyesDistance * 2),
      (int) (myMidPoint.x + myEyesDistance * 2),
      (int) (myMidPoint.y + myEyesDistance * 2), myPaint);
   }
  }
 }

}
3.Do not forget to drop an image into drawable folder.

4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:



Google Map in Android Application Example



In this sample application we wills see how to display a MapView in an android application. Of course we are going to use Google Map API library for that.

So let us start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the application and project name as MapViewApplication , package name as you like, set the Build SDK to Google APIs (Google Inc.) (API8) and the Build Target to API8:Android 2.2(Froyo) -If you do not have these AVDs or Platforms please use SDK Manager or AVD Manager to download and install them.

2. Let the Activity name be MainActivity(MainActivity.java) and layout name be activity_main(activity_main.xml).

3. Now let us design the layout for our Activity .Note that while including the MapView tag in xml it is necessary to mention the full library path(com.google.android.maps.MapView) since it is not android defined and belongs to google. Also note that the 'android:apikey' attibute should have a valid key which should be obtained by registering a Google Map API Key Refer (How to obtain Google Map API Key for Android) to know how to obtain a google map API key

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="Your API Key here"
        android:clickable="true" />

</RelativeLayout>
4.Now let us use this layout in the MainActivity . This activity will extend MapActivity and must implement isRouteDisplayed() method .Press Ctrl+Shift+O for missing imports after typing the code.

MapActivity
public class MainActivity extends MapActivity {

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  MapView mapview = (MapView) findViewById(R.id.mapview);
  mapview.setBuiltInZoomControls(true);
 }

 @Override
 protected boolean isRouteDisplayed() {
  // TODO Auto-generated method stub
  return false;
 }
}
5.Make the changes in AndroidManifest.xml file by including internet permission <uses-permission android:name="android.permission.INTERNET" /> and indicate the use of google map library <uses-library android:name="com.google.android.maps" />

AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.aj.mapviewapplication"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET" />

<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<uses-library android:name="com.google.android.maps" />
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
6.Run your Android Application by rightclicking project Run as → android project. If everything goes well you will be shown a map of North America which you can zoom in and drag around.

Output:

The output of this example would be similar to the one as follows:




How to get Google Map API Key for Android

Now I will explain how to get Google Map API key for Android Application Development. To do this first we should know where the debug.keystore  reside in your system.

Getting the 'debug.keystore' path:

To find it , In Eclipse navigate to Windows->Preferences->Android->Build Her you will find the path near Default Debug Keystore:"C:\Users\<your_name>\.android\debug.keystore"

Getting the 'MD5 Certificate Fingerprint':

Now that you have the keystore path we are ready to get the MD5 Certificate Fingerprint . Open Command Prompt (type cmd in run and press enter) and navigate to Program Files (x86)\Java\jre6\bin
and type the command keytool -list -alias androiddebugkey -keystore "C:\Users\<your_name>\.android\debug.keystore" -storepass android -keypass android and press enter.
You will be given a Certificate Fingerprint like 2G:54:39:DB:23:E7:D7:3A:9E:18:3D:7F:FB:6D:BC:9D

Refer the below Image for reference:












.

Getting the API Key:

Now that we have got the Certificate Fingerprint log in to your Google Account and open the link ->
https://developers.google.com/android/maps-api-signup

Read the terms and conditions accept it and paste the MD5 Fingerprint in the textbox and click Generate API key button. You will be given an API key like 0XQpOUpGrVszoIS6vgtJ6oSdcYj1wRHnxj_4EHg 

Paste the API key in your layout file where MapView is used:


<com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="0XQpOUpGrVszoIS6vgtJ6oSdcYj1wRHnxj_4EHg "
        android:clickable="true"
         />

Note : The Map would be shown only in the Emulator in the computer where you generate the finger print since this is a debug key.If you wish to show map in different devices generate the key using the applications publishing keystore.

How to disable Japanese / Chinese keyboard suggestions in Android Emulator

If the android emulator suggests Japanese or Chinese words when you type in English and you want to disable it then just uncheck the Japanese  IME / Chinese IME in settings.

This is how its done:

Navigate to Settings->Language & Keyboard -> Japanese  IME (uncheck it!!)

The same can be done to disable Chinese suggestions also.

Android Count Down Timer Example


In this sample application we will create a countdown timer in android using the CountDownTimer class .This is an example of showing a 30 second countdown in a TextView . We will update the TextView on every tick of the timer.The option to stop and restart the timer is also provided.

So let us start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as TimerActivity(TimerActivity.java) and layout as activity_timer.xml.

2.Now let us design the UI for the TimerActivity i.e activity_timer.xml with a textview and a button.

activity_timer.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="fill_parent"
android:orientation="vertical"
android:background="@drawable/bgi" >

<TextView
android:id="@+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:paddingRight="10dip"
android:textSize="50dp" />

<Button
android:id="@+id/button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Start" />

</RelativeLayout>

3.Now in the TimerActivity we implement the count down timer by extending the CountDownTimer class.Press Ctrl+Shift+O for missing imports after typing the code.

TimerActivity.java

public class TimerActivity extends Activity implements OnClickListener {

 private CountDownTimer countDownTimer;
 private boolean timerHasStarted = false;
 private Button startB;
 public TextView text;
 private final long startTime = 30 * 1000;
 private final long interval = 1 * 1000;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_timer);
  startB = (Button) this.findViewById(R.id.button);
  startB.setOnClickListener(this);
  text = (TextView) this.findViewById(R.id.timer);
  countDownTimer = new MyCountDownTimer(startTime, interval);
  text.setText(text.getText() + String.valueOf(startTime / 1000));
 }

 @Override
 public void onClick(View v) {
  if (!timerHasStarted) {
   countDownTimer.start();
   timerHasStarted = true;
   startB.setText("STOP");
  } else {
   countDownTimer.cancel();
   timerHasStarted = false;
   startB.setText("RESTART");
  }
 }

 public class MyCountDownTimer extends CountDownTimer {
  public MyCountDownTimer(long startTime, long interval) {
   super(startTime, interval);
  }

  @Override
  public void onFinish() {
   text.setText("Time's up!");
  }

  @Override
  public void onTick(long millisUntilFinished) {
   text.setText("" + millisUntilFinished / 1000);
  }
 }

}
4.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows:

 




Android SlidingDrawer Example


In this example we will demonstrate how to implement sliding drawer in android. SlidingDrawer is a special widget which allows user to drag some content into the screen from outside and hide them if not needed. It has a handle and content , dragging the handle in shows the content and dragging the handle out hides the content.

So lets start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as SlidingDrawerActivity(SlidingDrawerActivity.java) and layout as main.xml. Press Ctrl+Shift+O for missing imports after typing the code.

SlidingDrawerActivity.java

public class SlidingDrawerActivity extends Activity implements OnClickListener {
 Button slideButton, b1, b2, b3;
 SlidingDrawer slidingDrawer;

 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_sliding_drawer);
  slideButton = (Button) findViewById(R.id.slideButton);
  slidingDrawer = (SlidingDrawer) findViewById(R.id.SlidingDrawer);
  b1 = (Button) findViewById(R.id.Button01);
  b2 = (Button) findViewById(R.id.Button02);
  b3 = (Button) findViewById(R.id.Button03);
  b1.setOnClickListener(this);
  b2.setOnClickListener(this);
  b3.setOnClickListener(this);
  slidingDrawer.setOnDrawerOpenListener(new OnDrawerOpenListener() {
   @Override
   public void onDrawerOpened() {
    slideButton.setText("V");
   }
  });
  slidingDrawer.setOnDrawerCloseListener(new OnDrawerCloseListener() {
   @Override
   public void onDrawerClosed() {
    slideButton.setText("^");
   }
  });
 }

 @Override
 public void onClick(View v) {
  Button b = (Button) v;
  Toast.makeText(SlidingDrawerActivity.this,
    b.getText() + " is Clicked :)", Toast.LENGTH_SHORT).show();
 }
}

2.Now design the UI for the above activity in the activity_sliding_drawer.xml file .

activity_sliding_drawer.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Drag the control at the bottom"
        android:textSize="20dp"
        tools:context=".SlidingDrawerActivity" />

    <SlidingDrawer
        android:id="@+id/SlidingDrawer"
        android:layout_width="wrap_content"
        android:layout_height="250dip"
        android:layout_alignParentBottom="true"
        android:content="@+id/contentLayout"
        android:handle="@+id/slideButton"
        android:orientation="vertical"
        android:padding="10dip" >

        <Button
            android:id="@+id/slideButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="^" >
        </Button>

        <LinearLayout
            android:id="@+id/contentLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:padding="10dip" >

            <Button
                android:id="@+id/Button01"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:text="Button 1" >
            </Button>

            <Button
                android:id="@+id/Button02"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:text="Button 2" >
            </Button>

            <Button
                android:id="@+id/Button03"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_margin="2dp"
                android:text="Button 3" >
            </Button>
        </LinearLayout>
    </SlidingDrawer>

</RelativeLayout>

3.Run the project by rightclicking project Run as → android project.

Output:

The output of this example would be similar to the one as follows

 

Android Options Menu Example


In this example, we will be creating a simple options menu for an activity . On clicking the menu items a toast message will be shown.

So lets start:

1.Create a new project File ->New -> Project ->Android ->Android Application Project. While creating the new project, name the activity as MenuActivity(MenuActivity.java) and layout as main.xml


2.If you have the latest SDK and ADT version say (20.0.2 ). There will be a folder named menu under /res in the folder structure, you can type your menu items code there. If not create a new menu.xml file in res/layout folder , here we should use two different names for the layout files

res/layout/menu.xml or res/menu/main.xml


<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/menu_one"
        android:orderInCategory="100"
        android:title="one"/>

    <item
        android:id="@+id/menu_two"
        android:icon="@drawable/ic_launcher"
        android:orderInCategory="100"
        android:title="two"/>

    <item
        android:id="@+id/menu_three"
        android:icon="@android:drawable/ic_menu_camera"
        android:orderInCategory="100"/>

    <item
        android:id="@+id/menu_four"
        android:orderInCategory="100"
        android:title="four"/>

    <item
        android:id="@+id/menu_five"
        android:orderInCategory="101"
        android:title="five"/>

    <item
        android:id="@+id/menu_six"
        android:orderInCategory="100"
        android:title="six"/>

</menu>

res/menu/main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="@string/hello_world"
tools:context=".MenuActivity" />

</RelativeLayout>

3.Now let us bind our UI layout files with the activity. To do so we override onCreateOptionsMenu(Menu menu) and onOptionsItemSelected(MenuItem item) methods in MenuActivity.java file.Press Ctrl+Shift+O for missing imports after typing the code

MenuActivity.java

public class MenuActivity extends Activity {

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

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.main, menu); // or use->
  // getMenuInflater().inflate(R.layout.menu,
  // menu);
  return true;
 }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
  // TODO Auto-generated method stub
  switch (item.getItemId()) {
  case R.id.menu_one:
   Toast.makeText(MenuActivity.this, "One is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  case R.id.menu_two:
   Toast.makeText(MenuActivity.this, "Two with icon is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  case R.id.menu_three:
   Toast.makeText(MenuActivity.this, "Icon is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  case R.id.menu_four:
   Toast.makeText(MenuActivity.this, "Four is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  case R.id.menu_five:
   Toast.makeText(MenuActivity.this, "Five is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  case R.id.menu_six:
   Toast.makeText(MenuActivity.this, "Six is Selected",
     Toast.LENGTH_SHORT).show();
   return true;

  default:
   return super.onOptionsItemSelected(item);
  }

 }

}

4.Run the project by rightclicking project Run as → android project. If observed carefully the menu item six would be in front of five that is because we have the orderInCategory level of five greater than that of menu item six. We have also tried menus with icon,text and icon with text.

Output:

The output of this example would be as follows

Android Paint Example


In this example, we demonstrate how to draw/paint on canvas when the user touches and drags on the screen. Here we will create a custom view class called 'PaintView' which will be used as the contentview for the 'MainActivity'.

So lets start:

1. Create a new project File ->New -> Project ->Android ->Android Application Project. While creating a new project, name the activity as MainActivity(MainActivity.java).Press Ctrl+Shift+O for missing imports after typing the code

MainActivity.java
public class MainActivity extends Activity {

 PaintView paintView;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
  requestWindowFeature(Window.FEATURE_NO_TITLE);

  paintView = new PaintView(this);
  setContentView(paintView);
  paintView.requestFocus();
 }

}

2. Now create a new class by rightclicking the /src/<package-name> and select class to create a new class named PaintView(PaintView.java).Press Ctrl+Shift+O for missing imports after typing the code

PaintView.java
public class PaintView extends View implements OnTouchListener {
 private static final String TAG = "PaintView";

 List<Point> points = new ArrayList<Point>();
 Paint paint = new Paint();

 public PaintView(Context context) {
  super(context);
  setFocusable(true);
  setFocusableInTouchMode(true);

  this.setOnTouchListener(this);

  paint.setColor(Color.GREEN);
  paint.setAntiAlias(true);
 }

 @Override
 public void onDraw(Canvas canvas) {
  for (Point point : points) {
   canvas.drawCircle(point.x, point.y, 2, paint);
  }
 }

 public boolean onTouch(View view, MotionEvent event) {
  Point point = new Point();
  point.x = event.getX();
  point.y = event.getY();
  points.add(point);
  invalidate();
  Log.d(TAG, "point: " + point);
  return true;
 }
}

class Point {
 float x, y;

 @Override
 public String toString() {
  return x + ", " + y;
 }
}

3.We did not create any .xml file for UI since the above two files are the only significant files for this example. Run the project by rightclicking project Run as → android project. Try enhancing this by providing color options,brush styles etc.,  


Output:

The output of this example after drawing would be something like this



Splash Screen for Android Application - Example

Adding a splash screen for your application is necessary if your application takes more time to load. It is similar to the PC games we play where you would see the brand of the gaming company before the actual game commences.

Here in this example we will create an activity to display your splash screen with progress bar for two seconds . After two seconds the user will be directed to the main page.

So lets start:

1. Create a new project File -> Android Project. While creating a new project name the as SplashScreenActivity(SplashScreenActivity.java).Press Ctrl+Shift+O for missing imports after typing the code

SplashScreenActivity.java


public class SplashScreenActivity extends Activity {
 private long ms = 0;
 private long splashDuration = 2000;
 private boolean splashActive = true;
 private boolean paused = false;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.splashscreen);
  Thread mythread = new Thread() {
   public void run() {
    try {
     while (splashActive && ms < splashDuration) {
      if (!paused)
       ms = ms + 100;
      sleep(100);
     }
    } catch (Exception e) {
    } finally {
     Intent intent = new Intent(SplashScreenActivity.this,
       MainActivity.class);
     startActivity(intent);
    }
   }
  };
  mythread.start();
 }
}

2. Now you need to create user interface for the SplashScreenActivity.java
3. Create a new xml file in layout folder as splashscreen.xml

splashscreen.xml


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

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="300dp"
        android:src="@drawable/androidbite" />

    <ProgressBar
        android:id="@+id/progressBar1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/image"
        android:layout_gravity="center_horizontal" >
    </ProgressBar>

</LinearLayout>

4. Now that the splash screen is ready lets create the main activity(MainActivity.java) and layout for the main activity (main.xml)

MainActivity.java

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
 }
}
main.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="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="181dp"
        android:text="Welcome To Main Screen" />

</RelativeLayout>
5.Here come the most important part, include all your activity in manifest file. In addition to that put android:noHistory=”true” attribute in the SplashScreenActivity's tag so that the activity will not appear in the activity stack, meaning if the user presses back from the main activity its should not direct the user to splash screen.


AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbite.splashscreen"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="7"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".SplashScreenActivity"
            android:label="@string/title_activity_splashscreen"
            android:noHistory="true" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_splashscreen" />
    </application>

</manifest>


Output:

The output of this example would be as follows

   

Android switching activity and sending data - Example


There may be situation where you want to send data from one activity to another while switching from one activity to another. The following is a simple example where you can enter your name and age in the first screen and receive it at the second screen on click of a button.

So lets start .

1. Create a new project File -> Android Project. While creating a new project give activity name as FirstActivity(FirstActivity.java).
2. Now you need to create user interface for the FirstActivity.java
3. Create a new xml file in layout folder or rename the main.xml to first.xml
4. Now insert the following code in first.xml to design a small layout. This layout contains two edittext and a button.


First.xml

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Name: " />

    <EditText
        android:id="@+id/name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip" />

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Age: " />

    <EditText
        android:id="@+id/age"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:inputType="number" />

    <Button
        android:id="@+id/btnNextScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:text="Send Data" />

</LinearLayout>



5.Now open your FirstActivity.java and Type the following code. In the following code we are creating a new Intent and passing parameters on clicking button.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class FirstActivity extends Activity {
 // Initializing variables
 EditText inputName;
 EditText inputAge;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.first);
  inputName = (EditText) findViewById(R.id.name);
  inputAge = (EditText) findViewById(R.id.age);
  Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
  // Listening to button event
  btnNextScreen.setOnClickListener(new View.OnClickListener() {
   public void onClick(View arg0) {
    // Starting a new Intent
    Intent nextScreen = new Intent(getApplicationContext(),
      SecondActivity.class);
    // Sending data to another Activity
    nextScreen.putExtra("name", inputName.getText().toString());
    nextScreen.putExtra("age", inputAge.getText().toString());
    startActivity(nextScreen);
   }
  });
 }
}



  1. Create a class called SecondActivity.java. And an xml file named second.xml
SecondActivity.java.

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class SecondActivity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.second);
  TextView txtName = (TextView) findViewById(R.id.txtName);
  TextView txtEmail = (TextView) findViewById(R.id.txtAge);
  Button btnBack = (Button) findViewById(R.id.btnBack);
  Intent i = getIntent();
  // Receiving the Data
  String name = i.getStringExtra("name");
  String age = i.getStringExtra("age");
  Log.e("Second Screen", name + "." + age);
  // Displaying Received data
  txtName.setText(name);
  txtEmail.setText(age);
  // Binding Click event to Button
  btnBack.setOnClickListener(new View.OnClickListener() {
   public void onClick(View arg0) {
    // Closing SecondScreen Activity
    finish();
   }
  });
 }
}


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

    <TextView
        android:id="@+id/txtName"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dip"
        android:textSize="18dip" />

    <TextView
        android:id="@+id/txtAge"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="15dip"
        android:textSize="18dip" />

    <Button
        android:id="@+id/btnBack"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:text="Back" />

</LinearLayout>



  1. Open you AndroidManifest.xml file and modify the code as below in application tag

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
    
        <activity
            android:name=".FirstActivity"
            android:label="@string/app_name" >
    
            <intent-filter>
    
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
        <activity
            android:name=".SecondActivity"
            android:label="@string/app_name" />
    
    </application>
    

    8.Run your project by right clicking on your project folder -> Run As -> 1 Android Application.

The below image is output of this example