刷新listView时出现问题:UnsupportedOperationException

时间:2011-04-03 10:56:14

标签: java android exception listview

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

这是我的代码段

public class 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        
}

我希望,有人可以帮助我...... 非常感谢,周日愉快。

2 个答案:

答案 0 :(得分:1)

您需要以ArrayAdapterArrayList而不是固定大小的数组来支持List - 固定大小数组的大小不能更改也无法清除(没有重新创建它,这默认了整个目的)

因此,请将适配器的内容设置为al而不是TST(在旁注上,您确实需要使用合理的名称命名变量)。然后调用al.clear()al.add(String)来修改支持适配器的数据集。更改数据集后,请调用ad.notifyDataSetChanged - 这将导致列表适配器和列表更新显示。

同样你的适配器不应该是静态的(也不应该TSTal) - 这会导致内存泄漏,因为适配器保持对引用的引用当前背景。永远不要使用上下文静态(drawables,adapter等)。除非你知道为什么你想要某些东西是静态的,否则将它保持为正常变量。

答案 1 :(得分:0)

在您更新列表视图时清除TST