Listview refresh without notifyDataSetChange

|▌冷眼眸甩不掉的悲伤 提交于 2020-03-05 04:05:14

问题


There is a problem with notifyDataSetChanged. I have a list which retrieves data from sqlite database. The problem is that I know that I have to call notifyDataSetChanged everytime I use add method of list class. I can't understand why my list shows data after addAll() calling without the notifyDataSetChange(). I also tried using add() but result is the same. I need answer because I want to understand very well how notifyDataSetChange() works. Fragment code:

 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);

Async class:

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();
    }

It maybe natural scenario because I call async() in onCreateView?


回答1:


You're applying the adapter to your listview after updating the list mListFoodsIn, since your data is coming from a Database not via a network call the result returns relatively fast. So the correct list is applied to the listview on creation correctly. If the data were to change during the lifecycle of your fragment, then you would need to notify the adapter.

notifyDataSetChanged()

Notifies the attached observers that the underlying data has been changed



来源:https://stackoverflow.com/questions/58894798/listview-refresh-without-notifydatasetchange

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!