Good day. It is required to maintain a certain value after the completion of the application and further load it, for example, a record or number of points. Unity
has a great PlayerPrefs
tool (saves a key-value pair). Is there something similar in Android Studio? Or maybe some kind of? Thank.
- sharedpreferences - iFr0z
|
1 answer
Write to general settings
To write to the general settings file, create a SharedPreferences.Editor
object by calling edit()
in SharedPreferences
.
Pass the keys and values you want to write using methods such as putInt()
and putString()
. Then call commit()
to save the changes. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt(getString(R.string.saved_high_score), newHighScore); editor.commit();
Read from general settings
To get the values from the common settings file, call methods such as getInt()
and getString()
, providing the key for the value you need, as well as, if desired, the default value that will be displayed when there is no key. For example:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE); int defaultValue = getResources().getInteger(R.string.saved_high_score_default); long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);
|