问题
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
回答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);
回答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.
回答3:
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.
回答4:
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 :)
来源:https://stackoverflow.com/questions/45834331/how-to-valid-sharedpreference-value-in-android