活动生命周期存储和恢复

时间:2019-07-08 13:15:05

标签: android

“使用onSavedInstanceState(Bundle)保存所有数据,但是如果我的应用程序已关闭,则重新打开我的应用程序以及如何还原保存的实例”

package com.example.savedandrestored;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
EditText first,last;
Button submit;
@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    first=findViewById(R.id.firstname);
    last=findViewById(R.id.lastname);
    submit=findViewById(R.id.submit);
    if(savedInstanceState!=null && savedInstanceState.containsKey("firstName") && savedInstanceState.containsKey("lastName")) {
        first.setText(savedInstanceState.get("firstName").toString());
        last.setText(savedInstanceState.get("lastName").toString());
    }
    submit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
 savedInstanceState.putString("firstName",first.getText().toString());
   savedInstanceState.putString("lastName",last.getText().toString());
            onSaveInstanceState(savedInstanceState);
        }
    });
    }
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState){
        super.onSaveInstanceState(savedInstanceState);
     }
}

“当我打开应用程序并且没有执行任何新数据时,它不会还原数据”

1 个答案:

答案 0 :(得分:1)

onSaveInstanceState用于其他目的,例如在轮播中重新创建活动等。

  

使用onSavedInstanceState(Bundle)保存所有数据,但是如果我的应用程序   关闭,然后重新打开我的应用程序

然后,您应该阅读lifecycle of an activity

但是您问题的简短答案是

  1. 将数据保存在onPause
  2. 获取onResume

例如

import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //retrieve your data here and update UI here not onCreate 

    }

    @Override
    protected void onPause() {
        super.onPause();

        //Save your data here into shared prefs, or file, or DB (*last not recommended)
    }
}