不使用 SharedPreferences 保存数据

Data is not saved using SharedPreferences

我的 SharedPreferences 有误。当我通过 phone 上的活动应用程序菜单关闭应用程序时,我的数据没有保存。仅当我通过 finish Affinity() 关闭应用程序时才会保存数据。帮我修正错误。

    public class Progress extends AppCompatActivity {
    public static float progress;
    float progr;
    float sum_progr;
    String t_progress;
    public TextView etText;
    ProgressBar progressBar;
    SharedPreferences sPref;

@SuppressLint({"CutPasteId", "SetTextI18n"})
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_progress);
    etText = findViewById(R.id.text_Progress);
    t_progress=etText.getText().toString();
    progr=Float.parseFloat(t_progress);
    sum_progr=progr+progress;
    etText.setText(sum_progr+"%"); //Установили текст
    progressBar = findViewById(R.id.progressBar);
    progressBar.setProgress((int) sum_progr);
    saveText();
    loadText();
}
public void onHome(View view) {
    Intent intent=new Intent(Progress.this, MainActivity.class);
    startActivity(intent);
}
private void saveText() {
    sPref = getSharedPreferences("PROGRESS", MODE_PRIVATE);
    SharedPreferences.Editor ed = sPref.edit();
    ed.putFloat("SAVED_TEXT", sum_progr);
    ed.apply();
    Toast.makeText(Progress.this, "Text saved", Toast.LENGTH_SHORT).show();
}
@SuppressLint("SetTextI18n")
private void loadText() {
    sPref = getSharedPreferences("PROGRESS", MODE_PRIVATE);
    Float savedText = sPref.getFloat("SAVED_TEXT",0);
    etText.setText(savedText+"%");
    Toast.makeText(Progress.this, "Text loaded", Toast.LENGTH_SHORT).show();
}
@Override
protected void onDestroy() {
    super.onDestroy();
    saveText();
}

}`

您应该避免通过 onDestroy 方法保存数据。来自 onDestroy 方法的 docs

Note: do not count on this method being called as a place for saving data! For example, if an activity is editing data in a content provider, those edits should be committed in either onPause() or onSaveInstanceState(Bundle), not here.

我会将您的 saveText() 移动到您 activity 的 onPause() 方法来解决它:

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

此外,您知道每次创建 activity 时都会保存到 SharedPrefs 吗?我不确定你想要达到什么目的,但想提醒你一下。