我在主窗口上有一个列表视图
lvItems = (ListView) findViewById(R.id.lvItems);
new GetAsync(this,lvItems).execute();
和我的异步任务,我想从我的数据库中检索数据,并将其推送到我的列表视图。当我执行我的代码时,我的lsitview是空的。有人知道解决方案吗?
public class GetAsync extends AsyncTask<Void,ArrayList<Task>,List<Task>> {
private Context context;
private ListView listView;
ArrayAdapter<Task> tasks;
public GetAsync(Context context, ListView listview) {
this.context = context;
this.listView = listview;
}
@Override
protected List<Task> doInBackground(Void... voids) {
TaskDbHelper db = new TaskDbHelper(context);
return db.getTasks();
}
@Override
protected void onPreExecute() {
tasks = (ArrayAdapter<Task>) listView.getAdapter();
}
@Override
protected void onPostExecute(List<Task> tasks) {
tasks.addAll(tasks);
}
}
public List<Task> getTasks()
{
SQLiteDatabase db = this.getWritableDatabase();
String[] columns = new String[] {"id","task","complete"};
String prderBy = "task ASC";
// Cursor cursor = db.query(TaskContract.TaskEntry.TABLE_NAME,columns,null,null,null,null,prderBy,null);
Cursor cursor = db.rawQuery("select * from task where complete = ?",new String[]{"0"});
List<Task> tasks = new ArrayList<>();
while (cursor.moveToNext())
{
Task t = new Task(cursor.getInt(0),
cursor.getString(1)
,cursor.getInt(2));
tasks.add(t);
}
cursor.close();
return tasks;
}
最佳答案
完成ListView
后,更新您的AsyncTask
适配器
@Override
protected void onPostExecute(List<Task> tasks) {
tasks.addAll(tasks);
//Update listview adapter . Which already has the updated items
//assuming your listview adapter variable is listViewAdapter
listViewAdapter.notifyDataSetChanged();
}
选中此reference link