-2

I want to access a single shared preference file from multiple activities. I came across this similar question which has a well explained answer suggesting to create a helper class for this purpose. And so I followed.. Here's my code:-

1  //helper class
2  public class AppUserInfo {
3  public static final String KEY_PREF_USERNAME = "username";
3  public static final String APP_USER_INFO =
4  AppUserInfo.class.getSimpleName();
5  private SharedPreferences _sharedPrefs;
6  private SharedPreferences.Editor _prefEditor;
7
8  public AppUserInfo(Context context) {
9  this._sharedPrefs = context.getSharedPreferences(APP_USER_INFO,Activity.MODE_PRIVATE);
10 this._prefEditor = _sharedPrefs.edit();
11 }
12
13 public String getUsername() {
14   return _prefEditor.getString(KEY_PREF_USERNAME, "");
15 }
16
17}

However, while defining the getUsername() method, the IDE (Android Studio) points out the error below:-

Cannot resolve method 'getString(java.lang.String,java.lang.String)

(Also tried to achieve a solution without the helper class. And the result..)

I would get the same error when, after having created the user_info shared preference file in Activity A and storing the key-value pair {username : username@example.com} in it, I was trying to do this in Activity B:-

SharedPreferences _userInfo = getSharedPreferences("user_info", Context.MODE_PRIVATE);
SharedPreferences.Editor _prefEditor = _userInfo.edit();

String username = _prefEditor.getString("username","");

How do I resolve this error? I'm also open to different approaches if any.

Community
  • 1
  • 1
Syed Adil
  • 3
  • 1
  • 5

2 Answers2

0

SharedPreferences.Editor doesn't contains getter methods. It has methods that changes your preferences like - putString(), remove(), etc. If you want to get the values corresponding to a key in your preferences file use -

 public String getUsername() {
   return this._sharedPrefs.getString(KEY_PREF_USERNAME, "");
}
Shadab Ansari
  • 7,022
  • 2
  • 27
  • 45
0

You are confusing two things

private SharedPreferences _sharedPrefs;
private SharedPreferences.Editor _prefEditor;

Here, _sharedPrefs is going to be the object you read from, and _prefEditor is going to be the object you write to.

Your methods should read

public String getUsername() {

    // the read object
    return _sharedPrefs.getString(KEY_PREF_USERNAME, "");
}

public void setUsername(String s) {

    // the write object
    _prefEditor.putString(KEY_PREF_USERNAME, s);
    _prefEditor.commit()
}

When editing values in the editor object, be sure to call commit on it afterwards to push those changes back into the readable object.

Matt Clark
  • 27,671
  • 19
  • 68
  • 123