Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to Refresh Adapter/ListView on Android

My book, "Hello Android" gives this as a way of using a custom db helper, setting up a cursor, and then setting up an adapter as follows:

Cursor cursor CustomDatabaseHelper test = new CustomDatabaseHelper(this); try {         cursor = getData();         showData(cursor); } finally {         test.close(); } 

With this however, everytime I need to refresh the data set, I need to keep running this block of code (which gets a bit difficult inside an onClick() for a button due to "this" not being available.

Is this the best way to refresh the data set, or should I look towards removing the .close and issue an adapter.notifyDataSetChanged()? If I do this, sometimes I get a force close as (and I can't remember at the moment) but sometimes it cannot Delete properly - I think this may be because the database is currently open and it tries to open again.

Should we also be declaring the variables for the Cursors, DatabaseHelpers and Adapter in the Class (outside of the OnCreate) so that they are accessible to all the functions?

I realise this is just poor programming at this stage, but Im trying to get some pointers as to the best way of doing things.

like image 237
Simon Avatar asked Nov 16 '10 12:11

Simon


People also ask

How do I refresh Arrayadapter?

You can modify existing adapter data and call notifyDataSetChanged(). In your case you should call listView. setAdapter(adapter) in onClick method.

How do you refresh an ArrayList?

To update or set an element or object at a given index of Java ArrayList, use ArrayList. set() method. ArrayList.

What is notifyDataSetChanged in android?

notifyDataSetChanged() Notifies the attached observers that the underlying data has been changed and any View reflecting the data set should refresh itself.

What is the use of ListView in android?

A list view is an adapter view that does not know the details, such as type and contents, of the views it contains. Instead list view requests views on demand from a ListAdapter as needed, such as to display new views as the user scrolls up or down. In order to display items in the list, call setAdapter(android.


2 Answers

You should use adapter.notifyDataSetChanged(). What does the logs says when you use that?

like image 141
Macarse Avatar answered Oct 01 '22 21:10

Macarse


Simply add these code before setting Adapter it's working for me:

    listView.destroyDrawingCache();     listView.setVisibility(ListView.INVISIBLE);     listView.setVisibility(ListView.VISIBLE); 

Or Directly you can use below method after change Data resource.

   adapter.notifyDataSetChanged() 
like image 38
sravan Avatar answered Oct 01 '22 21:10

sravan