Search code examples
androidarraylistclasscastexception

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String when trying to retrieve arrayList items


I am sending the arrayList from my main class which is listView to another class which displays details of individual items of the list.

 lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {
 Intent intent = new Intent(ListActivity.this, DetailActivity.class);
 intent.putExtra("event",myList);
 startActivity(intent);
 }

Now in DetailActivity.class this is how I get the ArrayList. I can see all the values correctly when I print the arrayList.

 Intent i = getIntent();
 ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("event");
 System.out.println(myList);

Here's how I am trying to retrieve the first value and store it in a variable.

  for (int e=0;e<myList.size();e++)
    {
        String name = myList.get(0);
        System.out.println(name);
    }

I get java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.String What am I doing wrong here?


Solution

  • In your first activity myList is Array of HashMap, and you try to cast it to String which cannot be done.

     ArrayList<HashMap<String, String>> myList = (ArrayList<HashMap<String, String>>) getIntent().getSerializableExtra("event");
    

    This should be the correct way to convert it