Question

I'm starting programming for Android so I don't have much idea. I have a .xml with a button and a listview and when I click the button I get into the onClick method that I told it and I want my listView to update, but I'm not able to make this happen :S

I leave you my java code:

For the list:

list = (ListView) findViewById(R.id.listView1);

String[] values = new String[] {};

adapter = new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1, android.R.id.text1, values);

list.setAdapter(adapter); 

For the button:

public void onClickMyButton() {

            values = new String[] {"a", "b", "c"};
            adapter.notifyDataSetChanged();

    }

If you need anymore code, I'll copy it with no problem

Thanks

Was it helpful?

Solution

You need to add your items in the adapter before you notify the adapter the data has changed:

    public void onClickMyButton(View view) {
            values = new String[] {"a", "b", "c"};
            if(adapter!=null){
                        adapter.clear()
                        for(String value:values)
                                    adapter.add(value)
            }
            adapter.notifyDataSetChanged();
    }

OTHER TIPS

Finally, after trying a lot of possibilities, this one the only one that worked as I wanted, maybe not the best one:

public void onClickMyButton(View view) {
    values = new String[] {"1","2","3"} ;
    adapter = new ArrayAdapter<String>(this,
               android.R.layout.simple_list_item_1, android.R.id.text1, values);

    list.setAdapter(adapter);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top