Jesse Yuan
Jesse Yuan

Reputation: 3

notifyDataSetChanged() does not refresh my ListView

I am trying to delete items from a ListView. However, after calling notifyDataSetChanged(), my ListView does not refresh, and instead refreshes AFTER I click on the EditText. I have also tried using the adapter.remove method, but that produced the same error. Why is this happening?

Code:

public class AddWordActivity extends Activity {
private static ArrayList<String> words = new ArrayList<String>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_add_word);

    final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,       
    android.R.layout.simple_list_item_1, android.R.id.text1, words);
    final ListView listView = (ListView) findViewById(R.id.wordsListView);
    listView.setAdapter(adapter); 

    listView.setOnItemClickListener(new OnItemClickListener(){

        public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
            words.remove(position);
            adapter.notifyDataSetChanged();
        }
    });

}

Upvotes: 0

Views: 1860

Answers (4)

Rohan Pawar
Rohan Pawar

Reputation: 2003

I have implemented in my code like this and it works for me

@Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // TODO Auto-generated method stub
                MyAdatper adapter=(MyAdatper)parent.getAdapter();
                adapter.remove(myStringArray.get(position));
                adapter.notifyDataSetChanged();

        }

Upvotes: 1

Ra41P
Ra41P

Reputation: 774

It seems that the "words" array list will be local to your item listener. So instead of trying to remove the value from words, try removing it from the adapter itself. Cheers :)

Upvotes: 0

DjP
DjP

Reputation: 4577

Have you added items in ArrayList? Kindly add the idem otherwise your code is perfect.

Upvotes: 0

Paras Valera
Paras Valera

Reputation: 492

you should use adapter.remove(position) instead of words.remove(position). and if you want to use word.remove(position) then you need to set adapter again to ListView as there is changed data in ArrayList words. otherwise you can use adapter.remove(pos); method.

Upvotes: 0

Related Questions