I've made the majority of my game's mechanics, I now need to be able to:
Save all the data of the current activity and retrieve it when coming back (I'd appreciate an example of
SharedPreferences
if that's what I need)Open back the same
Activity
I left from and in the same time I was when I left it.
Just to be clearer: I want not to restart from my Main Activity each time the App gets closed or even killed.
EDIT:
Alright, I've used this Google article in order to save my Activity and recreate it later.
The code in one of my Activities is the following:
onCreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_selection);
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
village = savedInstanceState.getString(VILLAGE);
seekBarProgress = savedInstanceState.getInt(PROGRESS);
} else {
// Probably initialize members with default values for a new instance
initializeVariables();
Bundle bundle = getIntent().getExtras();
village = bundle.getString(VILLAGE);
}
[...] // Other code skipped
}
onSaveInstanceState()
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putString(VILLAGE, village);
savedInstanceState.putInt(PROGRESS, seekBarProgress);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Thus, I've created a Dispatcher Activity (which is now my Main) that when the App is killed and then launched back, knows which is the last opened Activity to launch. But when I try to do that, and it should open (i.e.) the PlayerSelection
Activity, I get a
java.lang.NullPointerException
as it runs this part of code
else {
// Probably initialize members with default values for a new instance
initializeVariables();
Bundle bundle = getIntent().getExtras();
village = bundle.getString(VILLAGE);
}
instead of the previous if
statement it runs the else
.
Dispatcher
This is the Dispatcher Activity which filters which Activity should be launched:
public class Dispatcher extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Class<?> activityClass;
try {
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
activityClass = Class.forName(
prefs.getString("lastActivity", MainActivity.class.getName()));
} catch(ClassNotFoundException ex) {
activityClass = MainActivity.class;
}
startActivity(new Intent(this, activityClass));
}
}
This is what I send to my Dispatcher Activity:
@Override
protected void onPause() {
super.onPause();
SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("lastActivity", getClass().getName());
editor.commit();
}
}
Question
Why does it happen? What can I do to fix this?