When the data associated with array adapter is changed, invalidating the listview is sufficient to show the updated values? Following piece of code is not working, did i misunderstood something here.?
public class ZeroItemListActivity extends Activity { private ArrayList<String> listItems=new ArrayList<String>(); private ListView mMyListView; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mMyListView=(ListView) findViewById(R.id.MyListView); mMyListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,listItems)); } public void addItem(View v){ listItems.add("list Item"); mMyListView.invalidate(); } }
Layout used :
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" /> <ListView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/MyListView"></ListView> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/AddItemsButton" android:text="Add Items" android:onClick="addItem"></Button> </LinearLayout>
To refresh the ListView in Android, call notifyDataSetChanged() method on the Adapter that has been set with the ListView. Also note that the method notifyDataSetChanged() has to be called on UI thread.
This example demonstrates how do I dynamically update a ListView in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Scroll down and long-press the “Settings” widget, then place it on your home screen. You'll get a list of features that the Settings shortcut can access. Tap “Notification Log.” Tap the widget and scroll through your past notifications.
substitute:
mMyListView.invalidate();
for:
((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged();
If that doesnt work, refer to this thread: Android List view refresh
Change this line:
mMyListView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems));
to:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems) mMyListView.setAdapter(adapter);
and after updating the value of a list item, call:
adapter.notifyDataSetChanged();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With