K
K
katavagner2015-05-01 11:39:55
Java
katavagner, 2015-05-01 11:39:55

Is Preferences accessible from another class?

Understanding data storage in Android. There was a problem:
Constants and global variables

SharedPreferences sharePref;
static final String SAVED_ANSWER = "saved_answer";
static final int MAX_ANSWER = 5;

Counter check code:
sharePref = getPreferences(MODE_PRIVATE);
String savedText = sharePref.getString(Config.SAVED_ANSWER, "");
Log.d(TAG, "SAVED_ANSWER равно: " + savedText);
return savedText;

Counter reset code
sharePref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor edit = sharePref.edit();
String savedText = sharePref.getString(Config.SAVED_ANSWER, "");
Log.d(TAG, "Сброс счетчика: он равен - " + savedText);
edit.putString(Config.SAVED_ANSWER, "0");
edit.apply();

Saving and checking the counter in one class, and zeroing in another class.
And here is the log:
D/MyLog﹕ Application started: Day 01 Month 05 Year 2015 Time 04:30
D/MyLog﹕ SAVED_ANSWER is: 5
D/MyLog﹕ Number of replies is: 5, so we link to
D/MyLog topics ﹕ Counter reset: it is - 0
D/MyLog﹕ SAVED_ANSWER is equal to: 5
D/MyLog﹕ The number of answers is: 5, so we are making a link to the topics
Maybe I did not ask the question correctly, tell me, I will add.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Semyon Novikov, 2018-05-26
@semennovikov123

Had the same problem. The classic SharedPreferences is only available in its activity. But getDefaultSharedPreferences can be used throughout the application. You can read more here:

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question