0

我需要在啓動活動時從一個數據庫檢索一些大量數據。爲了防止凍結窗口的用戶,我決定在數據處理過程中運行ProgressDialog。嘗試在AsyncTask中設置適配器時出現問題

從OnCreate中我打電話給我在initdb類:

新initdb的()執行();

然後要做到這一點,我有我的活動的類中一類:

public class initDb extends AsyncTask<Void, Void, Void> { 

    ProgressDialog mDialog = new ProgressDialog(ClientsReg.this); 

    @Override 
    protected void onPreExecute() { 
     mDialog.setMessage("Please wait..."); 
     mDialog.show(); 
    } 


    @Override 
    protected Void doInBackground(Void... voids) { 

     opendb(); 
     listCities(); 
    return null; 


    } 

@Override 
    protected void onPostExecute(Void unused) { 
     // Pass the result data back to the main activity 
     mDialog.dismiss(); 
    } 

}

在設置適配器的真正問題發生:

private void listCities() { 


     mRedrawHandler.sleep(100000); 


     c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC"); 

     //add some list items 
     ArrayList<String> finalList = new ArrayList<String>(); 

     c.moveToFirst(); 


     while (!c.isAfterLast()){ 

      finalList.add(c.getString(0) + ")"+ c.getString(5));    
      c.moveToNext(); 
     } 


     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
       R.layout.row, R.id.itemShow, finalList); 
     sp.setAdapter(adapter); 


    } 

它總是發生在在sp.setAdapter(適配器)上崩潰;

任何想法?

謝謝!

+0

是否可以從logcat的碰撞後的日誌? – Augusto

回答

0

嘗試服用finalList作爲initdb的類的屬性這樣你可以填充它在doInBackground方法,然後我們就在onPostExecute,就像這樣:

public class initDb extends AsyncTask<Void, Void, Void> { 

    ProgressDialog mDialog = new ProgressDialog(ClientsReg.this); 
    ArrayList<String> finalList; 

    @Override 
    protected void onPreExecute() { 
     mDialog.setMessage("Please wait..."); 
     mDialog.show(); 
    } 


    @Override 
    protected Void doInBackground(Void... voids) { 

     opendb(); 
     listCities(); 
    return null; 


    } 

@Override 
    protected void onPostExecute(Void unused) { 
     // Pass the result data back to the main activity 

     ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, 
       R.layout.row, R.id.itemShow, finalList); 
     sp.setAdapter(adapter); 

     mDialog.dismiss(); 
    } 

private void listCities() { 


     mRedrawHandler.sleep(100000); 


     c = db.executeSQL("SELECT * FROM RegDB WHERE Reg_Type = 1 AND cad_uzkow = 0 ORDER BY _id DESC"); 

     //add some list items 
     finalList = new ArrayList<String>(); 

     c.moveToFirst(); 


     while (!c.isAfterLast()){ 

      finalList.add(c.getString(0) + ")"+ c.getString(5));    
      c.moveToNext(); 
     } 
} 
+0

Necronet,你有!謝謝! – RickON

0

你應該叫:

sp.setAdapter(adapter); 

在主UI線程。例如在onPostExecute()函數中。請務必記住,只能從主線程訪問視圖(如ListView)。

+0

inazaruk,作品魅力!謝謝! – RickON

0

您不能從創建UI的線程以外的其他線程訪問UI。所以在AsyncTask中,你不能使用doInBackground()來達到這個目的。

+0

忘了它....謝謝! – RickON

相關問題