2012-02-18 106 views
0

当异步任务完成时,如何更新listivew。以下是示例代码,但listview未更新。asynctask完成后更新列表视图

class CallXML extends AsyncTask<Void, Void, Void> { 
    int gcid; 
    int scid; 

    public CallXML(int gid, int sid) { 
     // TODO Auto-generated constructor stub 
     gcid = gid; 
     scid = sid; 
    } 

    protected void onPreExecute() { 

    } 

    protected Void doInBackground(Void... arg0) { 
     // here goes the xml parsing.... 
     } 

     return null;    
    } 

    protected void onPostExecute(String result) { 
     Log.e("TAG", "In postExecute"); 


     Cursor cur3 = database2.query("Quote", qfield, null, null, null, null, null); 
     cur3.moveToFirst(); 

     do { 
     quotesarray.add(cur3.getString(2)); 

     } while (cur3.moveToNext()); 

     if(cur3 != null){ 
      cur3.close(); 
     } 

     QList.post(new Runnable() { 
      public void run() { 
       mAdapter = new CustomAdapter(); 
       mAdapter.notifyDataSetChanged(); 
       QList.setAdapter(mAdapter);  
      } 
     }); 


     if (helper2 != null) { 
      helper2.close(); 
     } 

     if (database2 != null) { 
      database2.close(); 
     } 

    } 
} 

编辑:

NOTE:事实上没有执行onPostExecute why..This是我叫asynctask new CallXML(gcid, scid).execute();

回答

2

此外,onPostExecute是在主线程上,所以不应该在那里做数据库查询。相反,获取doInBackground中的数据并从那里返回最终的集合。

onPostExecute可用于UI更新并使用结果集合更新适配器。

编辑:发布可运行

QList.post(new Runnable() { 
       public void run() { 
        //mAdapter.notifyDataSetChanged(); 
        QList.setAdapter(mAdapter);  
       } 
      }); 

是不需要的,因为你是在主循环。

2

您没有提供字符串的项目到适配器在你的代码的方式。在将适配器设置为列表时,不需要调用notifyDataSetChanged,因为当您设置适配器时,它会自动将数据加载到列表中。也许你我尝试这样做:

protected void onPostExecute(String result) { 
     Log.e("TAG", "In postExecute"); 

     Cursor cur3 = database2.query("Quote", qfield, null, null, null, null, null); 
     cur3.moveToFirst(); 

     mAdapter = new CustomAdapter(); 

     do { 
     mAdapter.add(cur3.getString(2)); 

     } while (cur3.moveToNext()); 

     if(cur3 != null){ 
      cur3.close(); 
     } 

     QList.post(new Runnable() { 
      public void run() { 
       //mAdapter.notifyDataSetChanged(); 
       QList.setAdapter(mAdapter);  
      } 
     }); 


     if (helper2 != null) { 
      helper2.close(); 
     } 

     if (database2 != null) { 
      database2.close(); 
     } 

    } 
0

你有什么错误吗?如果是的话请张贴。如果没有检查你从数据库中获得的数据的大小,如果你想刷新listview只是调用listview.invalidateViews()它将刷新列表视图并在列表视图中设置新的数据。