gpt4 book ai didi

java - 刷新 listView : UnsupportedOperationException 时出现问题

转载 作者:行者123 更新时间:2023-12-01 15:53:30 24 4
gpt4 key购买 nike

为什么我无法刷新/重新加载我的 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。为什么?这真的让我很累。整个周六下午我都试图修复它——但没有成功......也许有人可以帮助我!?

这是我的代码 fragment

公共(public)类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
}

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

最佳答案

您需要通过 ArrayListList 而不是固定大小的数组(固定大小的大小)来支持您的 ArrayAdapter数组不能更改也不能被清除(无需重新创建它,这默认了整个目的)

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

此外,您的适配器不应该是静态的(TSTal 可能也不应该)——这会导致内存泄漏,因为适配器保留对当前 Context 的引用。切勿使任何内容具有静态上下文(可绘制对象、适配器等)。除非您知道为什么想要静态的东西,否则请将其保留为普通变量。

关于java - 刷新 listView : UnsupportedOperationException 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5529151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com