I am trying to add a new entry to my listview and refresh it with the old entry still showing in the listview. Previously I was using ArrayAdapter which I was able to refresh after adding a new entry by using
adapter.notifyDataSetChanged();
But I am unable to use the code above with SimpleAdapter. Any suggestion? I have tried a couple of solutions but nothing has worked so far.
Below is the code I am using which is not adding an entry:
void beta3 (String X, String Y){
//listview in the main activity
ListView POST = (ListView)findViewById(R.id.listView);
//list = new ArrayList<String>();
String data = bar.getText().toString();
String two= data.replace("X", "");
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
HashMap<String,String> event = new HashMap<String, String>();
event.put(Config.TAG_one, X);
event.put(Config.TAG_two, two);
event.put(Config.TAG_three, Y);
list.add(event);
ListAdapter adapter = new SimpleAdapter(this, list, R.layout.list,
new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three},
new int[]{R.id.one, R.id.two, R.id.three});
POST.setAdapter(adapter);
}
If your beta3
method really is your function to add a new entry to your ListView
: it will set a new adapter with a new list every time you call it. So this will always result in a ListView
containing one entry. After exiting the beta3
method the reference to the list is gone.
You have to reuse the list
instance variable. Put ArrayList<HashMap<String,String>> list
in class/activity scope and initialize it once (e.g. in onCreate()
).
Another problem is that you use a ListAdapter
variable as reference to the SimpleAdapter
instance. ListAdapter
is an interface which doesn't provide a notifyDataSetChanged
method. You should use a SimpleAdapter
variable instead.
Here is an example:
public class MyActivity {
ArrayList<HashMap<String,String>> list;
SimpleAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
ListView POST = (ListView)findViewById(R.id.listView);
list = new ArrayList<HashMap<String, String>>();
adapter = new SimpleAdapter(this, list, R.layout.list,
new String[]{Config.TAG_one, Config.TAG_two, Config.TAG_three},
new int[]{R.id.one, R.id.two, R.id.three});
POST.setAdapter(adapter);
}
void beta3 (String X, String Y){
String two = ""; // adapt this to your needs
...
HashMap<String,String> event = new HashMap<String, String>();
event.put(Config.TAG_one, X);
event.put(Config.TAG_two, two);
event.put(Config.TAG_three, Y);
list.add(event);
adapter.notifyDataSetChanged();
}
}