why I am not able to refresh/reload my ListView? I' ve written an app, which read out html-websites, saves the information in a String-Array an present it in my ListView. But every time I close and re-open the app the new content append to the existing content. In the first run I get, e. g., "1 2 3 4" and in the second run "1 2 3 4 1 2 3 4" and then " 1 2 3 4 1 2 3 4 1 2 3 4" and so on. I google a lot and find the methods to clear an ArrayAdapter (aa) and refill it with new data -> aa.clear() / aa.setModifyDataChanged() / aa.remove(String Object) / aa.add(String) but every time i call one Method my app does a force close and LogCat shows the exception: java.lang.UnsupportedOperationException. Why? This really grind my gears. The whole saturday afternoon I try to fix it -without success... Maybe somebody could help me!?
Here is my code-snippet
public class viewband extends ListActivity {
private static final int AKTUALISIEREN = 0;
private static ArrayList<String> al = new ArrayList<String>();
static String[] TST;
static ArrayAdapter<String> ad;
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case AKTUALISIEREN:
getIt();
//here a ad.close does a force close
setListAdapter(ad);
ListView lv = getListView();
lv.setTextFilterEnabled(true);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getIt();
ad = new ArrayAdapter<String>(this, R.layout.list_item, TST);
setListAdapter(ad);
// he开发者_如何学编程re, when I try ad.clear() my app does a force close
ListView lv = getListView();
lv.setTextFilterEnabled(true);
}
public static void getIt ()
{
// Here I get the source-code of the html-site and parse my content
// All necessary Information I write in my String Array TST, declared above in a static way
}
I hope, somebody could help me... Many thanks and a nice sunday.
You need to back your ArrayAdapter
by an ArrayList
or List
rather than a fixed-size array - the size of a fixed-size array cannot change nor can it be cleared (without re-creating it, which defaults the whole purpose)
So set the content of your adapter to be al
rather than TST
(on a side note you really need to name your variables with sensible names). Then call al.clear()
, al.add(String)
, to modify the dataset backing the adapter. Once the dataset has been changed call ad.notifyDataSetChanged
- this will then cause the list adapter and list to update the display.
Also your adapter should not be static (nor should TST
or al
probably) -- this will lead to memory leaks since the Adapter holds onto a reference to the current Context. NEVER make anything with a context static (drawables, adapters etc). Unless you know why you want something to be static keep it as a normal variable.
clear TST all time you update your listview
精彩评论