如何检测android中是否存在偏好

如何检测android中是否存在偏好,android,sharedpreferences,Android,Sharedpreferences,我已经创建了一个android应用程序,我想检查偏好是否存在 我的代码是: public static boolean checkPref(Context context, String name) { SharedPreference sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); String uid = sharedPreferences.getString(nam

我已经创建了一个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;
    }               
}
使用类似

public static boolean checkPref(Context context, String name) { SharedPreference sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); return sharedPreferences.contains(name); } 公共静态布尔checkPref(上下文、字符串名称) { SharedReference SharedReferences=PreferenceManager.GetDefaultSharedReferences(上下文); 返回SharedReferences.contains(名称); }
如果SharedReference不存在,将抛出NullPointerException,因此我建议您像这样管理代码:

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

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

它总是返回false。它会工作的。文件上说: