I have written an application that keeps erasing my shared preference. It was always my understanding that the when you use SharedPreferences, they persist until you uninstall the application or clear the preferences programatically (I could be wrong). What is happening is that I have the string value of a sharedpreference in one file. That value is then called for in a separate file which runs an if statement and sets an imageview to a specific graphic if that variable has been stored. It seems to run great and everything works like it is supposed to until I close the application and kill it within the phones settings or use the “Advanced Task Killer” application. I have programmed other applications using the shared preferences the same way (not using the if statement) and I don’t seem to have this problem, so this makes me think that there is an issue with the if statement. Logically, I cannot figure out what is going wrong. Any help is much appreciated. File one code:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.guessaquaman);
final Button guessbutton = (Button) findViewById(R.id.guess_button);
guessbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
guess=(EditText)findViewById(R.id.guess_edittext);
String myguess = guess.getText().toString();
String correctanswer = "aquaman";
if( myguess.equals( correctanswer ) ){
Toast.makeText(getApplicationContext(), "Correct", Toast.LENGTH_SHORT).show();
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("aquamanticked", "on");
editor.commit();
Intent myintent1 = new Intent(AquamanGuess.this,PlayActivity.class);
startActivity(myintent1);
guessbutton.setEnabled(false);
}
}
});
And the second file:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
SharedPreferences sharedPreferences = getSharedPreferences("MY_SHARED_PREF", MODE_PRIVATE);
String aquamanticker = sharedPreferences.getString("aquamanticked", "");
String aman= "on";
ImageView aquaman = (ImageView) findViewById(R.id.aquaman);
aquaman.setImageResource(R.drawable.aquaman_small_empty);
if (aquamanticker == aman ){
aquaman.setImageResource(R.drawable.aquaman_small_filled); }
That line in the second file looks bad!
Try it this way:
The reason:
You are comparing two
Stringobjects calledaquamantickerandamaninstead of comparing the contents of what theStringvariable holds.