Android Dev: Pre-loading with AsyncTask

{lang: 'en-GB'}


I have an app that downloads an RSS feed, parses the information, then displays it in a ListView. This all happens in less than a second or so when using WiFi, but when on GPRS can take 5 seconds or so.

The problem I had was that all these tasks occurred onCreate of the main activity, meaning that you would press the app icon and nothing would happen… then after a few seconds the app would just appear.

I used the AsyncTask class to correctly pre-load the data, whilst displaying a ProgressDialog.

 private class DoInBackground extends AsyncTask<Void, Void, Void>
                                 implements DialogInterface.OnCancelListener
    {
        private ProgressDialog dialog;
               
        protected void onPreExecute() 
        {
        	dialog = ProgressDialog.show(main.this, "", "Loading. Please wait...", true);
        }
       
        protected Void doInBackground(Void... unused) 
        { 
        	do_update(); 
        	return null; 
        }
        
        protected void onPostExecute(Void unused) 
        { 
        	dialog.dismiss(); 
        	populate_listview();
        }
        
        public void onCancel(DialogInterface dialog) 
        { 
        	cancel(true); 
        	dialog.dismiss(); 
        }
    }

The onPreExecute method is called before the task starts. In this example it initializes and displays a ProgressDialog.

The doInBackground method is where your task actually takes place. In this example it calls a do_update method.

The onPostExecute method is called when your task finishes. In this example it kills the ProgressDialog, and also calls a method to populate a listview.

The onCancel method is there, and I presume it handles if the user backs out of the app or presses the back button???

And… that’s it. To start the example above just call the following from your main code:

new DoInBackground().execute();


Google+ Comments

Comments are closed.