Thursday, 3 November 2011

XML parsing and asynchronously update the list-view

This is a sample demo application to understand that how the Interface works and how we can update the List view  at the time of XML parsing.I hope this will help you.

Below there are classes and XML for sample demo application

ListviewDemoActivity is the Activity for display products in List view

ListviewDemoActivity
=================

package com.example.listview;

import java.util.ArrayList;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class ListviewDemoActivity extends Activity implements OnFetchProduct{

Button btnLoad;
ListView lstProducts;
ArrayList<Product> arrProducts;
ProductAdapter adapter;

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btnLoad = (Button)findViewById(R.id.btnLoad);
        lstProducts = (ListView)findViewById(R.id.lstProducts);
     
        btnLoad.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
new LoadProductTask().execute();
}
});
     
        arrProducts = new ArrayList<Product>();
        adapter = new ProductAdapter();
        lstProducts.setAdapter(adapter);
    }

@Override
public void fetchProduct(Product product) {
arrProducts.add(product);
runOnUiThread(new Runnable() {

@Override
public void run() {
adapter.notifyDataSetChanged();
}
});
}

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


@Override
protected void onPreExecute() {
super.onPreExecute();
btnLoad.setText("Loading");
btnLoad.setEnabled(false);
}


@Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
btnLoad.setText("Load Products");
btnLoad.setEnabled(true);
}


@Override
protected Void doInBackground(Void... params) {
try {
ProductParser.parseProducts(ListviewDemoActivity.this, ListviewDemoActivity.this);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

}

private class ProductAdapter extends BaseAdapter {

@Override
public int getCount() {
return arrProducts.size();
}

@Override
public Object getItem(int position) {
return arrProducts.get(position);
}

@Override
public long getItemId(int id) {
return id;
}

@Override
public View getView(int position, View view, ViewGroup arg2) {
if(view == null) {
view = getLayoutInflater().inflate(R.layout.product_row, null);
}
view.setTag(arrProducts.get(position));
((TextView)view.findViewById(R.id.tvProductName)).setText(arrProducts.get(position).getName());
return view;
}

}
}


Interface OnFetchProduct 
========================

package com.example.listview;

public interface OnFetchProduct {

public void fetchProduct(Product product);
}


XML Parser ProductParser
=========================


package com.example.listview;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;

public class ProductParser {

private static final String PRODUCTS = "products";
private static final String PRODUCT = "product";
private static final String PRODUCT_NAME = "name";
private static final String PRODUCT_ID = "id";

public static boolean parseProducts(Context c, OnFetchProduct onFetchProductListener) throws Exception{

InputStream inputStream = c.getApplicationContext().getAssets().open("products.xml");
        if(inputStream == null) {
        throw new IOException("Input stream is null");
        }
String KEY;
String VALUE = null;
Product product = null;
try {
InputStreamReader inputreader = new InputStreamReader(inputStream);
XmlPullParserFactory factory = null;
factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(true);
XmlPullParser xpp = null;
xpp = factory.newPullParser();
xpp.setInput(inputreader);
int eventType = 0;
eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {

if(eventType == XmlPullParser.START_TAG) {
KEY = xpp.getName();
if(KEY.equalsIgnoreCase(PRODUCT)) {
product = new Product();
int prodId = Integer.parseInt(xpp.getAttributeValue(null, PRODUCT_ID));
}
VALUE = null;

} else if(eventType == XmlPullParser.END_TAG) {
KEY = xpp.getName();

if(KEY.equalsIgnoreCase(PRODUCT_NAME)) {
product.setName(VALUE);
}else if(KEY.equalsIgnoreCase(PRODUCT)) {
if(onFetchProductListener != null) {
onFetchProductListener.fetchProduct(product);
}
}else if(KEY.equalsIgnoreCase(PRODUCTS)) {
break;
}
} else if(eventType == XmlPullParser.TEXT) {
VALUE = xpp.getText();
}

eventType = xpp.next();
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
return true;
}
}


Product class
=======================

package com.example.listview;

public class Product {
String id;
String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}


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">
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp">
<Button android:id="@+id/btnLoad" android:layout_width="wrap_content"
android:layout_centerInParent="true" android:layout_height="wrap_content"
android:text="Load Products" />
</RelativeLayout>
<ListView android:id="@+id/lstProducts" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:fastScrollEnabled="true"></ListView>
</LinearLayout>


product_row.xml
=========================
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:padding="10dp">
<TextView android:id="@+id/tvProductName"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="Product Name" android:textStyle="bold" android:textSize="18dp"
android:textColor="#FFFFFF" />
</RelativeLayout>

=> NOTE:: Put  below products.xml file inside assets folder because we are reading xml file from assets

products.xml
=================

<?xml version="1.0" encoding="utf-8"?>
<root total="100">
<products>
<product id="1">
<name>ABC</name>
</product>
<product id="2">
<name>PQR</name>
</product>
<product id="3">
<name>ABC</name>
</product>
<product id="4">
<name>PQR</name>
</product>
<product id="5">
<name>ABC</name>
</product>
<product id="6">
<name>PQR</name>
</product>
<product id="7">
<name>ABC</name>
</product>
<product id="8">
<name>PQR</name>
</product>
<product id="9">
<name>ABC</name>
</product>
<product id="10">
<name>PQR</name>
</product>
<product id="11">
<name>ABC</name>
</product>
<product id="12">
<name>PQR</name>
</product>
</products>
</root>

No comments:

Post a Comment