Basically, I am trying to save and load data with my Android app. It works as intended when pressing the home button, and re-entering the app. Even closing the app for the first time through the app manager, it loads fine with the correct data (just one integer at the moment for test purposes). The second time the app is closed through the app manager, the data is lost, even though it's killed using the same method as the first time. Find below the code dealing with anything saving, loading, and the relevant methods.
Android life cycle methods:
public int setting1 = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
loadData();
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
AdView mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
}
@Override
public void onPause() {
super.onPause();
saveData();
}
@Override
public void onStop() {
super.onStop();
saveData();
}
@Override
public void onDestroy() {
super.onDestroy();
saveData();
}
@Override
public void onResume() {
super.onResume();
loadData();
updateUnlockables(setting1);
}
Save and Load Methods:
public void saveData(){
String filename = "icesSave.asv";
FileOutputStream fos;
try {
fos = openFileOutput(filename, Context.MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeInt(setting1);
oos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadData(){
String filename = "icesSave.asv";
FileInputStream fis;
try{
fis = openFileInput(filename);
} catch (FileNotFoundException ex){
return;
}
try {
ObjectInputStream ois = new ObjectInputStream(fis);
setting1 = ois.readInt();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
}
saveData()
should be above on super
Dont Use saveData()
in all 3 method because its same process
@Override
public void onPause() {
saveData();
super.onPause();
}
@Override
public void onStop() {
saveData();
super.onStop();
}
@Override
public void onDestroy() {
saveData();
super.onDestroy();
}