简体   繁体   中英

Android Parcelable trouble

I am having trouble with implementing a Parcelable class in android.

The issue i am having is that i am receiving is that BinarySearchTree cannot be cast to a TreeNode.

When i print out what the type is when i am recieving it says tree node so im not entirely sure what the issue is.

This is the error

01-31 18:13:50.986: E/AndroidRuntime(1059): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.discoverycalendar/com.discoverycalendar.DiscoveryMainMenu}: 
java.lang.ClassCastException: com.DiscoveryUtils.BinarySearchTree cannot be cast to com.DiscoveryObjects.TreeNode

private TreeNode  root = null;


@Override
public int describeContents() {

    return 0;
}

public BinarySearchTree(Parcel in){

    this();
    root = (TreeNode) in.readValue(TreeNode.class.getClassLoader());
    in.readStringList(treeCont);
    in.readStringList(treeAsString);
}

public static final Creator<BinarySearchTree> CREATOR = new Creator<BinarySearchTree>() {

    public BinarySearchTree createFromParcel(Parcel source) {

        return new BinarySearchTree(source);
    }

    public BinarySearchTree[] newArray(int size) {

        return new BinarySearchTree[size];
    }
};

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeValue(root);
    dest.writeStringList(treeCont);
    dest.writeStringList(treeAsString);
}

The error i am receiving is when i try casting the return value into a TreeNode. I dont know why its thinking its a different object.

The simple reason is TreeNode is not Serializable or Parcelable. Hence you need to make a custom class that extends TreeNode and impelemtn one of them in order to flatten the data. Here is a document of support types. TreeNode isn't there.

public static final Creator and if it could be it would need to have the same constructor morphism and also because it is not the same package you would need to upcast to an object first eg

//....
Object treeinst = (Object) BinarySearchTree[x];
TreeNode treet = (TreeNode) treeinst;
return treet;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM