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

Était-ce utile?

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

Autres conseils

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top