Java – if you reopen the application, SharedPreferences is not saved
My sharing preferences will not be saved. If I reopen my game and the previously saved SharedPreferences data is not loaded, my current active settings will return to normal or default again
This is menu Image of my button in class
This is my menu Class
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.menu); SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putInt("Lifes",6); editor.putInt("Hints",6); editor.putInt("Level",1); editor.commit(); f1=(Button)findViewById(R.id.f1); f2=(Button)findViewById(R.id.f2); f2lock=(ImageView)findViewById(R.id.f2lock); f1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ // TODO Auto-generated method stub Intent i =new Intent(menu.this,levelone.class); startActivity(i); } }); f2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v){ // TODO Auto-generated method stub Intent i =new Intent(menu.this,leveltwo.class); startActivity(i); } }); f3=(Button)findViewById(R.id.f3); f3lock=(ImageView)findViewById(R.id.f3lock); } public void onResume() { super.onResume(); SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); levelunlocked = pref.getInt("Level",0); if(levelunlocked == 2) { f2.setVisibility(View.VISIBLE); f2lock.setVisibility(View.GONE); } if(levelunlocked == 3) { f3.setVisibility(View.VISIBLE); f3lock.setVisibility(View.GONE); } SharedPreferences.Editor editor = pref.edit(); editor.putInt("Level",levelunlocked); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.splashscreen,menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button,so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
I'm at LevelOne There is this code in class to get from menu Class gets the default value
int gamelifes,gamehints,gamelevel,index=0; SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); gamelifes = pref.getInt("Lifes",0); gamehints = pref.getInt("Hints",0); gamelevel = pref.getInt("Level",0); //the value from sharedpreferences is use to be a text by use code below lifes1 =(TextView)findViewById(R.id.lifestext1); lifes1.setTextColor(Color.RED); lifes1.setText(String.valueOf(gamelifes)); hints1 =(TextView)findViewById(R.id.hintstext1); hints1.setTextColor(Color.GRAY); hints1.setText(String.valueOf(gamehints));
And save sharing preferences with new data
String answer=edittextanswer1.getText().toString(); if(answer.equalsIgnoreCase(answer1[index])) { gameleveL++; image.setVisibility(View.GONE); finishbutton.setVisibility(View.VISIBLE); SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putInt("Lifes",gamelifes); editor.putInt("Hints",gamehints); editor.putInt("Level",gamelevel); editor.commit(); else { tryagain1.setVisibility(View.VISIBLE); gamelifes--; lifes1.setText(String.valueOf(gamelifes)); }
Then, if you click the finish button, it will look like this
finishbutton.setOnClickListener(new View.OnClickListener() { public void onClick(View v){ finish(); } });
So LevelOne Class completes and returns to menu class
And SharedPreferences code works normally, my menu Each button in class works with the code and is visible!
But if I quit the application, it will return to normal again
Does anyone have a solution to my problem?
Solution
In fact, in your oncreate() method, you always reset the sharing preferences here:
SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); SharedPreferences.Editor editor = pref.edit(); editor.putInt("Lifes",6); editor.putInt("Hints",6); editor.putInt("Level",1); editor.commit();
Just use the if statement to check if the file already exists before the line That should be enough
It's like:
if (pref.contains("Level")) { // Do not reset } else { // Create the prefs SharedPreferences.Editor editor = pref.edit(); editor.putInt("Lifes",1); editor.commit(); }
You don't have to check the exact fields, this is just an example Adjust according to your needs and game logic
Check the activity lifecycle to see why this happens
The oncreate () method is called every time the application is opened, so prefs. Is reset before reading
More about lifecycle here
Editor: the following snnipet shows a way to solve the problem
public static final String PREF_LIFES = "Lifes"; public static final String PREF_HINTS = "Hints"; public static final String PREF_LEVEL = "Level"; public static final String PREF_IS_SET = "isSet"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); this.requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.menu); SharedPreferences pref = getSharedPreferences("SavedGame",MODE_PRIVATE); // Check wether the pref is set or not. if (pref.getBoolean(PREF_IS_SET.false)) { // The prefs is set. Do some game logic here. Like checking for lifes. if (pref.getInt(PREF_LIFES,0) == 0) { // Player is "dead",reset it. resetPrefs(pref); } else { // Player is alive,do whatever you want,or do nothing at all. } } else { // if it's not set,just create it. resetPrefs(pref); } // ... } private void resetPrefs(SharedPreferences pref) { SharedPreferences.Editor editor = pref.edit(); editor.putInt(PREF_LIFES,6); editor.putInt(PREF_HINTS,6); editor.putInt(PREF_LEVEL,1); editor.putBoolean(PREF_IS_SET,true); editor.commit(); }
Edit 2: you can also put this logic on the onresume () method, as long as you delete it from oncreate (), otherwise you will check these conditions twice;)