我正在尝试使用共享首选项将值从一个活动传递到另一个活动,但是我获得了null值。在第一个活动中,我在控制台中打印了值并将其打印但是我无法检索这些值。请帮我解决这个错误
第一项活动:传递值
sharedpreferences.edit().putString("CHECKPASS","changepass").commit();
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
第二项活动:我正在检索的地方
Log.d("succ", "reached");
String yourpass = sharedpreferences.getString("CHECKPASS","changepass");
Log.d("succ", "yournext" + yourpass);
if (yourpass.equals("changepass")) {
{
final String foodshared = sharedpreferences.getString("FOOD","NULL");
Log.d("succ", "foodshared" + foodshared);
final String colorshared = sharedpreferences.getString("COLOR", "NULL");
Log.d("succ", "colorshared" + colorshared);
final String buyshared = sharedpreferences.getString("BUY", "NULL");
Log.d("succ", "buyshared" + buyshared);
final String placeshared = sharedpreferences.getString("PLACE", "NULL");
Log.d("succ", "placeshared" + placeshared);
}
答案 0 :(得分:1)
使用此代码
//用于写入数据
SharedPreferences.Editor
editor=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE).edit();
editor.putString("CHECKPASS","changepass");
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.apply();
//读取数据
SharedPreferences sharedPreferences=getSharedPreferences("nameOFSharedPref",MODE_PRIVATE);
String foodshared = sharedPreferences.getString("FOOD","NULL");
String colorshared = sharedPreferences.getString("COLOR", "NULL");
final String buyshared = sharedPreferences.getString("BUY", "NULL");
final String placeshared = sharedPreferences.getString("PLACE", "NULL");
同样在编写数据时不要使用editor.commit()而是使用editor.apply(),因为它在后台处理数据。
答案 1 :(得分:0)
更新:
在您的第一个活动中
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);//or MODE_PRIVATE
Editor editor = pref.edit();
editor.putString("CHECKPASS","changepass")
editor.putString("FOOD",food1);
editor.putString("PLACE",place1);
editor.putString("COLOR",colour1);
editor.putString("BUY",buy1);
editor.commit();
在你的secondActivity中
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
final String foodshared = pref.getString("FOOD",null);
Log.d("succ", "foodshared" + foodshared);
final String colorshared = pref.getString("COLOR",null);
Log.d("succ", "colorshared" + colorshared);
final String buyshared = pref.getString("BUY",null);
Log.d("succ", "buyshared" + buyshared);
final String placeshared = pref.getString("PLACE",null);
Log.d("succ", "placeshared" + placeshared);
修改强>:
初始化
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
存储数据
editor.putBoolean("key_name", true); // Storing boolean - true/false
editor.putString("key_name", "string value"); // Storing string
editor.commit(); // commit changes
检索数据
pref.getString("key_name", null); // getting String
pref.getBoolean("key_name", null); // getting boolean