public abstract class CartSharedPrefrences {
public static boolean addFavoriteItem(Activity activity,String favoriteItem){
//Get previous favorite items
String favoriteList = getStringFromPreferences(activity,null,"favorites");
// Append new Favorite item
if(favoriteList!=null){
favoriteList = favoriteList+","+favoriteItem;
}else{
favoriteList = favoriteItem;
}
// Save in Shared Preferences
return putStringInPreferences(activity,favoriteList,"favorites");
}
public static String[] getFavoriteList(Activity activity){
String favoriteList = getStringFromPreferences(activity,null,"favorites");
return convertStringToArray(favoriteList);
}
private static boolean putStringInPreferences(Activity activity,String nick,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, nick);
editor.commit();
return true;
}
private static String getStringFromPreferences(Activity activity,String defaultValue,String key){
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
String temp = sharedPreferences.getString(key, defaultValue);
return temp;
}
private static String[] convertStringToArray(String str){
String[] arr =str.split(",");
return arr;
}
}
我已经尝试了上面的解决方案,而调试它会将数据保存到共享 偏好,但当我试图从共享偏好中检索数据时 将返回null,同时将数据添加到它正在检索的共享首选项 用于检查先前是否在共享首选项中可用的任何数据的方法 不是,那个方法它返回数据用于检查目的,但是 从另一个活动调用时,它返回null。谁能帮我? 如何从中获得完美的价值。提前谢谢。
答案 0 :(得分:2)
您使用的是私人模式:
SharedPreferences sharedPreferences = activity.getPreferences(Activity.MODE_PRIVATE);
如果您想在活动之间分享偏好,可以使用:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);