Two methods of implementing ListView dynamic Loading Data paging by Android _android

Source: Internet
Author: User
Tags int size message queue stub

In Android development, it is often necessary to use data paging, such as to achieve a news list display, or the list of posts can not be displayed in the first load, it is necessary to use a paging method to load data, in Android handler is often used in time-consuming work, It receives the data sent by the child thread and uses the data to match the update ui,asynctask is executing time-consuming operations in one thread and passing the results to the UI thread, without you having to manage the threads and handles yourself.

First, using the handler+ threading method
1. Basic knowledge
Handler in the Android system, mainly responsible for sending and receiving messages, it is mainly used in the following two kinds:
(1) Process a message (SendMessage) according to schedule or execute a Runnable instance (post (Runnable) method)
(2) Put other thread objects into message queues to avoid threading conflicts.
Messages are sent via post (Runnable), Postattime (Runnable, Long), postdelayed (Runnable, Long), sendemptymessage (int), SendMessage ( Message), the Sendmessageattime (message, long) and the sendmessagedelayed (message, long) method are complete. For the Postxxx method, the Runnable object is given to the message queue and invoked after the message queue arrives. For the Sendmessagexxx method, passes a containing message object that can be processed by the Handlermessage (message) method of the handler class.
2. Main code

public class Handlerdemo extends activity implements Onscrolllistener {private ListView mlistview;
 LinearLayout loadinglayout;
 Private Thread Mthread;

 Private Listviewadapter adapter;
 private int startIndex = 1;//starting from 1th private int size = 10;//Download 10 data each time private list<news> newslist;

 list<map<string, string>> data; * * Set layout Display Properties/private layoutparams mlayoutparams = new Layoutparams (LinearLayout.LayoutParams.WRAP_CONTENT, Lin

 EarLayout.LayoutParams.WRAP_CONTENT); Private Layoutparams fflayoutparams = new Layoutparams (LinearLayout.LayoutParams.FILL_PARENT, Linearlayout.layoutpar Ams.

 Fill_parent);

 Private ProgressBar ProgressBar; @Override protected void OnCreate (Bundle savedinstancestate) {//TODO auto-generated Method stub super.oncreate (Savedi
 Nstancestate);
 Setcontentview (R.layout.news_main);
 Data=new arraylist<map<string, string>> ();
 AddView (); private void AddView () {if (StartIndex = 1) {newslist = newArraylist<news> ();
 Newslist = Getnewslist ();
 } getdata (Newslist);
 LinearLayout layout = new LinearLayout (this);
 Layout.setorientation (linearlayout.horizontal);
 ProgressBar = new ProgressBar (this);
 Layout.addview (ProgressBar, mlayoutparams);
 TextView TextView = new TextView (this);
 Textview.settext ("Load ...");
 Textview.setgravity (gravity.center_vertical);
 Layout.addview (TextView, fflayoutparams);
 Layout.setgravity (Gravity.center);
 Loadinglayout = new LinearLayout (this);
 Loadinglayout.addview (layout, mlayoutparams);

 Loadinglayout.setgravity (Gravity.center);
 Get a ListView to display entries Mlistview = (ListView) Findviewbyid (R.id.listview);
 Mlistview.addfooterview (loadinglayout);
 adapter = new Listviewadapter ();
 Mlistview.setadapter (adapter);
 Mlistview.setonscrolllistener (this);
 Mlistview.settextfilterenabled (TRUE);
 @Override public void Onscroll (Abslistview view, int firstvisibleitem, int visibleitemcount, int totalitemcount) { TODO Auto-generated Method Stub if (firstvisibleitem + visibleitemcount = = Totalitemcount) {if (Mthread = = NULL | |!mthread.isalive ()) {Mthread =
   New Thread () {@Override public void run () {newslist = new arraylist<news> ();
   Newslist = Getnewslist ();
   GetData (newslist);
   msg = new Message ();
   Msg.what = 1;
   Handler.sendmessage (msg);
  }
  };
  Mthread.run (); }} Handler Handler = new Handler () {@Override public void Handlemessage (msg) {//TODO auto-generate
  D method Stub if (Msg.what = 1) {StartIndex = startIndex + size;
  LOG.V ("startindex", startindex + "");
  Mlistview.removefooterview (loadinglayout);
  Mthread.stop ();
  Adapter.count + = size;
  Adapter.notifydatasetchanged ();
  Return

 }
 }
 };

 Class Listviewadapter extends Baseadapter {int count = 10;
 @Override public int GetCount () {//TODO auto-generated method stub return count; @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 St
  UB Convertview = Layoutinflater.from (Getapplicationcontext ()). Inflate (R.layout.news_item, NULL);
  TextView TextView = (TextView) convertview. Findviewbyid (R.id.textnewstitle);
  Textview.settext ((data.get (position)). Get ("title");
 return convertview; @Override public void onscrollstatechanged (Abslistview view, int scrollstate) {//TODO auto-generated method Stu
 b} private list<map<string, string>> GetData (list<news> list) {if (list = = null) return null;
  for (News news:list) {map<string, string> Map = new hashmap<string, string> ();
  Map.put ("title", News.gettitle ());
 Data.add (map);
 } return data; * * * Get network data NOTE: I am accessing the local news service, using the ASP.net technology to achieve * This is a project is an Android based information broadcast softPiece * * Private list<news> getnewslist () {String path = "Http://10.0.2.2/getNewsList.aspx"; String xmlstr = "<?xml version= ' 1.0 ' encoding= ' utf-8 '"? ><source><categoryids>1,3,7</categoryids ><startIndex> "+ StartIndex +" </startIndex><detail>2</detail><count> "+ size +"
 </count></source> ";
 Newsconnector newsconnector = new Newsconnector ();
 list<news> list = new arraylist<news> ();
 List = newsconnector.getnewslist (path, XMLSTR);
 return list;

 }
}

3. Summary
The steps to dynamically load data using the Handler+ threading method are as follows: ListView
1. Initialize the page first (for example: Load the first page of data)
2. After receiving the message of an event (the above code is a onscroll event), start the thread (the thread completes downloading the data and sends the message to handler)
3.handler updates the interface after receiving the message and displays the data.

Ii. use of Asynctask method
1. Basic knowledge
Asynctask is also a class that Android offers to not block the main thread, Asynctask defines three generic types params, progress, and Result,params start task execution input parameters. For example, HTTP request URL and parameters, progress background to perform the percentage of tasks, background to perform the final return results.
Asynctask's execution is divided into four steps, each corresponding to a callback method, the developer needs to implement one or several methods, in the execution of the task, these methods will be automatically invoked.
OnPreExecute () is called before performing a background time-consuming operation, and you can do some UI actions in this method, such as displaying a progress bar, etc.
Doinbackground (Params ...), this method executes after OnPreExecute (), this method completes time-consuming work, such as downloading.
Onprogressupdate (Progress ...), the UI thread obtains the completion of the task through this method, such as the percentage of the completed task.
OnPostExecute (Result), which is invoked after time-consuming work has been completed. The UI thread calls this method to obtain the result.
Note: There are several guidelines to follow in using the Asynctask class
(1) An instance of a task must be created in the UI thread
(2), the Execute method must be called in the UI thread
(3), do not manually call the above four methods
(4), this task is only executed once (if the second execution will throw an exception)
2. Main code

@Override public void Onscroll (Abslistview arg0, int arg1, int arg2, int arg3) {//TODO auto-generated method stub if
 (ARG1+ARG2==ARG3)
  {if (!isloading) {new Myasynctask (). Execute (NULL);
  else {Mlistview.removefooterview (loadinglayout);
 
 @Override public void onscrollstatechanged (Abslistview arg0, int arg1) {//TODO auto-generated method stub Private class Myasynctask extends Asynctask<void, void, void> {@Override protected Void doinbackground (Vo
  ID ... params) {//TODO auto-generated method Stub newslist = new Arraylist<news> ();
  Newslist = Getnewslist ();
  GetData (newslist);
  
 return null; @Override protected void OnPostExecute (void result) {//TODO auto-generated Method stub Super.onpostexecute (resu
  LT);
  Adapter.count+=size;
  Adapter.notifydatasetchanged ();
  Startindex+=size;
 Isloading=false; @Override protected void OnPreExecute () {//TODO auto-generated method Stub Super.onpreexecute ();
 Isloading=true;

 }
 
 }

Note: The above is only a different code and the use of handler+ threading method, recommended download Source: Http://xiazai.jb51.net/201606/yuanma/NewsList (jb51.net). RAR, understand the detailed code
3. Summary
ListView The method of dynamically loading data using the Asynctask method is as follows:
1. Initialize the page like handler (for example: Load first page)
2. After receiving the message for an event (the above code is the Onscroll event), create a new asynchronous task and start executing
3. After the time-consuming work completes, starts to update the UI

Third, summary
Comparison of ListView dynamic loading using the handler+ thread and using the Asynctask method
handler+ Threading Method:
When using the handler method, it involves handler, Thread, message, Looper four objects, in the following process: The main thread starts a thread, this thread executes the time-consuming operation, and the time-consuming operation completes, generates a message, Looper reads the message and passes it to the UI for Hander,handler to receive messages and update the response. Because looper after a message processing, will read the next one, if multiple messages will form a queue, so it is more clear to the background operation, clear. But for a single message it appears to be more code, too complex.
Asynctask Way:
Asynctask inherits from Object and is a lightweight asynchronous class provided by Android. and provides a way to get the execution progress of the task (you can update the UI according to it) and finally return the result to the main thread. This approach is simpler, and you can clearly see the progress of time-consuming task execution. However, it becomes more complex to have multiple asynchronous operations at the same time and update the UI.

Screenshot on attachment

Reference article: Android ListView Dynamic Load list item implementation code

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.