1

i set a shared preference variable:

SharedPreferences SPrefs;
SPrefs.edit().putString("SomeStringVariable", "sometext").commit();

and then i retrieve it:

String test1 = SPrefs.getString("SomeStringVariable", "Empty");

then compare it:

if(test1 == "sometext")
Toast.makeText(Main_Activity.this, test1, Toast.LENGTH_LONG).show();

Toast not works , it means test1 != "sometext" but if i remove "if" statement:

Toast.makeText(Main_Activity.this, test1, Toast.LENGTH_LONG).show();

Toast Works and "sometext" appears in emulator!

why this Occur?

Infinite Recursion
  • 6,511
  • 28
  • 39
  • 51
Behnam Maboudi
  • 655
  • 5
  • 21

3 Answers3

2

You should use

 if(test1.equals("sometext"))

use .equals or .equalsIgnoreCase to compare strings because == checks fro reference equality.

Reference :

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#equals(java.lang.Object)

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

Try using

if(test1.equals("sometext")){
  //Toast goes here
}
Alberto Zaccagni
  • 30,779
  • 11
  • 72
  • 106
Deepak Senapati
  • 1,103
  • 2
  • 11
  • 30
0

You are comparing string so you should use .equals not ==

So as Raghunandan said you should use

if(test1.equals("sometext")) instead of 
if(test1 == "sometext")  replace this line with above and you are done.
InnocentKiller
  • 5,234
  • 7
  • 36
  • 84