How we can check whether the data exists in the SharedPreferences.if exists then start new activity?
我们如何检查SharedPreferences.if中是否存在数据,然后启动新活动?
4 个解决方案
#1
5
SharedPreferences prefs = getSharedPreferences("application_settings", 0);
int id = prefs.getInt("id", 0);
if(id > 0) {
startActivity(new Intent(CurrentCLass.this, NextClass.class));
}
#2
1
Whenever you retrieve the data, you always need to supply a default parameter to return if the data doesn't exist, so for example
每当您检索数据时,如果数据不存在,您总是需要提供一个默认参数来返回,例如
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
int data = pref.getInt("key",-1);
then data
will be -1
if the preference value for "key" doesn't exist.
如果“key”的首选项值不存在,则数据将为-1。
#3
1
if (preferences.contains("yourKey")){
startActivity(new Intent(CurrentActivity.this, NewActivity.class));
}
#4
1
A simple Solution. Get Data From Shared Preference. If Data Not Found Then It Returns null
So Check if String Variable get null or any other Value.
简单的解决方案。从共享首选项中获取数据。如果找不到数据则返回null所以检查字符串变量是否为null或任何其他值。
File f = new File("/data/data/" + getPackageName() + "/shared_prefs/mypref.xml");
if(f.exists())
{
String user=mypref.getString("UserName", null);
if(user!=null){
//do stuff`enter code here
}
}
#1
5
SharedPreferences prefs = getSharedPreferences("application_settings", 0);
int id = prefs.getInt("id", 0);
if(id > 0) {
startActivity(new Intent(CurrentCLass.this, NextClass.class));
}
#2
1
Whenever you retrieve the data, you always need to supply a default parameter to return if the data doesn't exist, so for example
每当您检索数据时,如果数据不存在,您总是需要提供一个默认参数来返回,例如
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getContext());
int data = pref.getInt("key",-1);
then data
will be -1
if the preference value for "key" doesn't exist.
如果“key”的首选项值不存在,则数据将为-1。
#3
1
if (preferences.contains("yourKey")){
startActivity(new Intent(CurrentActivity.this, NewActivity.class));
}
#4
1
A simple Solution. Get Data From Shared Preference. If Data Not Found Then It Returns null
So Check if String Variable get null or any other Value.
简单的解决方案。从共享首选项中获取数据。如果找不到数据则返回null所以检查字符串变量是否为null或任何其他值。
File f = new File("/data/data/" + getPackageName() + "/shared_prefs/mypref.xml");
if(f.exists())
{
String user=mypref.getString("UserName", null);
if(user!=null){
//do stuff`enter code here
}
}