2012-06-04 104 views
0

我想使用AsyncTask填充我的ListView。在評論使用AsyncTask填充ListView(doInBackground()返回光標)

private class DownloadDataTask extends AsyncTask<String, Void, Cursor> { 
    private final ProgressDialog dialog = new ProgressDialog(ctx); 


    @Override 
    protected void onPreExecute() { 
     this.dialog.setMessage(ctx.getString(R.string.AcquiringData)); 
     this.dialog.show(); 
    } 


    @Override 
    protected Cursor doInBackground(final String... args) {   

     DbAdapter dbAdapter = new DbAdapter(ctx); 
     dbAdapter.open(); 
     // normally when I call this method from main class it reurns cursor full of values 
     Cursor cursor = dbAdapter.fetchAllItemsInExpenses(); 

     return cursor; 
    } 


    protected void onPostExecute(final Cursor cursor) { 
     if (this.dialog.isShowing()) { 
      this.dialog.dismiss(); 
      //cursor is empty 

    } 

ctx包含的問題是,設置在主類的OnCreate()

按照要求粘貼fetchAllItemsInExpenses()方法上下文:

public Cursor fetchAllItemsInExpenses() { 
    String query = "SELECT ... " //(some terribly boring and long query string, but trust me, it works perfectly fine) 
    return SQLDb.rawQuery(query, null); 
} 
+0

檢查使用'如果(空!=光標){cursor.getCount()}',並檢查你的方法'fetchAllItemsInExpenses'是正確的還是不 –

+0

燦你顯示'fetAllItemsInExpenses()'源?另外,你有沒有考慮過使用['CursorLoader'](http://developer.android.com/reference/android/content/CursorLoader.html)? –

+0

當我從Activity類調用它時,fetchAllItemsInExpenses()正常工作。不過花了一些時間,所以我決定把列表填入AsyncTask。但是提供了代碼。 @JasonRobinson糾正我如果我錯了,Cursor加載器是一種專爲加載遊標而設計的任務嗎? –

回答

0

AsyncTask試試這個...

private class DownloadDataTask extends AsyncTask<String, Void, Cursor> { 
    private final ProgressDialog dialog = new ProgressDialog(ctx); 
    Context ctx = null; //Add this and the constructor below 

    public DownloadDataTask(Context context) { 
     ctx = context; 
    } 

    ... 

} 

然後在你身邊[R Activity創建並執行AsyncTask如下...

DownloadDataTask ddt = new DownloadDataTask(this); 
ddt.execute(theArgs); 
+0

10這是怎麼改變的?我在活動的OnCreate上初始化的ctx變量保持相同的東西 –

+0

你說你的'ctx'是'Activity'的一部分 - 你不應該試圖從'doInBackground'中訪問'Activity'(UI線程)中的任何東西線。將它傳遞給構造函數允許'doInBackground'訪問'AsyncTask'' ctx'。 – Squonk

+0

是有道理的...我儘快嘗試血腥的X10靴子 –