Lockon Lockon - 2 months ago 32
Android Question

Unable refresh listview with simpleadapter

I am trying to add a new entry to my listview and refresh it with the old entry still show in the listview. Previously i was using ArrayAdapter which i am able to refresh the listview with new entry by using

adapter.notifyDataSetChanged();


But the above codes i am unable to use with simpleadapter.any suggestion?
I have try a couple of solution but nothing have work so far.

Below is the code i am using which is unable to add

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);
}

Answer

If your beta3 method really is your function to add a new entry to your ListView: it will only set a new adapter with a new (empty) list. After exiting the beta3 method the list is gone.

You have to reuse the list instance. Put ArrayList<HashMap<String,String>> list in class/activity scope and initialize it once (e.g. in onCreate()).

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();
    }

}