2012-06-04 106 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靴子 –