How to retain EditText data on orientation change? - android

I have a Login screen which consists of 2 EditTexts for Username and Password. My requirement is that on orientation change , input data(if any) in EditText should remain as it is and a new layout should also be drawn. I have 2 layout xml files- one in layout folder and other in layout-land folder. I am trying to implement following 2 approaches but none of them is perfect:
(1) configChanges:keyboardHidden - In this approach, I don't provide "orientation" in configChanges in manifest file. So I call setContentView() method in both onCreate() and onConfigurationChanged() methods. It fulfills both my requirements. Layout is changed and input data in EditTexts also remains as it is. But it has a big problem :
When user clicks on Login button, a ProgressDialog shows until server-response is received. Now if user rotates the device while ProgressDialog is running, app crashes. It shows an Exception saying "View cannot be attached to Window." I have tried to handle it using onSaveInstanceState (which DOES get called on orientation change) but app still crashes.
(2) configChanges:orientation|keyboardHidden - In this approach, I provide "orientation" in manifest. So now I have 2 scenarios:
(a) If I call setContentView() method in both onCreate() and onConfigurationChanged(), Layout is changed accordingly but EditText data is lost.
(b) If I call setContentView() method in onCreate() , but not in onConfigurationChanged(), then EditText data is not lost but layout also not changes accordingly.
And in this approach, onSaveInstanceState() is not even called.
So I am in a really intimidating situation. Is there any solution to this problem? Please help. Thanx in advance.

By default, Edittext save their own instance when changing orientation.
Be sure that the 2 Edittexts have unique IDs and have the same IDs in both Layouts.
That way, their state should be saved and you can let Android handle the orientation change.
If you are using a fragment, be sure it has a unique ID also and you dont recreate it when recreating the Activity.

A better approach is to let android handle the orientation change. Android will automatically fetch the layout from the correct folder and display it on the screen. All you need to do is to save the input values of the edit texts in the onSaveInsanceState() method and use these saved values to initialize the edit texts in the onCreate() method.
Here is how you can achieve this:
#Override
protected void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.login_screen);
...
...
String userName, password;
if(savedInstanceState!=null)
{
userName = savedInstanceState.getString("user_name");
password= savedInstanceState.getString("password");
}
if(userName != null)
userNameEdtTxt.setText(userName);
if(password != null)
passEdtTxt.setText(password);
}
>
#Override
protected void onSaveInstanceState (Bundle outState)
{
outState.putString("user_name", userNameEdtTxt.getText().toString());
outState.putString("password", passEdtTxt.getText().toString());
}

Give the element an id and Android will manage it for you.
android:id="#id/anything"

in onConfigurationChanged method, first get the data of both the edit texts in global variables and then call setContentView method. Now set the saved data again into the edit texts.

There are many ways to do this. The simplest is 2(b) in your question. Mention android:configChanges="orientation|keyboardHidden|screenSize" in your manifest so that Activity doesn't get destroyed on Orientation changes.
Call setContentView() in onConfigChange(). but before calling setContentView() get the EditText data into a string and set it back after calling setContentView()
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mEditTextData = mEditText.getText().tostring();//mEditTextData is a String
//member variable
setContentView(R.layout.myLayout);
initializeViews();
}
private void initializeViews(){
mEditText = (EditText)findViewById(R.id.edittext1);
mEdiText.setText(mEditTextData);
}

The following should work and is standard to the activities and fragments
#Override
public void onSaveInstanceState (Bundle outState)
{
outState.putString("editTextData1", editText1.getText().toString());
outState.putString("editTextData2", editText2.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate();
... find references to editText1, editText2
if (savedInstanceState != null)
{
editText1.setText(savedInstanceState.getString("editTextData1");
editText2.setText(savedInstanceState.getString("editTextData2");
}
}

Im restoring instance to restore values and it works fine for me :)
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.addtask2);
if(savedInstanceState!=null)
onRestoreInstanceState(savedInstanceState);
}

Remove android:configChanges attribute from the menifest file and let android handle the orientation change your data in edittext will automatically remain.
Now The problem you mentioned is with the progress dialog force close this is because when the orientation is changed the thread running in backgroud is trying to update the older dialog component whihc was visible. You can handle it by closing the dialog on savedinstancestate method and recalling the proceess you want to perform onRestoreInstanceState method.
Below is a sample hope it helps solving your problem:-
public class MyActivity extends Activity {
private static final String TAG = "com.example.handledataorientationchange.MainActivity";
private static ProgressDialog progressDialog;
private static Thread thread;
private static boolean isTaskRunnig;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new EditText.OnClickListener() {
#Override
public void onClick(View v) {
perform();
isTaskRunnig = true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void perform() {
Log.d(TAG, "perform");
progressDialog = android.app.ProgressDialog.show(this, null,
"Working, please wait...");
progressDialog
.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
//isTaskRunnig = false;
}
});
thread = new Thread() {
public void run() {
Log.d(TAG, "run");
int result = 0;
try {
// Thread.sleep(5000);
for (int i = 0; i < 20000000; i++) {
}
result = 1;
isTaskRunnig = false;
} catch (Exception e) {
e.printStackTrace();
result = 0;
}
Message msg = new Message();
msg.what = result;
handler.sendMessage(msg);
};
};
thread.start();
}
// handler to update the progress dialgo while the background task is in
// progress
private static Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "handleMessage");
int result = msg.what;
if (result == 1) {// if the task is completed successfully
Log.d(TAG, "Task complete");
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
isTaskRunnig = true;
}
}
}
};
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState" + isTaskRunnig);
if (isTaskRunnig) {
perform();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState");
if (thread.isAlive()) {
thread.interrupt();
Log.d(TAG, thread.isAlive() + "");
progressDialog.dismiss();
}
}

As pointed out by Yalla T it is important to not recreate the fragment. The EditText will not lose its content if the existing fragment is reused.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_frame);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Display the fragment as the main content.
// Do not do this. It will recreate the fragment on orientation change!
// getSupportFragmentManager().beginTransaction().replace(android.R.id.content, new Fragment_Places()).commit();
// Instead do this
String fragTag = "fragUniqueName";
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = (Fragment) fm.findFragmentByTag(fragTag);
if (fragment == null)
fragment = new Fragment_XXX(); // Here your fragment
FragmentTransaction ft = fm.beginTransaction();
// ft.setCustomAnimations(R.xml.anim_slide_in_from_right, R.xml.anim_slide_out_left,
// R.xml.anim_slide_in_from_left, R.xml.anim_slide_out_right);
ft.replace(android.R.id.content, fragment, fragTag);
// ft.addToBackStack(null); // Depends on what you want to do with your back button
ft.commit();
}

Saving state = Saving (Fragment State + Activity State)
When it comes to saving the state of a Fragment during orientation change, I usually do this way.
1) Fragment State:
Save and Restore EditText value
// Saving State
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("USER_NAME", username.getText().toString());
outState.putString("PASSWORD", password.getText().toString());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.user_name_fragment, parent, false);
username = (EditText) view.findViewById(R.id.username);
password = (EditText) view.findViewById(R.id.password);
// Retriving value
if (savedInstanceState != null) {
username.setText(savedInstanceState.getString("USER_NAME"));
password.setText(savedInstanceState.getString("PASSWORD"));
}
return view;
}
2) Activity State::
Create a new Instance when the activity launches for the first time
else find the old fragment using a TAG and the FragmentManager
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
fragmentManager = getSupportFragmentManager();
if(savedInstanceState==null) {
userFragment = UserNameFragment.newInstance();
fragmentManager.beginTransaction().add(R.id.profile, userFragment, "TAG").commit();
}
else {
userFragment = fragmentManager.findFragmentByTag("TAG");
}
}
You can see the the full working code HERE

Below code is work for me. Need to care two things.
Each Input Field (Edit Text or TextInputEditText) assign unique id.
Manifest activity declaration should have on configuration change attribute with below values.
android:configChanges="orientation|keyboardHidden|screenSize"
Sample activity declaration in manifest.
<activity
android:name=".screens.register.RegisterActivity"
android:configChanges="orientation|keyboardHidden|screenSize"
android:exported="true"
android:label="Registration"
android:theme="#style/AppTheme.NoActionBar" />
Sample declaration of
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/inputLayout"
style="#style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:boxCornerRadiusBottomEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusBottomStart="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopEnd="#dimen/boxCornerRadiusDP"
app:boxCornerRadiusTopStart="#dimen/boxCornerRadiusDP">
<com.google.android.material.textfield.TextInputEditText
android:id="#+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:fontFamily="#font/proxima_nova_semi_bold"
android:inputType="textCapWords"
android:lines="1"
android:textColor="#color/colorInputText"
android:textColorHint="#color/colorInputText" />
</com.google.android.material.textfield.TextInputLayout>

this may help you
if your android:targetSdkVersion="12" or less
android:configChanges="orientation|keyboardHidden">
if your android:targetSdkVersion="13" or more
android:configChanges="orientation|keyboardHidden|screenSize">

Related

Edit button in application doesn't save when edited

The EditButton of my app in Android Studio can be edited but once you have edited the texts it will not save when you exit the window. What to do?
public class BellPepperActivity extends AppCompatActivity {
TextView bpTextView;
AlertDialog dialog;
EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bell_pepper);
bpTextView = (TextView) findViewById(R.id.bpTextView);
dialog = new AlertDialog.Builder(this).create();
editText = new EditText(this);
dialog.setTitle("BELL PEPPER");
dialog.setView(editText);
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "SAVE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
bpTextView.setText(editText.getText());
}
});
bpTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
editText.setText(bpTextView.getText());
dialog.show();
}
});
}
}
By window, I assume you Activity (the AppCompatActivity that you have created). To maintain state in Activities you have to learn about the activity lifecycle. Basically when you leave you have to save the instance state:
// invoked when the activity may be temporarily destroyed, save the instance state here
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putString(TEXT_VIEW_KEY, editText.getText());
// call superclass to save any view hierarchy
super.onSaveInstanceState(outState);
}
and when you restore the state you do the same:
// This callback is called only when there is a saved instance previously saved using
// onSaveInstanceState(). We restore some state in onCreate() while we can optionally restore
// other state here, possibly usable after onStart() has completed.
// The savedInstanceState Bundle is same as the one used in onCreate().
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
editText.setText(savedInstanceState.getString(TEXT_VIEW_KEY));
}
Obviously you have to create a TEXT_VIEW_KEY as private final string at the top of your class:
private static final String TEXT_VIEW_KEY = "TEXT_VIEW_KEY";
Untested, but that should work for you now. For more advanced lifecycle handling learn about the Android Architecture Components, but that should wait until you understand the basic activity lifecycle in android App.

How to manually call onSaveInstanceState()

I am writing a program where I call multiple layouts on the same activity but then i noted that when i switch layouts, the changes made before the switch are not restored and onSavedInstanceState(Bundle outState) is not called. I have tried to manually call the method but i can't get the Bundle outState.
So the question really is: How do I get and store the current state of an activity to be recalled and/or restored at a time of my choosing?
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
// more code
}
#Override
public void onBackPressed() {
if (layoutId == R.layout.activity_contact_view) exit();
else if (layoutId == R.layout.main) {
Toast.makeText(NsdChatActivity.this, "Successful back button action", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_contact_view);
refreshContactList();
}
}
And then from a seperate class
public void updateList(final int found) {
LinearLayout layxout = (LinearLayout) ((Activity)mContext).getWindow().getDecorView().findViewById(R.id.others);
TextView t = new TextView(mContext);
t.setClickable(true);
t.setText(found + ". " + activity.sNames.get(found));
t.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
t.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//show chat view
activity.setContentView(R.layout.main);
TextView name = (TextView)activity.findViewById(R.id.clientName);
name.setText(activity.sNames.get(found).split(" \\(")[0]);
final ScrollView scroll = (ScrollView)activity.findViewById(R.id.scroll);
scroll.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View view, boolean b) {
scroll.fullScroll(View.FOCUS_DOWN);
}
});
}
});
layxout.addView(t);
}
I might be late for that but what you could do is to keep your sate as a member of the class. That way you can restore the state anytime you want.
Bundle mState;
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the state
savedInstanceState = mState;
super.onSaveInstanceState(savedInstanceState);
}
#Overrite
public void onRestoreInstanceState(Bundle savedInstance){
mState = savedInstance;
Restore();
}
public void Restore(){
//access your state and restore
}
Also you shouldn't use setContentView to switch between views it's expensive way to do it. You might want to check ViewSwitcher or ViewFlipper or someway to implement Fragments.
May be you should have a look at Application Fundamentals
Android calls onSaveInstanceState() before the activity becomes vulnerable to being destroyed by the system, but does not bother calling it when the instance is actually being destroyed by a user action (such as pressing the BACK key)
so you call multiple layouts on the same activity may not cause the above situation. For more details, you can refer to the question Android: Saving a state during Android lifecycle. Hope that helps!

restore Button text and visibility when activity is reCreated

My app uses one activity and many fragments, the activity which extends AppCompatActivity inflates an xml file which has a LinearLayout among
other ViewGroups, the purpose of this LinearLayout is to hold 3 buttons not all are visible at start.
In code, I change the view of LinearLayout and
the view and texts of some of its buttons depending on the action taken in the current fragment. However their state is not maintained when the
activity is reCreated after phone home key press.
Saving visibility and text of each button every time one gets chnaged in SharedPreferences is too misssy, so I tried the below code but failed.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mMainButtons_LL != null) {
mMainButtons_LL = (LinearLayout) savedInstanceState.getSerializable("mainButtons");
} else {
mMainButtons_LL = (LinearLayout) findViewById(R.id.main_buttons_LL);
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("mainButtons", (Serializable) mMainButtons_LL);
}
Change your code to something like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.your_layout); // << replace your layout id here
mMainButtons_LL = (LinearLayout) findViewById(R.id.main_buttons_LL);
if (savedInstanceState != null) {
mMainButtons_LL.setVisibility(savedInstanceState.getInt("visibility"));
mMainButtons_LL.setText(savedInstanceState.getString("text");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("visibility", mMainButtons_LL.getVisibility());
outState.putString("text", mMainButtons_LL.getText.toString());
}

How to save activity state after navigating?

I have an app with 3 activities,home,calculationResult and help.What I'm trying to do is save the details of the calculations on calculationResult when the user navigates to help.So when the user is in help and presses the action bar back icon,the results of the calculation will still be there in calculationResult.
I have tried to implement this so far by following this guide: Recreating an activity,But when I implemented it the variable I'm wanting to store is not recognized when using with savedInstanceState.Below is how I have tried to do this in the result class.Can someone point out where I have gone wrong with this or if this is the correct way to accomplish saving the activity state?
public class CalcResult extends Activity implements OnClickListener{
TextView result1;
static final String MARK1 = "marking1";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
if (savedInstanceState != null) {
// Restore value of members from saved state
//not recognizing this variable mark1 which I'm setting to the variable that stores the result of the calculation.
mark1 = savedInstanceState.getDouble(MARK1);
}
final Intent intent1=new Intent(this,AboutActivity.class);
final Intent intent2=new Intent(this,MainActivity.class);
final Intent intent3=new Intent(this,MainActivity.class);
final ViewGroup actionBarLayout = (ViewGroup) getLayoutInflater().inflate(
R.layout.a,
null);
// Set up your ActionBar
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowHomeEnabled(false);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
actionBar.setCustomView(actionBarLayout);
final Button actionBarHome = (Button) findViewById(R.id.action_bar_title);
actionBarHome.setBackgroundResource(R.drawable.ic_action_back);
actionBarHome.setOnClickListener(this);
actionBarHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent2);
}
});
final Button actionBarInfo = (Button) findViewById(R.id.action_bar_staff);
actionBarInfo.setBackgroundResource(R.drawable.ic_action_help);
actionBarInfo.setOnClickListener(this);
actionBarInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent1);
}
});
final Button actionBarHoome = (Button) findViewById(R.id.action_bar_home);
actionBarHoome.setBackgroundResource(R.drawable.appicon);
actionBarHoome.setOnClickListener(this);
actionBarHoome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(intent3);
}
});
result1 = (TextView)findViewById(R.id.markOne);
Intent intent = getIntent();
double markOne = intent.getDoubleExtra("number1", 0);
DecimalFormat df = new DecimalFormat("#.##");
result1.setText(String.valueOf(df.format(markOne)+"mm"));
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
//Also doesn't recognise markOne here ->
savedInstanceState.putDouble(MARK1, this.markOne);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Instead of this
double markOne = intent.getDoubleExtra("number1", 0);
You should write
markOne = intent.getDoubleExtra("number1", 0);
by declaring it again you are not assigning the value to the class level markOne
Also you can try setting the lauchmode of your calculateResult activity as singleTop
android:launchMode="singleTop"
This will use the same instance of the activity that already exist on the top of the stack so will have the same state as before.
Try calling finish in your Help activity when you move to CalculationResult activity.
for ex:
StartActivity(<Intent>);
finish();
onRestoreInstanceState() is called when Activity was killed by the OS. "Such situation happen when:
•orientation of the device changes (your activity is destroyed and recreated)
•there is another activity in front of yours and at some point the OS kills your activity in order to free memory.
Next time when you start your activity onRestoreInstanceState() will be called."
But in your case, this might not happen.
Approach i followed
I set a global varibale to act as a flag if i am launching this activity for the first time. If the global varibale is the same as what i had set, i leave the editText untouched. (in your case, result1). If the value is changed, i set the editText for this value. If the user clicks the editText even once, i track the change and store the value. When you think, the mark1 is no longer needed, you can set the value of flag again as "FIRSTENTRY". This would work.
Kindly try and let us know if you still face issues.
Step 1
Created a class to store a static Global variable.
public class Constants {
public static String sFlag= "FIRSTENTRY";
}
Step 2
Add this piece of code after "setContentView(R.layout.result);" line in your oncreate method. Instead of TextView, i have declared result1 as EditText.
if(!Constants.sFlag.equalsIgnoreCase("FIRSTENTRY"))
{
result1.setText(Constants.sFlag);
}
result1.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
Constants.sFlag = result1.getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
Constants.sFlag = result1.getText().toString();
}
});

Persist views across screen rotation

New to Android so I'm writing small programs to get familiar with how things work.
What has been giving me a headache so far are views created at runtime in combination with screen rotation.
After having little luck trying to use parcels, I solved the problem by just recreating the views after a rotation.
The program will add the entered text as a TextView to a TableLayout below the EditText.
Is there a better way of solving this? I could not find any "out of the box" methods for doing this.
public class MWEActivity extends Activity {
TableLayout table;
EditText txtInput;
ArrayList<String> savedEntry = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout)this.findViewById(R.id.table);
txtInput = (EditText)this.findViewById(R.id.txtInput);
txtInput.setOnEditorActionListener(new OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if(event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN){
TextView newtext = new TextView(getApplicationContext());
newtext.setText(txtInput.getText());
savedEntry.add(newtext.getText().toString());
table.addView(newtext);
txtInput.setText("");
return true;
}
return false;
}
});
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putStringArrayList("entry", savedEntry);
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
if(savedInstanceState.getStringArrayList("entry") == null){
savedEntry = new ArrayList<String>();
savedEntry.add("Return was NULL");
}else{
savedEntry = savedInstanceState.getStringArrayList("entry");
}
for(String s : savedEntry){
TextView tv = new TextView(getApplicationContext());
tv.setText(s);
table.addView(tv);
}
super.onRestoreInstanceState(savedInstanceState);
}
}
Either you have to disable orientation change like in previous answer, or just rely
on standard facility. It will pause an then recreate your activity. No extra code is necessary. You can also provide different layouts for different orientations:
http://developer.android.com/guide/practices/screens_support.html
You can stop the reloading of the activity by putting
android:configChanges="orientation"
in the manifest.xml for the activity and implementing onConfigurationChanged.
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
If your layout is the same you should not need to do anything else.

Categories

Resources