简体   繁体   中英

Application crashing when click on any item in ListView

I am a beginner in Android studio and I am having hard time to debug this issue.

when any item in my ListView gets clicked the application crashes, here is the class for the OnItemClick. The objective is to change the ListView from the Categories to the items inside the categories. The Categories and items are stored in a HashMap <String, String[]> , so passing the value of cat.toString() should return the string containing the category. Lastly using myList (Stored outside of the function) should return an array of string containing the items. However, when I click any of the items the application instantly crashes. Thanks for your help!

        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();
}

Variables

ListView myViewList;
Map<String, String[]> myList = new HashMap<String, String[]>();
ArrayAdapter<String> listAdapter;

Populating the 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);

You are getting exception because you are using listAdapter.clear(); which tries to clear the List inside the adapter. But apparently you have passed an array ( String[] categories ) which cannot be cleared. You should convert the array to ArrayList , (not just List ) by iterating through it and pass it into the adapter.

You should create the adapter by passing ArrayList

What do you think you're doing by creating a new adapter inside the onItemClick of old adapter?

Inside the onItemClick, don't create a new adapter. Instead, after clearing the adapter and creating a temp ArrayList, add all the temp ArrayList to the adapter.

listAdapter.addAll(tempItems);

Also to get text from a TextView, use cat.getText().toString(); instead of cat.toString();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM