Search code examples
androidandroid-listviewnotifydatasetchanged

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

}

Solution

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