Question

I don't understand what's going on here. I have a ListPreference with the entries and entryValues correctly set.

When I go in the prefernces activity and change the value it successfully works (I added a Toast to output the value after changing the option to test).

But when I do the following to compare it, it always executes the else statment when I change it everytime, even like above when I changed the ListPreference and the value was "bluesky" it still failed to execute the correct if statement.

Here's the code I use to check the value of the ListPreference in the onResume():

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this)
String backgroundPref = prefs.getString("backgroundPref", "");

  if(backgroundPref == "bluesky"){
    mainLayout.setBackgroundResource(R.drawable.bluesky); 
    Toast.makeText(getBaseContext(), "Blue Sky", Toast.LENGTH_SHORT).show();
  }else if(backgroundPref == "sky"){
    mainLayout.setBackgroundResource(R.drawable.sky);   
    Toast.makeText(getBaseContext(), "Sky", Toast.LENGTH_SHORT).show();
  }else{
    mainLayout.setBackgroundResource(R.drawable.sunsetscene);
    Toast.makeText(getBaseContext(), "Sunset Scene", Toast.LENGTH_SHORT).show();
  }

The Toasts are there so I can double check which statement gets executed, and it always seems to be the else one.

Am I having a bad day and getting something wrong?

Was it helpful?

Solution

For starters never compare Strings like this backgroundPref == "bluesky" should be backgroundPref.equals("bluesky");

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top