开发者

Android: Proper threading for ListActivity

So, I have my onCreate method here for populating a ListView with user installed apps. This takes a long time to do and I was trying to figure out where to make a new thread to do some of the heavy work so I can display a ProgressDialog while the list is loading. Here is the code I have:

protected void onCreate(Bundle savedInstanceState) {        
    super.onCreate(savedInstanceState);

    // Find out which prefs to update
    Bundle extras = getIntent().getExtras();
    if(extras !=null){
        buttonPressed = extras.getString("buttonPressed");
        loadNumber = extras.getString("loads");
    } 

    buttonPressedAppName = buttonPressed + "AppName" + loadNumber;
    buttonPressedAppPack = buttonPressed + "AppPack" + loadNumber;
    humanNamePrefs = buttonPressed + "AppText" + loadNumber;

    // Get shared preferences
    settings = getSharedPreferences(PREFS_NAME, 0);

    // Do in another thread to not slow the UI down...eventually
    adapter = createAdapter();
    setListAdapter(adapter);
}

public ListAdapter createAdapter() {
    namesArray = new String[] { "Loading" };
    names = new ArrayList<String>();

    PackageManager pm = this.getPackageManager();
    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    appList = pm.queryIntentActivities(mainIntent, 0);
    Collections.sort(appList, new ResolveInfo.DisplayNameComparator(pm));

    // Now, appList contains all of the ResolveInfo stuff

    for (int i = 0; i < appList.size(); i++) {          
        names.add(appList.get(i).loadLabel(pm).toString());
    }

    namesArray = maker(names);

    ListAdapter adapter = new ArrayAdapter<String>(this, 
            android.R.layout.simple_list_item_1, na开发者_如何学编程mesArray);
    setListAdapter(adapter);        
    return adapter;
}

I had a thread handling the sorting of the list and such, but the ProgressDialog I had wouldn't even show up until the list was completely populated, which kind of defeats the purpose of having a ProgressDialog.

My question in a nutshell is where should I put this thread to use to show the ProgressDialog WHILE the list is finishing populating?

ANSWERED BELOW

@Femi provided an excellent tutorial on AsyncTask and I have my ProgressDialog twirling during loading of the list of apps. Thanks!

Link: http://labs.makemachine.net/2010/05/android-asynctask-example/


The recommended way is to use an AsyncTask:

  1. Show the progress dialog.
  2. Start the async task and build the names ArrayList in the doInBackground method.
  3. Pass the array list to the createAdapter method in the postExecute, and then close the progress dialog.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜