如何检测Android中是否存在Preference

时间:2014-05-09 11:50:11

标签: android sharedpreferences

我创建了一个Android应用程序,因为我想检查首选项是否存在。

我的代码是:

public static boolean checkPref(Context context, String name)
{   
    SharedPreference sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    String uid = sharedPreferences.getString(name, "n/a");

    if(uid!= null && !uid.equals(""))
    {   
        return true;
    }
    else
    {
        return false;
    }               
}

2 个答案:

答案 0 :(得分:1)

使用类似

的内容
public static boolean checkPref(Context context, String name)
{   
    SharedPreference sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
    return sharedPreferences.contains(name);             
}

答案 1 :(得分:0)

如果不存在sharedPreference,则会抛出NullPointerException,因此我建议您像这样管理代码:

try
{
   //handle the situation where there exists the shared preference
}

catch(NullPointerException exc)
{
    //handle the situation of non-existent sharedpreference 
}