0

i have a custom adapter for a listview which receives an array of a custom object "CustomObj" and display it in the listview,

ArrayList<CustomObj> items;

trying to use AdapterView.OnItemClickListener:

@Override
        public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {
            CustomObj obj = (CustomObj)arg0.getAdapter().getItem(arg2);
        }
    };

or

@Override
        public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {
            CustomObj obj = (CustomObj)arg0.getItemAtPosition(arg2);
        }
    };

Causes the Error:

java.lang.String cannot be cast to com.example.project1.CustomObj
3
  • 1
    it is telling you that arg0.getItemAtPosition(arg2) is a String and cannot be type cast into CustomObj Commented Jun 3, 2021 at 9:08
  • the error seems self-explanatory as mkjh already said. maybe you can map a String to a CustomObj, but you can't cast it. Commented Jun 3, 2021 at 9:09
  • which is more confusing , because when i try to assign it to a string like: String stg = arg0.getAdapter().getItem(arg2); shows me an error: Required type: String Provided: Object. Commented Jun 3, 2021 at 9:10

1 Answer 1

1

The code you're trying to use

arg0.getAdapter().getItem(arg2);

will return the item at the arg2 position in the dataset.

Now what exactly is your data set? You might have used this somewhere

adapterView.setAdapter(YOUR_ADAPTER)

This is how you set an adapter to your adapter view. The adapter provides the data for your view. Now if you go to the YOUR_ADAPTER class, you'll find a method:

public Object getItem(int i) {

The values this method is returning, are the ones you'll get on the item click event arg0.getAdapter().getItem(arg2);.

In your case, it seems like the getItem returns a string, so you can't cast it to CustomObj.

Sign up to request clarification or add additional context in comments.

1 Comment

yes indeed, my getItem(int i) was returning items.get(i).toString(); which was causing this problem and i could notice due to how long my code is. i feel so stupid ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.