Tryam Tryam - 2 months ago 10
Android Question

Error with SharedPreferences in two activities

I have two activities and I need to get access to

SharedPreferences
from any of them. I try in my MainActivity OnCreate:

SharedPreferences prefs = getApplicationContext().getSharedPreferences("shkatovl.btandroid", MODE_PRIVATE);
if(!prefs.contains("CMD1")){
prefs.edit().putString("CMD1", "").apply();
}


And in another activity:

SharedPreferences prefs = getApplicationContext().getSharedPreferences("shkatovl.btandroid", MODE_PRIVATE);


And I have an error on the last string. What's the problem and how to solve it?

Answer

MODE_PRIVATE is member of Context. Depending on where you use it, you must prefix it with its class name, e.g.

...getSharedPreferences("shkatovl.btandroid", Context.MODE_PRIVATE);
Comments