簡體   English   中英

單擊ListView中的任何項目時,應用程序崩潰

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM