Search code examples
androidmultithreadinglistviewandroid-cursor

How to schedule heavy work for later display for Listviews?


I have a listview with 200 items. I use a custom view for each row. There is a code that takes some time to calculate, and because of this the list hangs out on scrolling and loads in slow (2-3sec).

I have subclassed SimpleCursorAdapter, and using Filterable and SectionIndexer.

I have in mind to show initially the name of the record, and put in a thread the calculation, and will show up later when it's done.

How do I push back some work, and later update the listview to include the calculated data? This should show up on fly without user interaction.


Solution

  • Since android the Android UI is singlethreaded it will be blocked whenever you perform a long operation.

    You could do regular java threading and have a Handler() in the main UI class that you can feed back information into. But..

    The simplest way would be to create an AsyncTask(). They are java threads with a slight change. They can perform a UI operation before/after the main calculation. So for example:

     private class AndroidThread extends AsyncTask {
          protected Object doInBackground(Object... params) {
               return result;
          }
    
          protected void onPostExecute(Object result) {
               // do things here with the result of the doInBackground function
               // Like: "UiElement"."performTask(result)"
          }
     }
    

    For more information on AsyncTask see this