Home > Net >  Data is not saved using SharedPreferences
Data is not saved using SharedPreferences

Time:04-24

I have an error with SharedPreferences. My data is not saved when I turn off the app via the active apps menu on my phone. The data is saved only if I close the application via finish Affinity(). Help me fix the error.

    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();
}

}`

CodePudding user response:

You should avoid saving data from your onDestroy method. From the docs on the onDestroy method:

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.

I would move your saveText() to the onPause() method of your activity to resolve it:

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

Also, are you aware you're saving to SharedPrefs every time your activity is created? I'm not sure what you'd like to achieve, but wanted to give you a heads up about it.

  • Related