F.Mi
F.Mi

Reputation: 51

I cant cast in onclicklistener

I have 2 simple different classes that one extends another. my first class is:

public class MyObject {}

without something in it.

and another:

public class People extends MyObject{
public  String UserId;


public void setUserId(String userId) {
    UserId = userId;
}

public String getUserId() {
    return UserId;
}
}

I was going to cast myobject to people in my adapter and in onBindViewHolder method,and I could do it well and worked,as below:

   @Override
public void onBindViewHolder(final RecyclerViewHolder holder, int position) {

        final People people = (People) array.get(position);
        //array is:ArrayList<MyObject> array
        ...}

but the problem is when I'm going to do this cast in the same class but in onclicklistener like this:

holder.rlsearchitem.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
            People people1= (People) savedPeopleArray.get(i);
            //savedPeopleArray is:ArrayList<MyObject> savedPeopleArray 
            ....      
            }
        });

I get this error:

com.example.qa.setGet.MyObject cannot be cast to com.example.qa.setGet.People

why do I get this error even though I used this cast before and it worked?!

Upvotes: 0

Views: 46

Answers (2)

hakim
hakim

Reputation: 3909

It because you insert values inside ArrayList array as People, for example: private List<MyObject> array = new ArrayList()

and then somewhere you insert

final MyObject obj = new People();
array.add(obj)

in short you insert runtime object People inside array, so downcasting is no problem.

but in ArrayList savedPeopleArray you insert MyObject, for example like this:

final MyObject obj = new MyObject();
savedPeopleArray = new MyObject();

at runtime element of savedPeopleArray is instance with type MyObject, so it is not possible to downcasting to People since the value is MyObject To prevent ClassCastException you can use instance before casting, for example

MyObject obj= savedPeopleArray.get(i);
if (obj instanceof People){
   People people = (People) obj;
}

I think this SO link will help you understand more about upcasting/downcasting in java What is the difference between up-casting and down-casting with respect to class variable

Upvotes: 1

Gabriel Slomka
Gabriel Slomka

Reputation: 1527

The only explanation i could think on why this happening is, you actually have MyObject inside that list, and not People.

Try adding

if ( savedPeopleArray.get(i) instanceof People )

probably you instantiate a MyObject only. At least the only explanation i could think of. How are you filling that list ?

Upvotes: 0

Related Questions