My SharedPref.java
is as follows:
public class SharedPref { private static final String PREF_NAME = "Wallet"; private static SharedPref instance; private SharedPreferences preferences; public static SharedPref getInstance() { return instance; } public static void init(Context context) { instance = new SharedPref(context); } private SharedPref(Context context) { preferences = context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE); } public void saveOAuthResponse(OAuthTokensResponse response) { preferences.edit() .putString("access", response.getAccessToken()) .apply(); preferences.edit() .putString("refresh", response.getRefreshToken()) .apply(); } public String getAccessToken() { return preferences.getString("access", null); } public String getRefreshToken() { return preferences.getString("refresh", null); } public void clearTokens() { preferences.edit() .putString("access", null) .apply(); preferences.edit() .putString("refresh", null) .apply(); } }
I am trying to access it through an activity with this line of code:
String token = SharedPref.getInstance().getAccessToken();
and I’m getting the following error:
java.lang.NullPointerException: Attempt to invoke virtual method ‘java.lang.String com.coin.coinsway.SharedPref.getAccessToken()’ on a null object reference
How can I solve this problem?
Advertisement
Answer
SharedPref.instance is null, because it hasn’t been initialised. You can initialise it in your MainActivity’s onCreate method like this:
@Override public void onCreate(Bundle savedInstanceState) { // ... SharedPref.init(this); // ... }
(In case you want to access SharedPref.getInstance() in onCreate, make sure you initialise it before trying to access it)