Issue in Parcelable implementation in Android Studio 1.2.2 Upgrade

365 views Asked by At

My Parcelable Class :

public class Category  implements Parcelable{
    int id;
    String name;
    Department department;
    @Override
    public int describeContents() {
        return 0;
    }
    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(name);
        dest.writeParcelable(department, 10);

    }

    public static final Parcelable.Creator<Category> CREATOR = new Parcelable.Creator<Category>() {
        public Category createFromParcel(Parcel in) {
            return new Category(in);
        }

        public Category[] newArray(int size) {
            return new Category[size];
        }
    };

    public Category(Parcel in){


        id=in.readInt();
        name=in.readString();
        department= in.readParcelable(department.getClass().getClassLoader());

    }

When i send object of category class to other activity, then writeToparcel() and createFromParcel() method got called, I observed NullPointerException at

department= in.readParcelable(department.getClass().getClassLoader());

But while debugging i had checked that in writeToParel() method department object is stored correct, but how that is not returned back, in createFromParcel() , Same code is running fine in Android Studio 1.1 . Currently I had changed my implementation code like that :

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeString(name);
    dest.writeParcelable(department, Constants.PARCELABLE_DEPARTMENT);
    dest.writeInt(department.getId());
    dest.writeString(department.getName());
}

public Category(Parcel in){
    id=in.readInt();
    name=in.readString();
    department=new Department(in.readInt(),in.readString());

}

Now, the code is working fine , but now i need to create extra department object, which i think is not good way .
Does any one have any solution regarding the problem ?

1

There are 1 answers

3
Simas On BEST ANSWER
department.getClass().getClassLoader()

This is what throws the error. department == null and you're trying to fetch it's class. Therefore it throws an NPE.

Instead, fetch the class loader via the class object:

Department.class.getClassLoader()