我在我的应用中使用了sharedPrefrence,但未返回任何值 这是代码:
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private Context context;
SharedPreferences sp;
public SharedPrefManager(Context context){
this.context = context;
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("username", username);
editor.putInt("numberRow",numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString("username","");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}
但是当调用方法getUsename()
返回“”而不返回值
这是被调用方法的地方: enter image description here
答案 0 :(得分:0)
答案 1 :(得分:0)
代码的关键部分是这样的:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
该行代码应为:
SharedPreferences.Editor editor = sp.edit();
一旦在类构造函数中获得SharedPreferences
对象,就应该使用它来创建编辑器。
public class SharedPrefManager {
public final String MY_PREFS_NAME = "name";
private final String MY_PREFS_USERNAME = "username";
private final String MY_PREFS_NUMBER_ROW = "numberRow";
SharedPreferences sp;
public SharedPrefManager(Context context){
sp = context.getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
Log.d(TAG, "database is created");
}
public void saveInfoUser(String username ,int numRow){
SharedPreferences.Editor editor = sp.edit();
editor.putString(MY_PREFS_USERNAME , username);
editor.putInt(MY_PREFS_NUMBER_ROW ,numRow);
editor.commit();
}
public String getUsename(){
String username = sp.getString(MY_PREFS_USERNAME ,"");
return username;
}
public void logout(){
sp.edit().clear().commit();
}
}