Search code examples
androiddatabaselistviewandroid-arrayadapter

notifyDatasetChanged() id not working


I have to fetch the data from the database and populate it into the ListView. But everytime I am running it, it adds the data into the previous data...

for example.. 1st run:- A B C

2nd run:- A B C A B C

and so on..

Here is my code I am using where I am using NotifyDatasetChanged()

List<Tag> allTags = db.getAllTags();
    for (Tag tag : allTags) {


        lv1=(ListView)findViewById(R.id.lv1);


        arraylist=new ArrayAdapter<Tag>(this,
                android.R.layout.simple_list_item_1, allTags);
        lv1.setAdapter(arraylist);



        Log.d("Tag Name", tag.getTagName());


        lv1.setOnItemClickListener(new OnItemClickListener() {


            @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub

                 String item = ((TextView)view).getText().toString();

                    Toast.makeText(getBaseContext(), item, Toast.LENGTH_SHORT).show();


                    arraylist.notifyDataSetChanged();



            }
        });
    }

I have searched many links, applied their answers in my code, But nothing is changed.


Solution

  • You are creating your adapter using allTags, so whenever you are changing the value of allTags by adding or removing more elements and then immediately calling notifyDataSetChange() it will reflect the changes in the adapter. What I can see here in your code is that inside OnItemClickListener you are not modifying your allTags hence calling notifyDataSetChanged is not effective.