【发布时间】:2016-05-12 08:26:10
【问题描述】:
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。谁能帮我? 如何从中获得完美的价值。提前致谢。
【问题讨论】:
-
but while calling from another activity it is returning null.... public SharedPreferences getPreferences (int mode) 在 API 级别 1 中添加 检索 SharedPreferences 对象以访问 此活动专用的首选项。 -
我尝试了stackoverflow.com/a/9054246/5324829 解决方案,但它返回 null
标签: android null sharedpreferences