[英]Application crashing when click on any item in ListView
我是Android Studio的初学者,现在很难调试此问题。
当单击ListView中的任何项目时,应用程序崩溃,这是OnItemClick的类。 目的是将ListView从Categories更改为Categories中的项目。 类别和项目存储在HashMap <String, String[]>
,因此传递cat.toString()
的值应返回包含类别的字符串。 最后使用myList
(存储在函数外部)应返回包含项的字符串数组。 但是,当我单击任何一项时,应用程序立即崩溃。 谢谢你的帮助!
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Choosen category
TextView cat = (TextView) view;
ArrayList<String> tempItems = new ArrayList<String>();
//Toast.makeText(this, cat.getText().toString(),Toast.LENGTH_SHORT).show();
listAdapter.clear();
for(String val : myList.get(cat.getText().toString())){
tempItems.add(val);
}
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,tempItems);
listAdapter.notifyDataSetChanged();
}
变量
ListView myViewList;
Map<String, String[]> myList = new HashMap<String, String[]>();
ArrayAdapter<String> listAdapter;
填充ListView
//Creating a list of all categories
Set<String> myListKeys = myList.keySet();
ArrayList<String> categories = new ArrayList<String>();
for(String val : myListKeys){
categories.add(val);
}
//String[] categories = myListKeys.toArray(new String[myListKeys.size()]);
//Populating list
myViewList = (ListView) findViewById(R.id.groceryList);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,categories);
myViewList.setAdapter(listAdapter);
myViewList.setOnItemClickListener(this);
您正在获取异常,因为您正在使用listAdapter.clear();
它试图清除适配器内部的列表。 但是显然您已经传递了一个无法清除的数组( String[] categories
)。 您应该通过迭代将数组转换为ArrayList
(而不仅仅是List
)并将其传递到适配器。
您应该通过传递ArrayList
来创建适配器
您认为通过在旧适配器的onItemClick内创建一个新适配器来做什么?
在onItemClick内,请勿创建新的适配器。 相反,在清除适配器并创建临时ArrayList之后,将所有临时ArrayList添加到适配器。
listAdapter.addAll(tempItems);
另外,要从TextView获取文本,请使用cat.getText().toString();
而不是cat.toString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.