EditText data is lost on rotating the device

筅森魡賤 提交于 2019-12-06 08:30:01
Ilya Demidov

Use the put methods to store values in onSaveInstanceState:

protected void onSaveInstanceState(Bundle extra) {
  super.onSaveInstanceState(extra);
  extra.putString("text", "your text here");
}

And restore the values in onCreate:

public void onCreate(Bundle extra) {
  if (extra != null) {
    String value = extra.getString("text");
  }
}

EDIT(What actually worked):

try to delete android:configChanges="orientation|keyboardHidden" from manifest.

Good luck!

josephus

First remove all onConfigurationChanged and configChanges=orientation stuff you did - this solution is for the weak. Then do the following:

  1. Override onRetainNonConfigurationInstance() so that it returns the texts that you need to save on device rotation. You may need to create a simple Object that contains these values - for example:

    public class TextObject {
        public String loginText;
        public String passwordText;
    }
    
  2. In onCreate, after initializing your views, try getting the saved object from rotation via getLastNonConfigurationInstance(). This will return null if it's the first time you're going through onCreate, so you need to do a null check. Example:

    TextObject mySavedTextObject = (TextObject) getLastNonConfigurationInstance();
    if(mySavedTextObject!=null) {
      myLoginEditText.setText(mySavedTextObject.loginText);
      myPasswordEditText.setText(mySavedTextObject.passwordText);
    }
    

On https://github.com/jcraane/AndroidBundleState you find a very simple library handling the state logic for you. All you have to do is annotate you fields.

@BundleState("state_name") private String name; The library will restore the values in the fields for you after the rotationChange.

Simply set this for your login text and password text

textView.setSaveEnabled(false);

At the point (time) in your code where the orientation is about to change, implement this:

this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

But this has to be placed before the screen is changing orientation e.g. while returning from device camera to your app, it often happens that the app returns and changes the orientation again without any reason.

And don`t forget to mark me =)

Good luck.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!