DCoder
DCoder

Reputation: 3488

notifyDataSetChanged() not working for custom adapter

I have already went through many similar question but still I am not getting the answer.

I am using custom adapter having arraylist for listview when there is some change on seek bar arraylist is modified and I want to show this changes on listview, I am doig this in following two ways

lv = (ListView) findViewById(R.id.lv_showcontactlist);
    customAdapter = new ContactListViewAdapter(this);
    customAdapter.setList(contactList);
    lv.setAdapter(customAdapter);
    contactList_temp = new ArrayList<ContactBean>(contactList);

attempt 1)

public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) {
    for (ContactBean object : contactList_temp) {
        int sal = Integer.parseInt(object.getSalary());
        if (sal > progress) {
            contactList.remove(object);
        }

    }

    customAdapter.notifyDataSetChanged();
    contactList.clear();
    contactList.addAll(contactList_temp);
} 

attempt 2)

public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) {
    contactList.clear();

    for (ContactBean object : contactList_temp) {
        int sal = Integer.parseInt(object.getSalary());
        if (sal < progress) {
            contactList.add(object);
                        }
    }
    customAdapter.notifyDataSetChanged();
    contactList.addAll(contactList_temp);
}

setList method in my adapter class:

public void setList(ArrayList<ContactBean> newList) {
    this.m_contactlist = newList;
    }

My problem is both methods are logically doing same task but my 1 method is not listview remains same but second method is working properly listview is reflecting changes as expected. So i want to know what is the reason behind this.

Upvotes: 0

Views: 7504

Answers (2)

thepoosh
thepoosh

Reputation: 12587

one way to implement changing information mid run in a custom adapter is to add a method for that and in that method (after ensuring you're on the UI thread), notifyDatasetChage.

public void setList(List<T> data) {
  this.mData = data;
  Handler handler = new Handler(Looper.getMainLooper());
  handler.post(new Runnable() {
     @Override
     public void run() {
         notifyDatasetChanged();
     }
  });
}

Upvotes: 2

Pankaj Kumar
Pankaj Kumar

Reputation: 83048

You are calling customAdapter.notifyDataSetChanged() before changing the data of adapter. You need to call this method after changing the data of adapter.

See below for edit

In attempt 1:-

Code should be

// customAdapter.notifyDataSetChanged(); // NOT HERE
contactList.clear();
contactList.addAll(contactList_temp);
customAdapter.notifyDataSetChanged(); // MUST BE HERE

In attempt 2

Code should be

// customAdapter.notifyDataSetChanged(); // NOT HERE
contactList.addAll(contactList_temp);
customAdapter.notifyDataSetChanged(); // MUST BE HERE

Upvotes: 3

Related Questions