I thought the error I'm catching is for only the first time running (where there's still no SharedPreferences
saved, but the error pops up everytime I run the app (in MainActivity
):
Attempt to invoke virtual method 'int com.android.test.helper.PreferencesHelper.load(java.lang.String)' on a null object reference
The same function however works and loads the value under that key
(key_foo
) successfully in the OptionsActivity
where that option is saved. MainActivity
runs first when opening the app immediately being replaced by OptionsActivity
after some more setup.
MainActivity.java
:
public class MainActivity {
private PreferencesHelper preferencesHelper;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
preferencesHelper.load("key_foo");
recreate();
}
catch(Exception e) {
Log.d("ERROR", e.getMessage());
}
startOptionsActivity();
}
}
PreferencesHelper.java
:
public class PreferencesHelper {
private Activity context;
private SharedPreferences sharedPref;
private SharedPreferences.Editor editor;
public PreferencesHelper (Activity activity){
context = activity;
sharedPref = context.getSharedPreferences("file", 0);
}
public int load(String key){
sharedPref = context.getSharedPreferences("file", 0);
return sharedPref.getInt(key, -1);
}
public void save(String key, int value){
editor = sharedPref.edit();
editor = putInt(key, value);
editor.apply();
}
}
OptionsActivity.java
:
public class OptionsActivity {
private PreferencesHelper preferencesHelper;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options);
preferencesHelper.save("key_foo", 42);
recreate();
try {
preferencesHelper.load("key_foo");
}
catch(Exception e) {
Log.d("ERROR", e.getMessage());
}
}
}
Attempt to invoke virtual method 'int com.android.test.helper.PreferencesHelper.load(java.lang.String)' on a null object reference
NullPointerException is thrown when program attempts to use an object reference that has the null
value. You must declare PreferencesHelper
in onCreate()
section.
private PreferencesHelper preferencesHelper;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
preferencesHelper = new PreferencesHelper(this);