不进行notifyDataSetChange的Listview刷新

问题描述 投票:0回答:1

大家好,我对notifyDataSetChanged有点问题。我有一个从sqlite数据库检索数据的列表。问题是,我知道每次使用列表类的add方法时都必须调用notifyDataSetChanged。太好了。我无法理解为什么在addAll调用后没有notifyDataSetChange的情况下我的列表为何显示数据。我也尝试使用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中调用了异步方法?

java android listview arraylist notifydatasetchanged
1个回答
0
投票

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

notifyDataSetChanged()

通知随附的观察者基础数据已经被已更改

© www.soinside.com 2019 - 2024. All rights reserved.