Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.     } 
like image 410
Riccardo Neri Avatar asked Apr 12 '12 15:04

Riccardo Neri


People also ask

How do you handle rotation on Android?

If you want to manually handle orientation changes in your app you must declare the "orientation" , "screenSize" , and "screenLayout" values in the android:configChanges attributes. You can declare multiple configuration values in the attribute by separating them with a pipe | character.

How do I stop Android from restarting activity when changing orientations?

If you want the activity to not restart during screen orientation change, you can use the below AndroidManifest. xml. Please note the activity android:configChanges=”orientation|screenSize” attribute. This attribute makes the activity not restart when change screen orientation.


1 Answers

In Activity Tag of Manifest you should have to mention

<activity         android:name="com.example.ListActivity"         android:label="@string/app_name"          android:configChanges="keyboardHidden|orientation"> 

If you are using Android 2.3(API level 13 ) and above use

<activity         android:name="com.example.Activity"         android:label="@string/app_name"          android:configChanges="keyboardHidden|orientation|screenSize"> 

It should have to work.

It will work only with activity tag and not with application tag

like image 190
Bhagwat K Avatar answered Oct 05 '22 22:10

Bhagwat K