androidandroid-layoutandroid-intent

Handle screen rotation without losing data - Android


I'm becoming crazy figuring out what is the best way to handle screen rotation. I read hundreds of questions/answers here but I'm really confused.

How can I save myClass data before the activity is re-created so I can keep everything for redrawing activity without another useless initialization?

Is there a cleaner and better way than parcelable?

I need to handle rotation because I want to change layout in Landscape mode.

public class MtgoLifecounterActivity extends Activity {

    MyClass myClass;

    // Called when the activity is first created
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        If ( ?? first run...myClass == null ? ) {
            myClass = new MyClass();
        } else {
            // do other stuff but I need myClass istance with all values.
        }
        // I want that this is called only first time. 
        // then in case of rotation of screen, i want to restore the other instance of myClass which
        // is full of data.
    }

Solution

  • 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 MyParcelable 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();
     }
    
    
    }