-1

I am checking all these at splashscreen activity,

So I am giving this,

SharedPreferences spf = getSharedPreferences("myprfs", Context.MODE_PRIVATE);
SharedPreferences.Editor spe = spf.edit();
String name = spf.getString("name","");
String id = spf.getString("id","");
String class = spf.getString("class","");
String roll = spf.getString("roll","");
spe.commit();

 if((spe != null) && (name != null) && (id != null) && (class != null) && (roll != null)){
     Intent i = new Intent(Startpage.this,Welcome.class);
     startActivity(i);
     Startpage.this.finish();

 }
 else{
     Intent i = new Intent(Startpage.this,MainActivity.class);
     startActivity(i);
     Startpage.this.finish();
 }

when I open app startup page directly moves to welcome page,

but I want to move splashscreen page to MainActivity when there is no values saved in shared-preferences

I followed this to get shared-preference values

can any one suggest me how to give condition in this kind

Whats Going On
  • 1,379
  • 6
  • 20
  • 49
ravi
  • 474
  • 1
  • 3
  • 11
  • Possible duplicate of [Condition is not working in sharedpreferences android](https://stackoverflow.com/questions/46661277/condition-is-not-working-in-sharedpreferences-android) – jobbert Oct 16 '17 at 14:28

4 Answers4

2
spf.getString("name","");

return as default value a empty string.

Idea:

why not use

spf.contains("name")

that return true or false? Alternatively you can check if string is empty or null with TextUtils.isEmpty() method.

Alessandro Verona
  • 1,157
  • 9
  • 23
1
String name = spf.getString("name","");

This method creates a shared pref if it doesn't exist already with the default value as the second argument. So in your case, shared pref are saved with empty string as value when user visited the app for first time.

Just change your default value to null since your checks are on null value and it will work -

String name = spf.getString("name",null);
Sachin Aggarwal
  • 1,095
  • 8
  • 17
0

you are putting null check on the string but while reading from the shared preferences you are setting them to empty string if the value is not found in the shared prefs. change your checks to String.isEmpty() in your if condition.

Umar Hussain
  • 3,461
  • 1
  • 16
  • 38
0

because null and ""are different,

You should use android.text.TextUtils.isEmpty(CharSequence str)instead of str != null

Another way is : String name = spf.getString("name",null); ,and then like if (Str != null)

For me,i always usee the first way i said to determine whether String is empty.

Hope it helps you :)

Fairy Tale
  • 19
  • 4