Answer the question
In order to leave comments, you need to log in
What is a good library for convenient use of shared preferences in Android?
I use sPrefs very often in the project, I would really like this code in one elegant line:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();
Answer the question
In order to leave comments, you need to log in
Make SharedPreferences sharedPref and SharedPreferences.Editor editor class members, e.g. MainActivity, initialize only 1 time, e.g. in onCreate.
That. the amount of code in your example will be reduced from 4 to 2 lines.
I didn’t understand something, but why is there a library at all? All methods that start with 'put...' return an Editor to you, so your code can be boiled down to
getActivity()
.getPreferences(Context.MODE_PRIVATE)
.edit()
.putInt(getString(R.string.saved_high_score), newHighScore)
.commit();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question