Creating a common Shared Preference class in android and using that class to fetch and set data from across all the modules in the project, Please share (.java) files and give a brief on it and also explain the flow like, how to call shared preference common class, how to set data and how to retrieve data. Thanks in advance 🙂
What currently I am following is written below:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE).edit();
editor.putString("name", "Elena");
editor.putInt("idName", 12);
editor.apply();
// For fetching data from preference)
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME,
MODE_PRIVATE);
String name = prefs.getString("name", "No name defined");//"No name
defined" is the default value.
int idName = prefs.getInt("idName", 0); //0 is the default value.
”””””””””””””””””””””’
2
Answers
Posting my answer here, this answer helped me, hope this would be helpful for you guys as well Thanks :)
Fetching & Putting data in preference:
Create a singleton class the initializes one instance from context like so:
and you can set values by calling put and get on mEditor, for example: