savedInstanceState返回null [英] savedInstanceState returning null

查看:142
本文介绍了savedInstanceState返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释为什么我的savedInstanceState中的值为null吗?我有3个小部件,一个EditText,Button和TextView.这个人输入他们想要的东西.短语将在TextView中弹出.翻盖手机时,我想保留输入.我尝试保存状态,但是当重新创建活动"时,我的Toast说它为空:

Can someone please explain why the value in my savedInstanceState is null? I have 3 widgets, an EditText, Button and TextView. The person types in what they want. The Phrase pops up in the TextView. I want to keep the input when I flip the phone. I tried saving the state but when the Activity is recreated, my Toast says that it's null:

public class MainActivity extends AppCompatActivity {
private EditText input;
private TextView output;
private Button button;
private String newString = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    input = (EditText)findViewById(R.id.input);
    output = (TextView) findViewById(R.id.output);
    button = (Button)findViewById(R.id.button);

    if (savedInstanceState!=null){
        Toast.makeText(this, "SAVED IS " + savedInstanceState.getString("example"), Toast.LENGTH_SHORT).show();
    }


    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            newString = input.getText().toString();
            output.setText(newString);
        }
    });

}

@Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putString("example",newString);
}}

推荐答案

您需要使用此函数 onSaveInstanceState(Bundle outState),该函数没有 PersistableBundle outPersistentState

You need to use this function onSaveInstanceState(Bundle outState), the one without PersistableBundle outPersistentState

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState, outPersistentState);
    outState.putString("example",newString);
}

void onSaveInstanceState (Bundle outState, PersistableBundle outPersistentState) this will only get called when you have attribute persistableMode specified in the activity tag inside manifest

您可以阅读更多的 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆