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
Chris Ed
  • 35
  • 4
  • 1
    it is telling you that `arg0.getItemAtPosition(arg2)` is a String and cannot be type cast into CustomObj – mkjh Jun 03 '21 at 09: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. – Stultuske Jun 03 '21 at 09: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. – Chris Ed Jun 03 '21 at 09:10

1 Answers1

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.

Shivam Pokhriyal
  • 1,044
  • 11
  • 26
  • 1
    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 ... – Chris Ed Jun 03 '21 at 09:21