Issue
I'm developing an Android app which uses a high amout of SharedPreferences. I have several SharedPreferences files and I'm making up to 77 calls to these files throughout my app. Sometimes I'm using :
static final String FileName= "SharedPreferencesFile";
at the beginning of my activities and then :
SharedPreferences settings = getSharedPreferences(FileName, Context.MODE_PRIVATE);
whenever I need to use them. Some other times I'm just refering to the files directly as in:
SharedPreferences settings = getSharedPreferences("SharedPreferencesFile", Context.MODE_PRIVATE);
I'm trying to organize things now so I would like to know about different alternatives to do it. My questions are:
- Should I define a single "SharedPreferencesFile" for all the variables in my app or using multiple files as I'm doing now is ok?
- Should I define all these
String FileName= "SharedPreferencesFile"
in thestrings.xml
from my app resources folder instead of putting them at the beginning of my activities and the just use them asSharedPreferences settings = getSharedPreferences(R.string.SharedPreferencesFile, Context.MODE_PRIVATE);
- Should I create a helper class that handles all shared preferences calls for every activity as suggested in Android Shared Preferences
Solution
Should I define a single "SharedPreferencesFile" for all the variables in my app or using multiple files as I'm doing now is ok?
If you can categorize them in a logical fashion do it. Dont just do it for the sake of having them split over multiple files in a random fashion. It will lead to a lot of confusion later
Should I define all these String FileName= "SharedPreferencesFile" in the strings.xml from my app resources folder instead of putting them at the beginning of my activities and the just use them as SharedPreferences settings = getSharedPreferences(R.string.SharedPreferencesFile, Context.MODE_PRIVATE);
It is always good to have string resources extracted to strings.xml
. Be careful if you are adding translations and make sure you don't translate the names. Mark them as notranslate
string resources.
Should I create a helper class that handles all shared preferences calls for every activity as suggested in Android Shared Preferences
There are already several available. Here is one that I created to simplify the use of SharedPreferences
. It is open source and can be used simply by adding a gradle dependency - Android-SharedPreferences-Helper
Answered By - Viral Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.