0

i have a problem. I want to restore last fragment opened before close my application and i would like to use SharedPreferences so i put into the onCreateView of each fragment a snippet of code that save a string to shared preferences and in the Main Activity i've this

if(savedIstanceState == null) {
            pref = new SharedPref(this);
            String prefe = pref.getPreString("LastPage");

            if(prefe == "0") {
                fragment = new Fragment0();
            } else if(prefe == "1") {
                fragment = new Fragment1();
            } else if(prefe == "2") {
                fragment = new Fragment2();
            } else {
                fragment = new Fragment3();
            }

            getFragmentManager().beginTransaction().add(R.id.container, fragment).commit();
        }

But return always Fragment3 also if in the preferences there are for example 0. Why?

user3717163
  • 61
  • 2
  • 8

1 Answers1

1

Firstly, dont compare Strings using ==, use equals instead. Secondly I assume you are saving correctly your preferences as you did not show how you store the value.

Hope it helps.

zozelfelfo
  • 3,776
  • 2
  • 21
  • 35
  • Which is the difference between == and equals? to save string data i have this method editor.putString(key, value).commit(); – user3717163 Jun 16 '14 at 10:36
  • When you use ==, you are comparing if both objects are exactly the same (the same instance), using `equals` you are comparing the content (the string itself). This is not 100% true , but your comparison may return false using == even if both Strings have the same value. Check this link. http://stackoverflow.com/questions/2486191/java-string-pool – zozelfelfo Jun 16 '14 at 10:38