I have been banging my head on the keyboard for hours. I want to store an incremented integer for a separate stats activity in my app. I am trying to use Shared Preferences to achieve this. However in my latest attempt, which is the furthest I have gotten, the program throws an exception.
My code:
public class LootChest extends AppCompatActivity {
public static final String prefName = "prefsFile";
SharedPreferences settings = getApplicationContext().getSharedPreferences(prefName, 0); //line 25
int rollCountS = settings.getInt("Roll Count", 0);
int rollCount = 0; //to be incremented
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loot_chest);
}
public void openChest(View v) {
SharedPreferences.Editor editor = settings.edit();
editor.putInt("Roll Count", rollCount);
rollCount = rollCountS + 1;
The exception:
Caused by: java.lang.NullPointerException:
Attempt to invoke virtual method
'android.content.SharedPreferences android.content.Context
.getSharedPreferences(java.lang.String, int)'
on a null object reference at android.content.ContextWrapper
.getSharedPreferences(ContextWrapper.java:171)
at net.zingrook.mobiloot.LootChest.<init>(LootChest.java:25)
I've read dozens of threads on implementing this, and looked at the Android documentation and I am out of ideas. Thank you for any help.