In this tutorial i am discussing about adding load more functionality to listview. It will be useful when you want to show data into paged format instead of loading huge amount of data into listview.

Download Code

Paged XML data

For this tutorial i am accessing an url which will give you paged XML by taking page number. Each page contains 20 results. You can access the xml by accessing url https://api.androidhive.info/list_paging/?page=1. This url accepts “page” (page number – 1, 2, 3 ..) parameter as a GET variable. The sample response will be

<menu>
  <item>
     <id>1</id>
     <name>sample list data 1</name>
  </item>
  <item>
     <id>2</id>
     <name>sample list data 2</name>
  </item>
  .
  .
  .
  <item>
     <id>20</id>
     <name>sample list data 20</name>
  </item>
<item>

You can prepare your own json or xml data with paging option. Example like displaying mysql data by taking page number.

Adding button to ListView at the bottom

You can add a view at the bottom of the listview by using addFooterView method. In this tutorial i am adding a button to the bottom of the listview.

// Getting listview from xml
ListView lv = (ListView) findViewById(R.id.list);

// Creating a button - Load More
Button btnLoadMore = new Button(this);
btnLoadMore.setText("Load More");

// Adding button to listview at footer
lv.addFooterView(btnLoadMore);

Running a Asynchronous Background Thread

We need a background thread while sending http request in order to get new data for listview. Following is a example of Async Background task.

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

		@Override
		protected void onPreExecute() {
		   // Before starting background task
		   // Show Progress Dialog etc,.
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
                // Run actual background task
                // Like sending HTTP Request - Parsing data
				}
			});
			return (null);
		}

		protected void onPostExecute(Void unused) {
			// On completing background task
			// closing progress dialog etc,.
		}

Calling a background thread

// calling a background task
new YourBackgroundThreadName().execute();

Create new Project

1. Create a new project by going to File ⇒ New ⇒ Android Project and fill all the required details.
2. Open your main.xml and add a listview element in it.

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

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

</LinearLayout>

3. Create a new XML layout for single list row item under layouts folder.
Right Click on res ⇒ New ⇒ Android XML File and fill with following code. Name the xml file as list_item.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="wrap_content"
    android:orientation="horizontal">  

        <!-- List item name -->
        <TextView
            android:id="@+id/name"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:textColor="#acacac"
            android:textStyle="bold"
            android:gravity="left"
            android:padding="10dip"
            android:textSize="16dp">
        </TextView>
</LinearLayout>

4. Create a new class and name it as ListViewAdapter.java and fill with following code. This class is required to fill the listview with parsed xml data. I just displayed single text view.

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class ListViewAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;

    public ListViewAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.list_item, null);

        TextView name = (TextView)vi.findViewById(R.id.name);

        HashMap<String, String> item = new HashMap<String, String>();
        item = data.get(position);

        //Setting all values in listview
        name.setText(item.get("name"));
        return vi;
    }
}

5. Now open your MainActivity try the following code. In the following code i am just displaying data into listview by parsing XML. Finally i added a load more button to the bottom to listview

public class AndroidListViewWithLoadMoreButtonActivity extends Activity {

	// All variables
	XMLParser parser;
	Document doc;
	String xml;
	ListView lv;
	ListViewAdapter adapter;
	ArrayList<HashMap<String, String>> menuItems;
	ProgressDialog pDialog;

	private String URL = "https://api.androidhive.info/list_paging/?page=1";

	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "name";

	// Flag for current page
	int current_page = 1;

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

		lv = (ListView) findViewById(R.id.list);

		menuItems = new ArrayList<HashMap<String, String>>();

		parser = new XMLParser();
		xml = parser.getXmlFromUrl(URL); // getting XML
		doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// LoadMore button
		Button btnLoadMore = new Button(this);
		btnLoadMore.setText("Load More");

		// Adding Load More button to lisview at bottom
		lv.addFooterView(btnLoadMore);

		// Getting adapter
		adapter = new ListViewAdapter(this, menuItems);
		lv.setAdapter(adapter);
	}
}
android listview with load more button

Working with Load More Button

Until now we displayed a simple listview with the first paged xml data. Now we need to add functionality to load more button. Add a click event listener to load more button and call a background thread which will append next paged data to listview.

Appending data to listview is nothing but appending data into adapter array. If you write your own Custom Adapter you need to call notifyDataSetChanged() on the adapter class in order to refresh list view. (For reference check this question: Dynamic ListView in Android app)

6. Add a click event listener to LoadMore button in your MainActivity Class and start a new background thread once it is clicked.

/**
* Listening to Load More button click event
* */
btnLoadMore.setOnClickListener(new View.OnClickListener() {
	@Override
	public void onClick(View arg0) {
		// Starting a new async task
		new loadMoreListView().execute();
	}
});

7. Now after closing onCreate Method write a background thread class like below. In the following code i am making a HTTP request with next page number. After getting the new paged data i am parsing it and loading into listview. Once the listview is appended with new data i am setting scroll position using setSelectionFromTop() method.

	/**
	 * Async Task that send a request to url
	 * Gets new list view data
	 * Appends to list view
	 * */
	private class loadMoreListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog = new ProgressDialog(
					AndroidListViewWithLoadMoreButtonActivity.this);
			pDialog.setMessage("Please wait..");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
					// increment current page
					current_page += 1;

					// Next page request
					URL = "https://api.androidhive.info/list_paging/?page=" + current_page;

					xml = parser.getXmlFromUrl(URL); // getting XML
					doc = parser.getDomElement(xml); // getting DOM element

					NodeList nl = doc.getElementsByTagName(KEY_ITEM);
					// looping through all item nodes <item>
					for (int i = 0; i < nl.getLength(); i++) {
						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();
						Element e = (Element) nl.item(i);

						// adding each child node to HashMap key => value
						map.put(KEY_ID, parser.getValue(e, KEY_ID));
						map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

						// adding HashList to ArrayList
						menuItems.add(map);
					}

					// get listview current position - used to maintain scroll position
					int currentPosition = lv.getFirstVisiblePosition();

					// Appending new data to menuItems ArrayList
					adapter = new ListViewAdapter(
							AndroidListViewWithLoadMoreButtonActivity.this,
							menuItems);

					// Setting new scroll position
					lv.setSelectionFromTop(currentPosition + 1, 0);
				}
			});
			return (null);
		}		

		protected void onPostExecute(Void unused) {
			// closing progress dialog
			pDialog.dismiss();
		}
	}

Final Code

The final code of the MainActivity class is

package com.example.androidhive;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class AndroidListViewWithLoadMoreButtonActivity extends Activity {

	// All variables
	XMLParser parser;
	Document doc;
	String xml;
	ListView lv;
	ListViewAdapter adapter;
	ArrayList<HashMap<String, String>> menuItems;
	ProgressDialog pDialog;

	private String URL = "https://api.androidhive.info/list_paging/?page=1";

	// XML node keys
	static final String KEY_ITEM = "item"; // parent node
	static final String KEY_ID = "id";
	static final String KEY_NAME = "name";

	// Flag for current page
	int current_page = 1;

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

		lv = (ListView) findViewById(R.id.list);

		menuItems = new ArrayList<HashMap<String, String>>();

		parser = new XMLParser();
		xml = parser.getXmlFromUrl(URL); // getting XML
		doc = parser.getDomElement(xml); // getting DOM element

		NodeList nl = doc.getElementsByTagName(KEY_ITEM);
		// looping through all item nodes <item>
		for (int i = 0; i < nl.getLength(); i++) {
			// creating new HashMap
			HashMap<String, String> map = new HashMap<String, String>();
			Element e = (Element) nl.item(i);
			// adding each child node to HashMap key => value
			map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
			map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

			// adding HashList to ArrayList
			menuItems.add(map);
		}

		// LoadMore button
		Button btnLoadMore = new Button(this);
		btnLoadMore.setText("Load More");

		// Adding Load More button to lisview at bottom
		lv.addFooterView(btnLoadMore);

		// Getting adapter
		adapter = new ListViewAdapter(this, menuItems);
		lv.setAdapter(adapter);

		/**
		 * Listening to Load More button click event
		 * */
		btnLoadMore.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Starting a new async task
				new loadMoreListView().execute();
			}
		});

		/**
		 * Listening to listview single row selected
		 * **/
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// getting values from selected ListItem
				String name = ((TextView) view.findViewById(R.id.name))
						.getText().toString();

				// Starting new intent
				Intent in = new Intent(getApplicationContext(),
						SingleMenuItemActivity.class);
				in.putExtra(KEY_NAME, name);
				startActivity(in);
			}
		});
	}

	/**
	 * Async Task that send a request to url
	 * Gets new list view data
	 * Appends to list view
	 * */
	private class loadMoreListView extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			// Showing progress dialog before sending http request
			pDialog = new ProgressDialog(
					AndroidListViewWithLoadMoreButtonActivity.this);
			pDialog.setMessage("Please wait..");
			pDialog.setIndeterminate(true);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		protected Void doInBackground(Void... unused) {
			runOnUiThread(new Runnable() {
				public void run() {
					// increment current page
					current_page += 1;

					// Next page request
					URL = "https://api.androidhive.info/list_paging/?page=" + current_page;

					xml = parser.getXmlFromUrl(URL); // getting XML
					doc = parser.getDomElement(xml); // getting DOM element

					NodeList nl = doc.getElementsByTagName(KEY_ITEM);
					// looping through all item nodes <item>
					for (int i = 0; i < nl.getLength(); i++) {
						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();
						Element e = (Element) nl.item(i);

						// adding each child node to HashMap key => value
						map.put(KEY_ID, parser.getValue(e, KEY_ID));
						map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

						// adding HashList to ArrayList
						menuItems.add(map);
					}

					// get listview current position - used to maintain scroll position
					int currentPosition = lv.getFirstVisiblePosition();

					// Appending new data to menuItems ArrayList
					adapter = new ListViewAdapter(
							AndroidListViewWithLoadMoreButtonActivity.this,
							menuItems);
					lv.setAdapter(adapter);
					// Setting new scroll position
					lv.setSelectionFromTop(currentPosition + 1, 0);

				}
			});

			return (null);
		}

		protected void onPostExecute(Void unused) {
			// closing progress dialog
			pDialog.dismiss();
		}
	}
}

Other Classes needed in this project

XMLParser.java – needed to parse xml data

package com.example.androidhive;

import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
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 XMLParser {

	// constructor
	public XMLParser() {

	}

	/**
	 * Getting XML from URL making HTTP request
	 * @param url string
	 * */
	public String getXmlFromUrl(String url) {
		String xml = null;

		try {
			// defaultHttpClient
			DefaultHttpClient httpClient = new DefaultHttpClient();
			HttpPost httpPost = new HttpPost(url);

			HttpResponse httpResponse = httpClient.execute(httpPost);
			HttpEntity httpEntity = httpResponse.getEntity();
			xml = EntityUtils.toString(httpEntity);

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// return XML
		return xml;
	}

	/**
	 * Getting XML DOM element
	 * @param XML string
	 * */
	public Document getDomElement(String xml){
		Document doc = null;
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			DocumentBuilder db = dbf.newDocumentBuilder();

			InputSource is = new InputSource();
		        is.setCharacterStream(new StringReader(xml));
		        doc = db.parse(is); 

			} catch (ParserConfigurationException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			} catch (SAXException e) {
				Log.e("Error: ", e.getMessage());
	            return null;
			} catch (IOException e) {
				Log.e("Error: ", e.getMessage());
				return null;
			}

	        return doc;
	}

	/** Getting node value
	  * @param elem element
	  */
	 public final String getElementValue( Node elem ) {
	     Node child;
	     if( elem != null){
	         if (elem.hasChildNodes()){
	             for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
	                 if( child.getNodeType() == Node.TEXT_NODE  ){
	                     return child.getNodeValue();
	                 }
	             }
	         }
	     }
	     return "";
	 }

	 /**
	  * Getting node value
	  * @param Element node
	  * @param key string
	  * */
	 public String getValue(Element item, String str) {
			NodeList n = item.getElementsByTagName(str);
			return this.getElementValue(n.item(0));
		}
}
This image is for thumbnail purpose.
android listview with load more button
Subscribe
Notify of
guest
123 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
RPGtoPlay
7 years ago

Nice tutorial.

Thet Paing
Thet Paing
7 years ago

I want to add previous and next button in your application like this link http://stackoverflow.com/questions/15376995/getting-next-and-previous-detail-data-from-listview I want to full tutorial. thanks brother

Thet Paing
Thet Paing
7 years ago
Reply to  Thet Paing

Now, I finished my request tutorial. Thanks your tutorial ……..

sKoyce
sKoyce
7 years ago

i think you have to use for this tutorial with JsonParser

Sumeet Rathore
Sumeet Rathore
5 years ago
Reply to  sKoyce

have you got the answer how do it with JSONParser please help me..

Rekz
Rekz
5 years ago
Reply to  Sumeet Rathore

This is how I did it, I used HttpClient in a AsyncTask to get the JSON. Once you have the JSON string, use JSON reader API (JSONObject etc) to load you separate fields into arraylist. The rest you do it like he did it. I hope that helps

Gonzalo Benoffi
7 years ago

Great example!!!!! You save the day! Thanks a lot!

andriangungon
andriangungon
7 years ago

sir the application has error when I changed the minimum sdk at 10 or above in android manifest. Please help sir. Thanks!

10-03 13:00:10.944: E/AndroidRuntime(2499): FATAL EXCEPTION: main
10-03 13:00:10.944: E/AndroidRuntime(2499): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.androidhive/com.example.androidhive.MainActivity}: android.os.NetworkOnMainThreadException

Ravi Tamada
7 years ago
Reply to  andriangungon

This is old tutorial. Try keeping all network calls code in Async Task

andriangungon
andriangungon
7 years ago

great tutorial sir. I changed to asynctask onload and my problem is the dialog box is not showing. Please help sir. Thanks in advanced.

here is the code sir:

private class loadVideos extends AsyncTask {
protected void onPreExecute() {
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage(“Please wait..”);
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}

protected Void doInBackground(Void… unused) {

runOnUiThread(new Runnable() {
public void run() {
list = (ListView) findViewById(R.id.list);
menuItems = new ArrayList<HashMap>();
parser = new XMLParser();
xml = parser.getXmlFromUrl(URL); // getting XML
doc = parser.getDomElement(xml); // getting DOM element
NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes

for (int i = 0; i < nl.getLength(); i++) {
HashMap map = new HashMap();
Element e = (Element) nl.item(i);
map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
map.put(KEY_VIEWS, parser.getValue(e, KEY_VIEWS));
map.put(KEY_THUMB_URL, parser.getValue(e, KEY_THUMB_URL));
menuItems.add(map);
}

adapter = new ListViewAdapter(MainActivity.this, menuItems);
list.setAdapter(adapter);
}

});

return (null);
}

protected void onPostExecute(Void unused) {

// closing progress dialog

pDialog.dismiss();

}

}

andriangungon
andriangungon
7 years ago

sir when i removed runOnUIThread, I got an error, please help sir I newbie in android dev. Thanks sir.

andriangungon
andriangungon
7 years ago

finally I got it sir…

andriangungon
andriangungon
7 years ago

sir there’s an error when all the data has been loaded. I got an error when i click again the loadmore. How to check sir if all the data are loaded already? Please help sir. thanks! more power!

andriangungon
andriangungon
7 years ago

Yeah! I also learned a lot from this website! The best!

Rupesh
Rupesh
6 years ago

Sir i followed your tutorials and its really working very well, I only
have one question on how to add load more function on Scroll moving. Please
consider me. Thanks.

imran RP
imran RP
6 years ago

good example thank you ,, it is usefull for me.

george
george
6 years ago

Hi all. I am a novice in developing app and thanks to
Ravi for all good work that is doing . I’m working at a simple app and I get
stuck . if you have knowledge of
building android apps, and make team
with me please replay to george.celsie@gmail.com . Thanks ang
good luck for all your projects.

Afifatul M
Afifatul M
6 years ago

HI GOEIHIONGKUEK, could u tell me how to mix it with json? I have no idea about how to create paging in mysql database. 🙁

Sruthi
Sruthi
6 years ago

Hi,
This looks good, but where are you removing the load more button once the list is completly loaded? Can you provide the snippet for that?

sruthi
sruthi
6 years ago

Hi,
This looks good, but where are you removing the load more button once the list has reached the end? Can you provide the snippet for that?

Qb Dudez
Qb Dudez
5 years ago

have you figure out the solution? i also want to append the new data

Sumeet Rathore
Sumeet Rathore
5 years ago

how to do it with JSON Parser please help me out ??

phan piseth
phan piseth
5 years ago

how to do with JSON?

phan piseth
phan piseth
5 years ago

can you show your this web service?

Ram Chandran
Ram Chandran
4 years ago

Wow, it’s working fine. Thanks

Sonu Kunwar
Sonu Kunwar
4 years ago

hi ravi …………..i m getting error on this ,not even option coming to import this class DefaulthttpClient ….i m trying to doing this project in android studio.

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();

Arslanali
Arslanali
4 years ago

Hello, you have php files?

Arslanali
Arslanali
4 years ago

Hello Ravi. You could not put you php file in “download code”?

Omis
Omis
4 years ago

Hi Ravi , I tried your code but I found a problem , this one is when I press the Load more button the listview contains the new list of items not the old one plus the new data , it’s like the items are removed and be replaced by the new ones , how can I fix this ?

Lhufi Luthfi
Lhufi Luthfi
3 years ago

Android ListView with Load More Button for json ?

Ravi Tamada
3 years ago
Reply to  Lhufi Luthfi

Read this tutorial to know how to load json into listview.
http://www.androidhive.info/2015/05/android-swipe-down-to-refresh-listview-tutorial/

Lhufi Luthfi
Lhufi Luthfi
3 years ago
Reply to  Ravi Tamada

thanks

Hafiz Oktri Putra
Hafiz Oktri Putra
3 years ago

can you tell any way to parse the paging if I use these json objects?

“paginator”: {
“total_items”: 5007,
“total_pages”: 501,
“items_per_page”: 10,
“current_page”: 1,
“items_start”: 1,
“items_end”: 10
},

I want to make the the “current_page” change when I press the Load More button

Amit
Amit
2 years ago

“paginator”: {
“total_items”: 5007,
“total_pages”: 501,
“items_per_page”: 10,
“current_page”: 1,
“items_start”: 1,
“items_end”: 1
}
its possible

Nitin Bansal
Nitin Bansal
8 years ago

100% genius!!!…way to go dude…

tpl
tpl
8 years ago

Thank you for this! How is it possible to do the same with JSON instead of XML?

anass belghiti
anass belghiti
8 years ago

Thanks for this man, i would like to know if it’s likly to use parsXml to parse a local File??

Emma
Emma
8 years ago

Another great tutorial, thanks.

Doctor_jr17
Doctor_jr17
8 years ago

execellent. thanks. do you have tutorial about parsing json data to listview in fragment like this http://www.broculos.net/en/article/android-101-use-fragments-handle-different-screen-orientations

Ravi Tamada
8 years ago
Reply to  Doctor_jr17

No i don’t have.

issoa
issoa
8 years ago

Hi Ravi,

Thanks for the new tut….

How can I do the same thing with using the AsyncTasks as separate public classes? rather than creating a private class in the same activity class.

I goggled and non I find that uses external public class for AsyncTask

any thoughts?

Ravi Tamada
8 years ago
Reply to  issoa

You can do that easily but find a way to access one class elements from other class. You may need to pass Context to another class.

Poker Agenda
8 years ago

nice tutorial Ravi!! very handy as all of you tutorials
thanks again !

Ravi Tamada
8 years ago
Reply to  Poker Agenda

I am glad you enjoyed all my posts 🙂

Eliysha243
Eliysha243
8 years ago

Hello Ravi!
I had to develop an android market like app but I don’t know how to design the UI.
Can you help me ?

thank you

Ravi Tamada
8 years ago
Reply to  Eliysha243

I can guide You. Where you want my help

Eliysha243
Eliysha243
8 years ago
Reply to  Ravi Tamada

thanks for your help 🙂
I don’t know which elements I should use.
Here is my need :
First view :
– an action bar
– a layout which contains some images (scrollable)
– an another layout which contains app by category or price

second view :
allow to show an app description and to make order

Eliysha243
Eliysha243
8 years ago
Reply to  Ravi Tamada

For other view I will use some of your tuto to do that

Asma
Asma
8 years ago
Reply to  Ravi Tamada

very good tuto thxx
plzz ravi can you help me to create my BDD for my project ??

IS SOA
IS SOA
8 years ago

Ravi, i have a question regards to your design, does it make more sense to add XMLParser in doinBackground (AsyncTask) ? … i have been thinking of what is the best approach to take.. and in my opinion if you put the XMLParser in the AsyncTask then will retrieve quick data from HttpGet?

make sense? any thoughts?

Ravi Tamada
8 years ago
Reply to  IS SOA

Ya its good idea to put xml parser in AsyncTask and i already did the same right.

Issoa99
Issoa99
8 years ago
Reply to  Ravi Tamada

If you look at the oncreate method it’s not using Asynctask but it’s calling asynctask when you click on loadmore button… Do you see that???

Ravi Tamada
8 years ago
Reply to  Issoa99

Ya, i just extended previous article. Just to avoid confusion i didn’t added async for oncreate method. You should add async for that.

IS SOA
IS SOA
8 years ago
Reply to  Ravi Tamada

so, if i add the asynctask in oncreate method then i will be appending ListViewAdapter arraylist in onPostExecute? is that correct?

Ravi Tamada
8 years ago
Reply to  IS SOA

yes

Persian Dev
Persian Dev
8 years ago

Hi.

Thanks for useful article. I have been searching around for some thing like that cause I did not know how to handle asynctask.
I used your way to load my data from sqlite db to list view, but the progress dialog box does not appear, although it reaches the dismiss part. What is wrong do you think ?

Regards.

Persian Dev
Persian Dev
8 years ago

Sorry I meant the dialog box does not “disappear” ….

Bituteh2
Bituteh2
8 years ago

great tutorial:) i think would be great to create some day a tut for expandable list view:)

IS SOA
IS SOA
8 years ago

Ravi: how you doing with paging? i am bit confused where you have a full list vs paging and if i go to your site and “http://api.androidhive.info/list_paging/?page=2342342”; where is the pulling information data code? can you shed some more light? if i go to this url still showing me the 20 items “http://api.androidhive.info/list_paging/”,…. so how many total items you have? i know lot of questions but just would like to to know 🙂

Ravi Tamada
8 years ago
Reply to  IS SOA

I did it in php by running for loop. There is no limit to data. I displayed sample data by taking page number and adding some 20 results to it. If there is no page number i am displaying first 20 results.

If you want to displaying paging data from getting information from database, you can show details until the results array is nil.

I am giving you my php code:
0) ? $_GET[‘page’] : 1;
$page = $page – 1;

// Page Size
$page_size = 20;

// xml data to print
$xml = ”;

// looping to print xml
for($i = ($page * $page_size + 1); $i <= ($page * $page_size + $page_size); $i++){
$xml .= '’;
$xml .= ”.$i.”;
$xml .= ‘sample list data ‘.$i.”;
$xml .= ”;
}

// closing xml
$xml .= ”;

// writing xml headers
header (“Content-Type:text/xml”);

// printing xml
echo $xml;
?>

IS SOA
IS SOA
8 years ago
Reply to  Ravi Tamada

thanks for the reply, what if; if i am not using any db? i have a big xml file over 100+ items in that xml and how would you do paging with that xml?

Ravi Tamada
8 years ago
Reply to  IS SOA

You need to find a way to parse that xml on the server side and display paged data to mobile.

If we load complete xml on mobile and parse, and showing paged data is meaning less. Loading such a big xml on mobile is probably bad idea and will cause you app to hang.

Prince
Prince
8 years ago

can you give code for synchronizing transactions in php file accessed by an android application?

new
new
8 years ago

it is really helpful for me,

Praveen
Praveen
8 years ago

Nice article 🙂

The name of the list item is sent to SingleMenuItemActivity using in.putExtra(KEY_NAME, name)
Similarly how can I access the KEY_ID of the list-item(or any other property) to send it to the SingleMenuItemActivity?

AnggriAone
AnggriAone
8 years ago

How to make it in Json ?

Kishore
Kishore
8 years ago

Hi Ravi, Thank you for such a nice tutorials about android applications..

I am building an android application with listview and populating the result from XML file.
On update, how can i delete all items from list view and add the refresh items to the same???

Ravi Tamada
8 years ago
Reply to  Kishore

You can keep all the xml parsing, updating to listview in functions. Once the item row is deleted from listview. You can those functions to update listview again.

Kishore
Kishore
8 years ago
Reply to  Ravi Tamada

Can i get some working example on it.

LC
LC
8 years ago

Thank you for all your great tutorials. I’m trying to have the listview with tabs along the top. I can’t seem to integrate the things in your lesson to have the listview “embedded” and show below the tabs. I get a force close error.

Any ideas?

Ravi Tamada
8 years ago
Reply to  LC

Check your log cat for errors.

LC
LC
8 years ago

Seems to be a null pointer exception. The tab and view loads fine (without the list) if I remove the lines below. I have narrowed it down, and it happens with the doc = parser.getDomElement(xml) line. The standalone code you provided works fine. I have gone over my implementation a few times to make sure I have made the appropriate changes to layout files as well.

doc = parser.getDomElement(xml); // getting DOM element

NodeList nl = doc.getElementsByTagName(KEY_ITEM);
// looping through all item nodes
for (int i = 0; i < nl.getLength(); i++) {
// creating new HashMap
HashMap map = new HashMap();
Element e = (Element) nl.item(i);
// adding each child node to HashMap key => value
map.put(KEY_ID, parser.getValue(e, KEY_ID)); // id not using any where
map.put(KEY_NAME, parser.getValue(e, KEY_NAME));

// adding HashList to ArrayList
menuItems.add(map);
}

If it matters, I have a MainScreen activity which extends TabActivity and creates the 4 tabs. I have the code in one of the tab activity classes.

LC
LC
8 years ago
Reply to  LC

Nevermind…I figured it out. You didn’t mention you needed the following line in the AndroidManifest.xml file

Ravi Tamada
8 years ago
Reply to  LC

Hi LC,

Thanks for notifying me. I will update this post.

Mio
Mio
8 years ago

hey hie ravi…Thank you again for this great tutorial also..Well i have one question regarding this post.I have implemented the same code in my app.And the new 10 datas are not getting appended.Rather they seem to replace the already existing 10 datas.Can you please guide me as to what may be the problem.As all the datas are getting updated but are not getting added to the already existing datas you can check this peice of code also

/ /get listview current position – used to maintain scroll position
int currentPosition = lview.getFirstVisiblePosition();
     
// Appending new data to menuItems ArrayList
adapter = new myAdapter(MainActivity.this, listItem, listFtext, stringArray);
lview.setAdapter(adapter);
     
// Setting new scroll position
lview.setSelectionFromTop(currentPosition + 1, 0);

Thanks in advance Ravi

Nitin
Nitin
8 years ago

how to add text and chronometer in a row dynamically in listview in Android?

GOEIHIONGKUEK
GOEIHIONGKUEK
8 years ago

hi…how can i change get xml data to php json data?

Ravi Tamada
8 years ago
Reply to  GOEIHIONGKUEK

Please check my JSON Parsing tutorial.

GOEIHIONGKUEK
GOEIHIONGKUEK
8 years ago
Reply to  Ravi Tamada

hi…thanks..i have mix it with json data already..
i need to hide the button when it go to the last page, how should i do?

Ravi Tamada
8 years ago
Reply to  GOEIHIONGKUEK

You need to check is json has empty results hide the button.

123
0
Would love your thoughts, please comment.x
()
x