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: