How to load a ListView using AsyncTask in android -
i have method called fetchdata() fetch data database , load listview. when activity starts there small lag because of this. need load data in background. wondering if tell me how using asynctask.
this fetchdata() method.
public void fetchdata() { database = helper.getreadabledatabase(); cursor c; date cdate = new date(); simpledateformat sdf=new simpledateformat("yyyy-mm-dd"); final string fdate = sdf.format(cdate); int thismonth=integer.parseint(fdate.split("-")[1]); month mn=new month(); string month=mn.getmonth(thismonth); calendar cal=calendar.getinstance(); int today=integer.parseint(fdate.split("-")[2]); int curtab=position; string whereclause=""; string sort=""; if(curtab==0){ whereclause=null; sort=database.name; } else if(curtab==1){ whereclause=database.month+" = '"+month+"' , "+database.day+" ="+today; sort=database.name; } else if(curtab==2){ cal.add(calendar.day_of_month, 1); int monthn=cal.get(calendar.month)+1; month mnn=new month(); string monthtomorrow=mnn.getmonth(monthn); int tomorrow=cal.get(calendar.day_of_month); whereclause=database.month+" = '"+monthtomorrow+"' , "+database.day+" ="+tomorrow; sort=database.day; } else if(curtab==3){ whereclause=database.month+" = '"+month+"'"; sort=database.day; } if(drawermain.pos==1){ if(curtab==0){ whereclause=database.type+"='birthday'"; } else{ whereclause=whereclause+" , "+database.type+"='birthday'"; } } else if(drawermain.pos==2){ if(curtab==0){ whereclause=database.type+"='anniversary'"; } else{ whereclause=whereclause+" , "+database.type+"='anniversary'"; } } c = database.query(database.table_event, null, whereclause, null, null, null, sort); string[] fromdb={database.name,database.month,database.day}; int[] toview={r.id.tvname_lv,r.id.tv_month_lv,r.id.tv_day_lv}; customcursoradapter adapter=new customcursoradapter(getactivity(), c, 0, r.layout.events_list_item,fromdb,toview); lv.setadapter(adapter); database.close(); }
you should consider using asynctaskloader instead. asyncloaders handle orientation changes better asynctasks.
you can find tutorial here: http://www.androiddesignpatterns.com/2012/08/implementing-loaders.html
code (copied directly tutorial)
public class sampleloader extends asynctaskloader<list<sampleitem>> { // hold reference loader’s data here. private list<sampleitem> mdata; public sampleloader(context ctx) { // loaders may used across multiple activitys (assuming aren't // bound loadermanager), never hold reference context // directly. doing cause leak entire activity's context. // superclass constructor store reference application // context instead, , can retrieved call getcontext(). super(ctx); } /****************************************************/ /** (1) task performs asynchronous load **/ /****************************************************/ @override public list<sampleitem> loadinbackground() { // method called on background thread , should generate // new set of data delivered client. list<sampleitem> data = new arraylist<sampleitem>(); // todo: perform query here , add results 'data'. return data; } /********************************************************/ /** (2) deliver results registered listener **/ /********************************************************/ @override public void deliverresult(list<sampleitem> data) { if (isreset()) { // loader has been reset; ignore result , invalidate data. releaseresources(data); return; } // hold reference old data doesn't garbage collected. // must protect until new data has been delivered. list<sampleitem> olddata = mdata; mdata = data; if (isstarted()) { // if loader in started state, deliver results // client. superclass method us. super.deliverresult(data); } // invalidate old data don't need more. if (olddata != null && olddata != data) { releaseresources(olddata); } } /*********************************************************/ /** (3) implement loader’s state-dependent behavior **/ /*********************************************************/ @override protected void onstartloading() { if (mdata != null) { // deliver loaded data immediately. deliverresult(mdata); } // begin monitoring underlying data source. if (mobserver == null) { mobserver = new sampleobserver(); // todo: register observer } if (takecontentchanged() || mdata == null) { // when observer detects change, should call oncontentchanged() // on loader, cause next call takecontentchanged() // return true. if ever case (or if current data // null), force new load. forceload(); } } @override protected void onstoploading() { // loader in stopped state, should attempt cancel // current load (if there one). cancelload(); // note leave observer is. loaders in stopped state // should still monitor data source changes loader // know force new load if ever started again. } @override protected void onreset() { // ensure loader has been stopped. onstoploading(); // @ point can release resources associated 'mdata'. if (mdata != null) { releaseresources(mdata); mdata = null; } // loader being reset, should stop monitoring changes. if (mobserver != null) { // todo: unregister observer mobserver = null; } } @override public void oncanceled(list<sampleitem> data) { // attempt cancel current asynchronous load. super.oncanceled(data); // load has been canceled, should release resources // associated 'data'. releaseresources(data); } private void releaseresources(list<sampleitem> data) { // simple list, there nothing do. cursor, // close in method. resources associated loader // should released here. } /*********************************************************************/ /** (4) observer receives notifications when data changes **/ /*********************************************************************/ // note: implementing observer outside scope of post (this example // uses made-up "sampleobserver" illustrate when/where observer should // initialized). // observer long able detect content changes // , report them loader call oncontentchanged(). example, // if writing loader loads list of installed applications // on device, observer broadcastreceiver listens // action_package_added intent, , calls oncontentchanged() on particular // loader whenever receiver detects new application has been installed. // please don’t hesitate leave comment if still find confusing! :) private sampleobserver mobserver; }
put fetchdata() method in loadinbackground(). close cursor in releaseresources() method. in oncreate() call
getloadermanager().initloader(0, null, this);
Comments
Post a Comment