The question is, like, banal, but how to write an ordinary cache line so that when you re-enter the application, the data is taken from there?

There is such code:

public static SharedPreferences readRules; private String s; @Override protected void onCreate(Bundle savedInstanceState) { readRules = getPreferences(MODE_PRIVATE); if(readRules.getString("readRules", "").equals("true")){ Intent intent = new Intent(getApplicationContext(), MainPageNavigation.class); startActivity(intent); }else{ Intent intent = new Intent(getApplicationContext(), Rules.class); startActivity(intent); } super.onCreate(savedInstanceState); } 

Initially, readRulse nothing in the readRulse , go to MainPageNavigation , there is a record when you press the button:

 btnOk.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sPref = getPreferences(MODE_PRIVATE); SharedPreferences.Editor ed = sPref.edit(); ed.putString(readRules, "true"); ed.commit(); readRules = sPref.getString("readRules", ""); Intent intent = new Intent(getApplicationContext(), MainPageNavigation.class); startActivity(intent); } }); 

When reopened, the application does not find the readRules variable.

  • one
    there are not enough quotes around readRules - ed.putString(readRules, "true"); -> ed.putString("readRules", "true"); - pavlofff
  • That didn't help ... - Heaven

1 answer 1

The getPreferences(...) method returns the SharedPreferences level SharedPreferences .

You want to access the same SharedPreferences from different activations, for this you need to use SharedPreferences -level SharedPreferences :

 SharedPreferences getSharedPreferences (String name, int mode) 

where name is the name of the settings file, in both activations it should be the same.

For keys, it is better to use constants, and a boolean value is better and saved as putBoolean(...) .

And yes, as @pavlofff suggests , you forgot the quotes in the string:

 ed.putString(readRules, "true"); 

It is for this reason that it is better to use constants as keys.