Reputation: 1678
I am running the following code where:
@Override
protected void onListItemClick(ListView listView, View view, int position,
long id) {
String item = (String) getListAdapter().getItem(position);
Toast.makeText(this, item + " selected", Toast.LENGTH_LONG).show();
Art art = (Art) getListAdapter().getItem(position);
/*Intent intent = new Intent(this,X.class);
intent.putExtra("art", art);
this.startActivity(intent);*/
}
My Art Class goes like this:
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.SerializedName;
public class Art implements Serializable{
private static final long serialVersionUID = 8359220892008313080L;
@SerializedName("body")
private String body;
@SerializedName("title")
private String title;
@SerializedName("images")
private List<Images> images;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<Images> getImages() {
return images ;
}
public void setImages(List<Images> images) {
this.images = images;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("***** Art *****\n");
sb.append("BODY=" + getBody() + "\n");
sb.append("TITLE=" + getTitle() + "\n");
sb.append("IMAGES=" + getImages() + "\n");
sb.append("*****************************");
return sb.toString();
}
}
This is my log and it crashes at this particular line: Art art = (Art)getListAdapter().getItem(position);
E/AndroidRuntime(912): FATAL EXCEPTION: main
E/AndroidRuntime(912): java.lang.ClassCastException: java.lang.String cannot be cast to com.Art
E/AndroidRuntime(912): at com.ArtListActivity.onListItemClick(ArtListActivity.java:118)
E/AndroidRuntime(912): at android.app.ListActivity$2.onItemClick(ListActivity.java:319)
Any ideas/help as of why it's happening and a possible fix would be greatly appreciated, thanks for reading.
Upvotes: 0
Views: 68
Reputation: 49
A class cast like:
Child child = new Child();
Parent parent = (Parent) child;
will work if Parent is a super class of Child.
As class Art is not a super class of class type String the cast will fail.
Example below :
public class CastExample {
public static void main(String[] args) {
Child child = new Child();
Parent parent = (Parent) child;
System.out.println(parent.whoami());
// Output: I am a Parent
}
private static class Parent {
public String whoami() {
return "I am a Parent";
}
}
private static class Child extends Parent {
public String whoami() {
return "I am a Child";
}
}
}
Upvotes: 0
Reputation: 2122
You cant cast the items to both String
and Art
. In your case the adapter has a list of Strings thats why it throws a ClassCastException.
Upvotes: 1
Reputation: 63054
Art art = (Art) getListAdapter().getItem(position);
getItem is returning a String and you are casting it to an Art. Your list adapter is holding strings and not Arts.
Upvotes: 1