119

My ListFragment code

public class ItemFragment extends ListFragment {

    private DatabaseHandler dbHelper;
    private static final String TITLE = "Items";
    private static final String LOG_TAG = "debugger";
    private ItemAdapter adapter;
    private List<Item> items;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.item_fragment_list, container, false);        
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.setHasOptionsMenu(true);
        super.onCreate(savedInstanceState);
        getActivity().setTitle(TITLE);
        dbHelper = new DatabaseHandler(getActivity());
        items = dbHelper.getItems(); 
        adapter = new ItemAdapter(getActivity().getApplicationContext(), items);
        this.setListAdapter(adapter);

    }



    @Override
    public void onResume() {
        super.onResume();
        items.clear();
        items = dbHelper.getItems(); //reload the items from database
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {
        super.onListItemClick(l, v, position, id);
        if(dbHelper != null) { //item is edited
            Item item = (Item) this.getListAdapter().getItem(position);
            Intent intent = new Intent(getActivity(), AddItemActivity.class);
            intent.putExtra(IntentConstants.ITEM, item);
            startActivity(intent);
        }
    }
}

My ListView

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>

But this does not refresh the ListView. Even after restarting app the updated items are not shown. My ItemAdapter extends BaseAdapter

public class ItemAdapter extends BaseAdapter{

    private LayoutInflater inflater;
    private List<Item> items;
    private Context context;

    public ProjectListItemAdapter(Context context, List<Item> items) {
        super();
        inflater = LayoutInflater.from(context);
        this.context = context;
        this.items = items;

    }

    @Override
    public int getCount() {
        return items.size();
    }

    @Override
    public Object getItem(int position) {
        return items.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ItemViewHolder holder = null;
        if(convertView == null) {
            holder = new ItemViewHolder();
            convertView = inflater.inflate(R.layout.list_item, parent,false);
            holder.itemName = (TextView) convertView.findViewById(R.id.topText);
            holder.itemLocation = (TextView) convertView.findViewById(R.id.bottomText);
            convertView.setTag(holder);
        } else {
            holder = (ItemViewHolder) convertView.getTag();
        }
        holder.itemName.setText("Name: " + items.get(position).getName());
        holder.itemLocation.setText("Location: " + items.get(position).getLocation());
        if(position % 2 == 0) {                                                                                 
            convertView.setBackgroundColor(context.getResources().getColor(R.color.evenRowColor));
        } else {    
            convertView.setBackgroundColor(context.getResources().getColor(R.color.oddRowColor));
        }
        return convertView;
    }

    private static class ItemViewHolder {
        TextView itemName;
        TextView itemLocation;
    }
}

Can someone help please?

edwoollard
  • 12,245
  • 6
  • 43
  • 74
Coder
  • 3,090
  • 8
  • 49
  • 85
  • 2
    Have you tested to see if the database operation are working properly? How does the adapter look like? Also, if you create an on object for the `adapter` reference why do you test it for null one line below? – user Jan 24 '13 at 14:00
  • Code does not throw exception and I checked using debug. All methods executed without error. Yeah thats a silly mistake. – Coder Jan 24 '13 at 14:03

11 Answers11

235

Look at your onResume method in ItemFragment:

@Override
public void onResume() {
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); // reload the items from database
    adapter.notifyDataSetChanged();
}

what you just have updated before calling notifyDataSetChanged() is not the adapter's field private List<Item> items; but the identically declared field of the fragment. The adapter still stores a reference to list of items you passed when you created the adapter (e.g. in fragment's onCreate). The shortest (in sense of number of changes) but not elegant way to make your code behave as you expect is simply to replace the line:

    items = dbHelper.getItems(); // reload the items from database

with

    items.addAll(dbHelper.getItems()); // reload the items from database

A more elegant solution:

1) remove items private List<Item> items; from ItemFragment - we need to keep reference to them only in adapter

2) change onCreate to :

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setHasOptionsMenu(true);
    getActivity().setTitle(TITLE);
    dbHelper = new DatabaseHandler(getActivity());
    adapter = new ItemAdapter(getActivity(), dbHelper.getItems());
    setListAdapter(adapter);
}

3) add method in ItemAdapter:

public void swapItems(List<Item> items) {
    this.items = items;
    notifyDataSetChanged();
}

4) change your onResume to:

@Override
public void onResume() {
    super.onResume();
    adapter.swapItems(dbHelper.getItems());
}
Tomasz Gawel
  • 8,379
  • 4
  • 36
  • 61
  • Wouldn't it be cleaner to move the whole dbHelper thing into the Adapter? So you would only call `adapter.swapItems();` and the adapter would do the `dbHelper.getItems()` stuff. But anyway thanks for the answer :) – Ansgar Feb 16 '14 at 20:32
  • 7
    Why should you have to clear() and add the items again? Isn't that exactly the purpose of `notifyDataSetChanged()`? – Phil Ryan Aug 26 '14 at 04:17
  • 1
    @tomsaz can you help me with this http://stackoverflow.com/questions/28148618/listview-not-refreshing-after-click-on-button –  Jan 27 '15 at 12:59
  • 1
    Thanks @tomsaz Gawel, your swapItems really help me alot, I dont know why my adapter.notifydatasetchanged not works, as the "list" i am passing is also updated, even I have checked it by printing log, Can you Please explain me this concept – Kimmi Dhingra Jul 31 '15 at 06:58
  • Tomasz can you help with a similar question: http://stackoverflow.com/questions/35850715/recyclerview-dont-show-inserted-sqlite-data-instantly/35850839#35850839 I have tried this solution but with no succses. –  Mar 07 '16 at 22:22
  • 1
    This answer is correct. The problem is that the ADAPTER'S Item ArrayList was not being updated. This means you can call notifydatasetchanged until your face is blue without any effect. The Adapter is updating your dataset with the same dataset so there are NO changes. Another alternative to the solution posted in this answer that might be cleaner is: adapter.items = items; adapter.notifyDataSetChanged(); – Ray Li Apr 18 '17 at 02:09
25

You are assigning reloaded items to global variable items in onResume(), but this will not reflect in ItemAdapter class, because it has its own instance variable called 'items'.

For refreshing ListView, add a refresh() in ItemAdapter class which accepts list data i.e items

class ItemAdapter
{
    .....

    public void refresh(List<Item> items)
    {
        this.items = items;
        notifyDataSetChanged();
    } 
}

update onResume() with following code

@Override
public void onResume()
{
    super.onResume();
    items.clear();
    items = dbHelper.getItems(); //reload the items from database
    **adapter.refresh(items);**
}
Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
Santhosh
  • 1,962
  • 2
  • 16
  • 23
  • 1
    This is exactly right. The adapter's constructor expects to be passed items, but he only ever updates the outer class's field. – LuxuryMode Feb 03 '13 at 04:46
  • Hi Santhosh. Can you take a look at a similar problem: http://stackoverflow.com/questions/35850715/recyclerview-dont-show-inserted-sqlite-data-instantly/35850839#35850839 –  Mar 07 '16 at 22:23
8

In onResume() change this line

items = dbHelper.getItems(); //reload the items from database

to

items.addAll(dbHelper.getItems()); //reload the items from database

The problem is that you're never telling your adapter about the new items list. If you don't want to pass a new list to your adapter (as it seems you don't), then just use items.addAll after your clear(). This will ensure you are modifying the same list that the adapter has a reference to.

Justin Breitfeller
  • 13,737
  • 4
  • 39
  • 47
  • It's confusing that `adapter.clear()` doesn't force the adapter to realize that the view should refresh, but `adapter.add()` or `adapter.addAll()` does. Thanks for the answer though! – w3bshark Aug 01 '15 at 18:26
  • Note that I was using `items.addAll()` and not adapter.addAll(). The only thing that is letting the adapter react to changes is the `notifyDataSetChanged`. The reason the adapter sees changes at all is the `items` list is the same list that the adapter is using. – Justin Breitfeller Aug 13 '15 at 19:19
4

If the adapter is already set, setting it again will not refresh the listview. Instead first check if the listview has a adapter and then call the appropriate method.

I think its not a very good idea to create a new instance of the adapter while setting the list view. Instead, create an object.

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
     setListAdapter(adapter);
    }
    else{ //Already has an adapter
    adapter.notifyDataSetChanged();
    }

Also you might try to run the refresh list on UI Thread:

activity.runOnUiThread(new Runnable() {         
        public void run() {
              //do your modifications here

              // for example    
              adapter.add(new Object());
              adapter.notifyDataSetChanged()  
        }
});
AlexGo
  • 487
  • 4
  • 19
  • I am not sure how to implement UI thread. My main activity has 3 fragments (tabs) and the code in the question is related to one of the fragment that contains list view. The reason for passing items to `ItemAdapter` is I want to color the rows and the list view displays multiple data items. I have posted the code for adapter. – Coder Jan 27 '13 at 09:48
  • You need to put your code that populates your list in my example code using "this." instead of "activity" – AlexGo Jan 28 '13 at 14:45
  • In some cases it is not updated when you run the notifyDataSetChanged() in different thread, So the above solution is right for some cases. – Ayman Al-Absi Apr 28 '14 at 18:42
4

If you want to update your listview doesn't matter if you want to do that on onResume(), onCreate() or in some other function, first thing that you have to realize is that you won't need to create a new instance of the adapter, just populate the arrays with your data again. The idea is something similar to this :

private ArrayList<String> titles;
private MyListAdapter adapter;
private ListView myListView;

@Override
public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_activity);

    myListView = (ListView) findViewById(R.id.my_list);

    titles = new ArrayList<String>()

    for(int i =0; i<20;i++){
        titles.add("Title "+i);
    }

    adapter = new MyListAdapter(this, titles);
    myListView.setAdapter(adapter);
}


@Override
public void onResume(){
    super.onResume();
    // first clear the items and populate the new items
    titles.clear();
    for(int i =0; i<20;i++){
        titles.add("New Title "+i);
    }
    adapter.notifySetDataChanged();
}

So depending on that answer you should use the same List<Item> in your Fragment. In your first adapter initialization you fill your list with the items and set adapter to your listview. After that in every change in your items you have to clear the values from the main List<Item> items and than populate it again with your new items and call notifySetDataChanged();.

That's how it works : ).

hardartcore
  • 16,886
  • 12
  • 75
  • 101
  • Thanks for the reply. I did the changes as you mentioned. I have posted my code. It still doesnt work. Now it doesnt even show list view when new items are added. – Coder Jan 28 '13 at 02:24
  • I have changed the code. The strange thing to observe is that item is not getting updated in DB – Coder Jan 28 '13 at 07:48
  • This thread is for the database http://stackoverflow.com/questions/14555332/android-sqlite-not-updating-the-data – Coder Jan 28 '13 at 07:49
3
adpter.notifyDataSetInvalidated();

Try this in onPause() method of Activity class.

Garg
  • 2,731
  • 2
  • 36
  • 47
Som
  • 1,514
  • 14
  • 21
3

An answer from AlexGo did the trick for me:

getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {
         messages.add(m);
         adapter.notifyDataSetChanged();
         getListView().setSelection(messages.size()-1);
        }
});

List Update worked for me before when the update was triggered from a GUI event, thus being in the UI thread.

However, when I update the list from another event/thread - i.e. a call from outside the app, the update would not be in the UI thread and it ignored the call to getListView. Calling the update with runOnUiThread as above did the trick for me. Thanks!!

Baby Groot
  • 4,637
  • 39
  • 52
  • 71
user2996950
  • 439
  • 3
  • 8
3

Try this

@Override
public void onResume() {
super.onResume();
items.clear();
items = dbHelper.getItems(); //reload the items from database
adapter = new ItemAdapter(getActivity(), items);//reload the items from database
adapter.notifyDataSetChanged();
}
Gautami
  • 361
  • 1
  • 6
2

If your list is contained in the Adapter itself, calling the function that updates the list should also call notifyDataSetChanged().

Running this function from the UI Thread did the trick for me:

The refresh() function inside the Adapter

public void refresh(){
    //manipulate list
    notifyDataSetChanged();
}

Then in turn run this function from the UI Thread

getActivity().runOnUiThread(new Runnable() { 
    @Override
    public void run() {
          adapter.refresh()  
    }
});
  • 1
    This indeed made a difference for me as the update came over network via a different thread. – Chuck Dec 16 '19 at 08:31
1

Try like this:

this.notifyDataSetChanged();

instead of:

adapter.notifyDataSetChanged();

You have to notifyDataSetChanged() to the ListView not to the adapter class.

Garg
  • 2,731
  • 2
  • 36
  • 47
Jachu
  • 405
  • 5
  • 10
1
adapter.setNotifyDataChanged()

should do the trick.

ArtOfCode
  • 5,702
  • 5
  • 37
  • 56
Hitman
  • 588
  • 4
  • 10