如何刷新一个Android列表视图后添加/删除动态数据?


当前回答

如果您正在使用SimpleCursorAdapter,请尝试在Cursor对象上调用requery()。

其他回答

如果你还不满意ListView刷新,你可以看看这个片段,这是从DB加载ListView,实际上你要做的就是简单地重新加载ListView,在你执行任何CRUD操作后 这不是一个最好的编码方式,但它会刷新ListView如你所愿。

它为我工作....如果你有更好的解决方案,请分享…

.......
......
do your CRUD Operations..
......
.....
DBAdapter.open();
DBAdapter.insert_into_SingleList();
// Bring that DB_results and add it to list as its contents....
                                            ls2.setAdapter(new ArrayAdapter(DynTABSample.this,
    android.R.layout.simple_list_item_1,                        DBAdapter.DB_ListView));
                                            DBAdapter.close();

如果我在这里谈论我的场景,上面的答案都不会起作用,因为我有一个显示db值列表的活动,同时还有一个删除按钮,当按下删除按钮时,我想从列表中删除该项。

最酷的是,我没有使用回收器视图,而是使用了一个简单的列表视图,该列表视图在适配器类中初始化。因此,调用notifyDataSetChanged()不会在适配器类内部执行任何操作,甚至不会在初始化了适配器对象的活动类中执行任何操作,因为delete方法位于适配器类中。

因此,解决方案是在适配器类getView方法中从适配器中删除对象(仅删除特定对象,但如果您想删除所有对象,则调用clear())。

为了让你们了解我的代码是什么样的,

public class WordAdapter extends ArrayAdapter<Word> {
  Context context;

  public WordAdapter(Activity context, ArrayList<Word> words) {}
    //.......

    @NonNull
    @Override
    public View getView(final int position, View convertView, ViewGroup group) {
      //.......
     ImageButton deleteBt = listItemView.findViewById(R.id.word_delete_bt);
     deleteBt.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
             if (vocabDb.deleteWord(currentWord.id)) {
                //.....
             } else{
                //.....
             }
             remove(getItem(position)); // <---- here is the trick ---<
             //clear() // if you want to clear everything
         }
    });
 //....

注意:这里remove()和getItem()方法继承自Adapter类。

Remove() -删除所单击的特定项 getItem(position) -用于获取项目(在这里,这是我的Word对象 我已经添加到列表)从点击的位置。

这就是我如何在活动类中将适配器设置为listview,

    ArrayList<Word> wordList = new ArrayList();
    WordAdapter adapter = new WordAdapter(this, wordList);

    ListView list_view = (ListView) findViewById(R.id.activity_view_words);
    list_view.setAdapter(adapter);

当使用SimpleCursorAdapter时,可以在适配器上调用changeCursor(newCursor)。

我有一个数组列表,我想把它显示在列表视图中。ArrayList包含mysql中的元素。 我重写了onRefresh方法,在该方法中我使用了tablelayout.removeAllViews();然后重复从数据库中获取数据的过程。 但在此之前,请确保清空你的数组列表或任何数据结构,否则新数据将被追加到旧数据。

我只能通过获得新的适配器数据来获得notifyDataSetChanged,然后为列表视图重置适配器,然后像这样调用:

    expandableAdapter = baseFragmentParent.setupEXLVAdapter();
    baseFragmentParent.setAdapter(expandableAdapter);
    expandableAdapter.notifyDataSetChanged();