I have a listview on my mainwindow
lvItems = (ListView) findViewById(R.id.lvItems);
new GetAsync(this,lvItems).execute();
and with my asyntask i want retrieve the data from my db and push it in my listview. When i execute my code my lsitview is empty. Someone knows the solution for this ?
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;
}
Update your ListView
's adapter after completing the 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();
}
Check this reference link
@Override
protected void onPostExecute(List<Task> tasks) {
tasks.addAll(tasks);
ArrayAdapter<Task> adapter = new ArrayAdapter<Task>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, tasks);
listView.setAdapter(adapter);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.