I've been experimenting for a couple of hours now on how to save the progress of a progressBar even if I closed/destroyed the app. I tried using the same method in TextViews and it works just fine. So, I'm wondering where I went wrong. Below is my code that I've done and any response is greatly appreciated! Have a nice day!
public class MainActivity extends AppCompatActivity {
public static final String PROGRESS = "progress";
private int CurrentProgress;
private ProgressBar progressBar;
private Button addProgress;
public static final String SHARED_PREFS="sharedPrefs";
private int getCurrentProgress;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = findViewById(R.id.progressBar);
addProgress = findViewById(R.id.addProgress);
progressBar.setMax(1000);
addProgress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CurrentProgress = CurrentProgress + 100;
progressBar.setProgress(CurrentProgress);
saveData();
}
});
loadData();
updateData();
}
public void saveData(){
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PROGRESS, CurrentProgress);
editor.apply();
}
public void loadData() {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
getCurrentProgress = sharedPreferences.getInt(PROGRESS, CurrentProgress);
}
public void updateData() {
progressBar.setProgress(CurrentProgress);
}
}