0

I've been trying to create an Android Parcelable object but keep running into the error "Inner classes cannot have static declarations". For reference I have been looking at the official Android tutorial located here.

My current code is as follows:

public class AppDetail implements Parcelable {
    CharSequence label;
    CharSequence name;
    Drawable icon;

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeArray(new Object[] { this.label, this.name, this.icon });
    }

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

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

    public AppDetail() {}

    public AppDetail(Parcel in) {
        Object[] data = in.readArray(AppDetail.class.getClassLoader());

        this.label = (String)data[0];
        this.name = (String)data[1];
        this.icon = (Drawable)data[2];
    }
}

I found someone else online who encountered a similar issue and concluded the compiler didn't like the static initializer block (rather than the static class itself) - I tried following this advice and declaring like this: public static Parcelable.Creator<AppDetail> CREATOR and initialising elsewhere - however I got the same error.

How can I get this / something workable to compile?

jProg2015
  • 1,098
  • 10
  • 40

1 Answers1

4

Yes it is- should that matter?

Yes, because that is why you are getting your error. Your error is not due to Parcelable.Creator<AppDetail>, but due to AppDetail itself. You cannot have static methods or data members, like CREATOR, on an inner class.

The net effect of this is that classes directly implementing Parcelable need to be either static inner classes (i.e., public static class AppDetail implements Parcelable) or regular (non-inner) Java classes.

Based upon this implementation, just making AppDetail be a public static class should solve your problem.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491