0

I'm trying to populate a listView, but if I initialize it after onCreate it doesn't appear. I tried to initialize it into the onCreate and use adapter.notifyDataSetChanged(); after I insert values into my String array used to populate the listView but I have no success.

Does someone know how to solve this problem? I checked other questions but I didn't find an answer to my problem.

Thanks in advance.

Gabriele Puia
  • 333
  • 1
  • 3
  • 10

1 Answers1

2

Maybe you need to call adapter.notifyDataSetChanged() inside the UI thread.

Also it's better to use an ArrayList<String> instead of a String[]

Keep references to both the ArrayList and ArrayAdapter inside your activity class.

private ArrayList<String> items;
private ArrayAdapter<String> adapter;

Initialize your ArrayList<String> and set adapter in your onCreate

items = new ArrayList<String>();
// add initial items
items.add("1st item");
// create adapter
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
// set the adapter
listView.setAdapter(adapter);

Now whenever you want to change the items, call the add(), remove(), etc methods of the ArrayList and subsequently call adapter.notifyDataSetChanged(). The change to the ArrayList can be done in any thread, but adapter.notifyDataSetChanged() should be called in UI thread.

For example in a button press you might wanna do

items.add("New item");
adapter.notifyDataSetChanged();

Also you might wanna check these: this and

this

PS: Sorry for my bad posting skills. I'm new.

Raihanul
  • 91
  • 1
  • 5