Android NullPointerException - Spinner onItemSelected `view` parameter is null after rotating

前端 未结 2 680
孤独总比滥情好
孤独总比滥情好 2020-12-18 03:50

Note: A limiting workaround from another, similar SO question\'s answer worked for me, but I am interested in finding a true solution. The workaround was to

2条回答
  •  别那么骄傲
    2020-12-18 03:53

    you can use override method onSaveInstanceState() and onRestoreInstanceState(). or to stop calling onCreate() on screen rotation just add this line in your manifest xml android:configChanges="keyboardHidden|orientation"

    note: your custom class must implements Parcelable example below.

    @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putParcelable("obj", myClass);
        }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
     // TODO Auto-generated method stub
     super.onRestoreInstanceState(savedInstanceState);
     myClass=savedInstanceState.getParcelable("obj"));
    }
    
    public class MyClass implements Parcelable {
         private int mData;
    
     public int describeContents() {
         return 0;
     }
    
     /** save object in parcel */
     public void writeToParcel(Parcel out, int flags) {
         out.writeInt(mData);
     }
    
     public static final Parcelable.Creator CREATOR
             = new Parcelable.Creator() {
         public MyParcelable createFromParcel(Parcel in) {
             return new MyParcelable(in);
         }
    
         public MyParcelable[] newArray(int size) {
             return new MyParcelable[size];
         }
     };
    
     /** recreate object from parcel */
     private MyParcelable(Parcel in) {
         mData = in.readInt();
     }
    
    
    }
    

提交回复
热议问题