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.
 
     
     
    