【问题标题】:Listview refresh without notifyDataSetChange没有 notifyDataSetChanged 的​​ Listview 刷新
【发布时间】:2020-03-12 15:44:38
【问题描述】:

notifyDataSetChanged 有问题。我有一个从 sqlite 数据库中检索数据的列表。问题是我知道每次使用 list 类的 add 方法时都必须调用 notifyDataSetChanged 。我不明白为什么我的列表在没有 notifyDataSetChange() 的情况下调用 addAll() 后显示数据。我也尝试过使用 add() 但结果是一样的。我需要答案,因为我想很好地理解 notifyDataSetChange() 是如何工作的。 片段代码:

 public static List<Wherehouse> mListFoodsIn;  
wherehouseAdapter wherehouseAdapter;



@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_wherehouse, container, false);

    wherehouseList = v.findViewById(R.id.wherehouseList); 
    final DBManager db = new DBManager(getActivity());

    mListFoodsIn = new ArrayList<>();
    wherehouseAdapter = new wherehouseAdapter(getActivity(), mListFoodsIn);
    new GetWherehoouseAsync(getActivity(),mListFoodsIn, wherehouseList, wherehouseAdapter).execute();  
    wherehouseList.setAdapter(wherehouseAdapter);

异步类:

public static class GetWherehoouseAsync extends AsyncTask<Void, Void, Void>{

    Context mContext;
    wherehouseAdapter mAdapter;
    DBManager db;
    List<Wherehouse> mList;

    ListView listViewWherehouse;

    public GetWherehoouseAsync(Context mContext, List<Wherehouse> list, ListView lv, wherehouseAdapter adapter) {
        this.mContext = mContext;
        db = new DBManager(mContext);
        this.mList = list;
        this.listViewWherehouse = lv;
        mAdapter = adapter;
    }


    @Override
    protected void onPreExecute() {
        super.onPreExecute();


    }

    @Override
    protected Void doInBackground(Void... voids) {

      //  List<Wherehouse> tmpList = db.GetWherehouse();


        mList.addAll(db.GetWherehouse());


        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

      //  mAdapter.notifyDataSetChanged();
    }

这可能是自然场景,因为我在 onCreateView 中调用了 async()?

【问题讨论】:

  • public static List&lt;Wherehouse&gt; mListFoodsIn; 与此相关的一切都必然是错误的和/或导致以后崩溃。包括多线程问题。
  • 我可以再解释一下吗?我是初学者

标签: java android listview arraylist notifydatasetchanged


【解决方案1】:

您在更新列表mListFoodsIn 后将适配器应用到您的列表视图,因为您的数据来自数据库而不是通过网络调用,结果返回速度相对较快。因此,正确的列表在创建时正确应用于列表视图。如果数据在片段的生命周期内发生变化,那么您需要通知适配器。

notifyDataSetChanged()

通知附加的观察者基础数据已被 改变了

【讨论】:

  • 但我也尝试在更新列表之前将适配器应用于我的列表视图,但行为是相同的。正常吗?
  • 调用setAdapter 将更新列表视图,但是如果您重复调用它,它将创建新的适配器消耗内存,直到以前的适配器被垃圾回收。当您设置适配器时,它会调用requestLayout(),在这种情况下会重置视图和数据。这是视图生命周期的一个很好的例子stackoverflow.com/a/25846243/5644761
  • 可能是定时,列表在设置适配器完成之前从异步更新。
  • 非常感谢 JakeB,现在一切都清楚了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 2013-01-08
  • 1970-01-01
  • 1970-01-01
  • 2019-04-12
相关资源
最近更新 更多