Saturday, April 16, 2011

Parsing Data from XML Using DOM & Displaying it in a ListView in Android ?


Notice three methods which i had shown below, they are
1. getElementsByTagName - Mention the tag which you want to parse
2.getChildNodes - retervies the child node
3.getNodeValue()- with the help of this method you can access the
value of particular tag
 


Step 1 : Create a List View in the xml as i shown below

<?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" >

<ListView android:id="@+id/mylistview" android:layout_width="fill_parent" android:layout_height="fill_parent"></ListView>

</LinearLayout>

Step 2:  Now Create an XML which determines the Inner Content of List View

<?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">

<ImageView android:id="@+id/myimgview" android:layout_width="wrap_content" android:layout_height="wrap_content" />

<TextView android:layout_toRightOf="@+id/myimgview" android:id="@+id/mytextview" android:layout_width="wrap_content" android:layout_height="wrap_content" />

</RelativeLayout>


Step 3:  Now Create a Activity which maps the List View in the XML

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.ListView;

public class MyActivity extends Activity {

ListView listcomp=null;
 MyAdapter adapt_obj=null; // Create a Object for Adapter Class
Context myref=null;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
  listcomp=(ListView)findViewById(R.id.mylistview); // Map the List View Here
myref=MyActivity.this;
  new MyAsyncTask().execute(); // Call the Async Task

}

private class MyAsyncTask extends AsyncTask<Void,Void,Void>{

private final ProgressDialog dialog=new ProgressDialog(MyActivity.this);

@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
  adapt_obj=new MyAdapter(myref,"http://synd.cricbuzz.com/score-gadget/gadget-scores-feed.xml");

return null;
}

@Override
protected void onPreExecute()
{
dialog.setMessage("Loading ...");
dialog.show();
dialog.setCancelable(false);
}

@Override
protected void onPostExecute(Void result)
{
if(dialog.isShowing() == true)
{
dialog.dismiss();
}
listcomp.setAdapter(adapt_obj);
adapt_obj.notifyDataSetChanged();
}
}
}

Step 4: Create a Adapter which extends Base Adapter


import java.io.InputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MyAdapter extends BaseAdapter {

LayoutInflater inflation=null;
Context mycontext=null;
String urlvalue=null,roottag=null,parseelement=null;
MyParser myparseobj=null;
String[] title_array=null,image_array=null;

MyAdapter(Context c,String url)
{
Log.d("1","1");
mycontext=c;
inflation=LayoutInflater.from(mycontext);
myparseobj=new MyParser();
  title_array=myparseobj.xmlParsing(url,"match","description");
  image_array=myparseobj.xmlParsing(url," match ","image");
}


@Override
public int getCount() {
// TODO Auto-generated method stub
Log.d("title_array",title_array.length+"");
return title_array.length;
}

@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
MyHolder holder=new MyHolder();;
if(convertView == null)
{
convertView=inflation.inflate(R.layout.listcontent, null);

holder.tv=(TextView)convertView.findViewById(R.id.mytextview);
holder.iv=(ImageView)convertView.findViewById(R.id.myimgview);


}
else
{
holder.tv=(TextView)convertView.findViewById(R.id.mytextview);
holder.iv=(ImageView)convertView.findViewById(R.id.myimgview);

}

holder.tv.setText(title_array[position]);
try{
String temp=image_array[position];
InputStream is= new java.net.URL(temp).openStream();
Bitmap b=BitmapFactory.decodeStream(is);
holder.iv.setImageBitmap(b);
}
catch(Exception e){}

return convertView;
}

static class MyHolder
{
TextView tv=null;ImageView iv=null;
}
}

Step 5:  Parse the Given Url, using DOM or SAX,  I had used DOM

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
//import java.util.ArrayList;

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

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import android.util.Log;

public class MyParser {

public String[] xmlParsing(String fetchurl,String roottag,String parseelemnt)
{
String[] temp=null;
URL url=null;
Log.d("I m Here","2");
try {
url = new URL(fetchurl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
Log.d("I got Exception","3");
e.printStackTrace();
}
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db=null;
try {
db = dbf.newDocumentBuilder();
}
catch (ParserConfigurationException e1) {
e1.printStackTrace();
Log.d("I m Here","4");
}
Document doc=null;
try {
doc = db.parse(new InputSource(url.openStream()));
} catch (SAXException e2) {
// TODO Auto-generated catch block
Log.d("I m Here","5");
e2.printStackTrace();
} catch (IOException e3) {
// TODO Auto-generated catch block
Log.d("I m Here","6");
e3.printStackTrace();
}
org.w3c.dom.Element elt=doc.getDocumentElement();
NodeList nodeList = elt.getElementsByTagName(roottag);
temp=new String[nodeList.getLength()];
Log.d("the length of nodelist",Integer.toString(nodeList.getLength()));


for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);

NodeList titleList = node.getChildNodes();
Log.d("The length of titlelist",Integer.toString(titleList.getLength()));


for(int j=0;j<titleList.getLength();j++)
{
Node node1= titleList.item(j);
String name = node1.getNodeName();

if (name.equalsIgnoreCase(parseelemnt)) {

Log.d("J value"," "+j);
temp[i]=node1.getFirstChild()
.getNodeValue();

Log.d("temp value",temp[i]);
}
}
}



return(temp);


}

}



2 comments:

  1. if i have image url in the same xml how to parse that image and how to display that in my listview..can u plz help me out...

    ReplyDelete
  2. if i have CDATA tag inside xml files means,how to parse the text inside Cdata...

    ReplyDelete

Notification in Android Using AlarmManager, BoradCastReceiver & Services

    Our aim is to show notification message to user in a specific time.     Say For example , I have planned to show Notification ...