I'm making an app with a counter that rises when I tap an ImageView. That works, but now I want to save the counter to a SharedPreferences Object.
I've tried to initialize the SP Object inside the onCreate method, which obviously doesn't work. When I try to use sp.getInt(...) globally, it doesn't work either. I understand why there is a problem (Trying to get an Integer from a sp object before it gets initialized), but I don't know how to solve it.
public class MainActivity extends AppCompatActivity {
int counterint;
TextView counter;
String stringnumber;
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.hugelon", Context.MODE_PRIVATE);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences.getInt("hugcounter", 0);
}
public void hughim(View view){
counter = findViewById(R.id.countertv);
stringnumber = counter.getText().toString();
counterint = Integer.parseInt(stringnumber);
counterint++;
counter.setText(Integer.toString(counterint));
sharedPreferences.edit().putInt("hugcounter", counterint);
}
}
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hugelon/com.example.hugelon.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference
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
Giovanni's answer is correct, you are just not setting the initial value at oncreate
public class MainActivity extends AppCompatActivity {
int counterint;
TextView counter;
String stringnumber;
SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = findViewById(R.id.countertv);
sharedPreferences = this.getSharedPreferences("com.example.hugelon", Context.MODE_PRIVATE);
stringnumber=String.valueOf(sharedPreferences.getInt("hugcounter", 0));
counter.setText(stringnumber);
}
public void hughim(View view){
counter = findViewById(R.id.countertv);
stringnumber = counter.getText().toString();
counterint = Integer.parseInt(stringnumber);
counterint++;
counter.setText(Integer.toString(counterint));
sharedPreferences.edit().putInt("hugcounter", counterint);
}
}