在asynctask中未使用适配器更新listview

pxyaymoc  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(490)

我是android和sqlite的初学者,在我的应用程序中,我从sqlite数据库获取数据,并使用asynctask将其添加到listview。但是在onpostexecute方法中listview没有得到更新。
主要活动代码-

private class Updateentries extends AsyncTask<String, Void, Void>{

    @Override
    protected Void doInBackground(String... strings) {
        cursor = db.query(SQLiteHelper.Table_name, new String[]{"name"}, "name like ?", new String[]{"%"+strings[0]+"%"}, null, null, null );
        cursorarray = new ArrayList<>();
        if(!cursor.moveToFirst()){
            Toast.makeText(OtherActivity.this, "NO DATA FOUND", Toast.LENGTH_SHORT).show();
        }else{
            do {
                String entry = cursor.getString(cursor.getColumnIndex(SQLiteHelper.name_column));
                cursorarray.add(entry);
            }while(cursor.moveToNext());
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        displaylistadapt = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1,cursorarray);
        displaylist.setAdapter(displaylistadapt);
        super.onPostExecute(aVoid);
    }
}

public boolean onCreateOptionsMenu(Menu menu){
    getMenuInflater().inflate(R.menu.searchactionbar, menu);
    searchtoggle = (SearchView) menu.findItem(R.id.search_toggle).getActionView();

    searchtoggle.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            new Updateentries().execute(query);
            return false;
        }
        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }
    });

    return super.onCreateOptionsMenu(menu);
}

我的应用程序使用搜索视图从数据库中获取数据,然后在listview中显示。

tp5buhyn

tp5buhyn1#

最好先创建视图和适配器,然后再获取数据更新适配器和调用适配器。 notifyDataSetChanged() 也代替了 getApplicationContext() 使用 activityContext ```
ArrayList cursorarray = new ArrayList();

class MainActivity{

void oncreate(){

...
displaylistadapt = new ArrayAdapter(this, android.R.layout.simple_list_item_1,cursorarray);
displaylist.setAdapter(displaylistadapt);

....

private class Updateentries extends AsyncTask<String, Void, ArrayList>{

@Override
protected ArrayList doInBackground(String... strings) {
cursor = db.query(SQLiteHelper.Table_name, new String[]{"name"}, "name like ?", new String[]{"%"+strings[0]+"%"}, null, null, null );
ArrayList list = new ArrayList<>();
if(!cursor.moveToFirst()){
Toast.makeText(OtherActivity.this, "NO DATA FOUND", Toast.LENGTH_SHORT).show();
}else{
do {
String entry = cursor.getString(cursor.getColumnIndex(SQLiteHelper.name_column));
list.add(entry);
}while(cursor.moveToNext());
}
return list;
}

@Override
protected void onPostExecute(ArrayList list) {
cursorarray.clear();
cursorarray.addAll(list);
displaylistadapt.notifyDataSetChanged();
}
}

相关问题