2011-04-03 84 views
0

为什么我无法刷新/重新加载我的ListView? 我写了一个应用程序,它读出html网站,将信息保存在我的ListView中存在的字符串数组中。 但每次关闭并重新打开应用程序时,新内容都会附加到现有内容。 在我第一次运行时,例如“1 2 3 4”,并在第二次运行“1 2 3 4 1 2 3 4”,然后“1 2 3 4 1 2 3 4 1 2 3 4”等等。 我google了很多,找到清除ArrayAdapter(AA)和新的数据填充它 方法 - > aa.clear()/ aa.setModifyDataChanged()/ aa.remove(String对象)/ aa.add(字符串) 但每次我调用一个Method时,我的应用程序会关闭一个强制,并且LogCat会显示异常:java.lang.UnsupportedOperationException。 为什么?这真的磨砺我的齿轮。整个星期六下午我试图修复它 - 没有成功... 也许有人可以帮助我!?问题刷新listView:UnsupportedOperationException

这里是我的代码片断

公共类viewband扩展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); 
    // here, 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   
} 

我希望有人可以帮我... 非常感谢和一个不错的周日。

回答

0

明确TST所有的时间更新您的ListView

1

您需要备份您的ArrayAdapterArrayListList,而不是一个固定大小的数组 - 一个固定大小的数组的大小无法改变,也不能被清除(不重新创建它,默认是全部用途)

因此,将适配器的内容设置为al而不是TST(在旁注中,您确实需要用明智的名称命名变量)。然后调用al.clear()al.add(String),修改数据集支持的适配器。一旦数据集已经改变呼叫ad.notifyDataSetChanged - 这将进而导致清单适配器,并列出更新显示。

而且适配器不应该是静态的(也不应TSTal可能) - 由于适配器保持到当前上下文的参考,这将导致内存泄漏。切勿使用静态上下文(可绘制,适配器等)进行任何操作。除非你知道为什么你想要的东西是静态保持它作为一个正常的变量。