2011-05-08 32 views
2

所以,我有我的onCreate方法在這裏填充用戶安裝的應用程序ListView。這需要很長時間才能完成,我試圖找出在哪裏創建新線程來完成一些繁重的工作,以便在列表加載時顯示ProgressDialog。這裏是我的代碼有:Android:適當的線程化ListActivity

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, namesArray); 
    setListAdapter(adapter);   
    return adapter; 
} 

我有一個線程處理列表和這樣的排序,但ProgressDialog我根本不會露面,直到列表完全填充,哪種擊敗目的在於擁有ProgressDialog

我的問題,簡而言之,我應該把這個線程用於顯示ProgressDialog WHILE列表正在完成填充?

以下內容得到

@Femi上AsyncTask提供了一個極好的教程和我的應用程序列表中的加載過程中有我ProgressDialog捻轉。謝謝!

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

+0

你看過使用asynctask嗎?在執行前顯示進度,然後關閉onPostExecute – jkhouw1 2011-05-08 02:22:27

+0

查看本教程以查看工作實施。 http://p-xr.com/android-tutorial-how-to-make-a-progress-dialog/ – 2011-05-08 05:15:24

回答

0

推薦的方法是使用的AsyncTask:

  1. 顯示進度對話框。
  2. 啓動異步任務並在doInBackground方法中構建names ArrayList。
  3. 將數組列表傳遞給postExecute中的createAdapter方法,然後關閉進度對話框。
+0

好吧,我把一些日誌命令在那裏,我發現它是Collections.sort(appList,新的ResolveInfo.DisplayNameComparator(pm));調用這麼久,所以我想我需要在doInBackground方法中執行此操作。我在ASyncTask中遇到了泛型問題。處理這個問題的正確方法是什麼? – SemperGumbee 2011-05-08 05:20:48

+0

不確定你在AsyncTask中的泛型是什麼意思,但是我AsyncTask的例子是http://labs.makemachine.net/2010/05/android-asynctask-example/:它帶有一個完全可行的例子,你可以修改以適應。看一看,看看這是否無助於解決您的問題。如果它沒有發佈一些代碼,而這些代碼不工作,我們可以看到你被卡住了。 – Femi 2011-05-08 05:47:27

+0

你在鏈接中的例子正是我所需要的。多謝,夥計! – SemperGumbee 2011-05-08 06:39:04