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

前端 未结 2 672
孤独总比滥情好
孤独总比滥情好 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<MyParcelable> CREATOR
             = new Parcelable.Creator<MyParcelable>() {
         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();
     }
    
    
    }
    
    0 讨论(0)
  • 2020-12-18 04:00
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
    

    adapterView is referenced to Spinner, not the item you clicked, you should cast the "view" parameter instead.


    @Rock Lee After rotated the layout would be refresh, you should resetup the spinner in some callback function like onConfigurationChanged(Configuration newConfig), Android listview disappears after screen rotation

    0 讨论(0)
提交回复
热议问题