Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't implement Parcelable because I can't make the CREATOR field static

The Parcelable docs say that the CREATOR field must be static, but when I try to implement it this way I get the error "Inner classes cannot have static declarations".

I attempted to resolve this by putting my CategoryButton in a separate class (not declaring it as an inner class in MainActivity) but then I couldn't call getApplicationContext() in the constructor to pass to the super.

public class MainActivity extends ActionBarActivity {


    private class CategoryButton extends Button implements Parcelable{
        private ArrayList<CategoryButton> buttons = null;
        private RelativeLayout.LayoutParams params = null;
        public CategoryButton(Context context){
            super(context);
        };
        public void setButtons(ArrayList<CategoryButton> buttons){
            this.buttons = buttons;
        }
        public void setParams(RelativeLayout.LayoutParams params){
            this.params = params;
        }
        public ArrayList<CategoryButton> getButtons(){
            return this.buttons;
        }
        public RelativeLayout.LayoutParams getParams(){
            return this.params;
        }



        public int describeContents() {
            return 0;
        }
        public void writeToParcel(Parcel out, int flags) {
            out.writeList(buttons);
        }
        public static final Parcelable.Creator<CategoryButton> CREATOR // *** inner classes cannot have static declarations
                = new Parcelable.Creator<CategoryButton>() {
            public CategoryButton createFromParcel(Parcel in) {
                return new CategoryButton(in); // *** 'package.MainActivity.this' cannot be referenced from a static context
            }

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

        private CategoryButton(Parcel in) {
            super(getApplicationContext());
            in.readList(buttons, null);
        }

    }

// ...other activity code
like image 875
Jpaji Rajnish Avatar asked Jul 12 '15 01:07

Jpaji Rajnish


1 Answers

You need to set your CategoryButton as inner static, i.e.

private static class CategoryButton extends Button implements Parcelable {
    ...
like image 96
Dimitar Genov Avatar answered Oct 05 '22 22:10

Dimitar Genov