Android - Is it bad practice to have multiple Shared Preferences? - java

I have an app making use of SharedPreferences. One just stores app version to check against update for a changelog, the other contains some layout info that clear() gets called on as the user chooses. I finally managed to get a PreferenceFragment working and noticed a trend, so I thought I might ask this now before i go preference crazy (though I think I have enough).
I've done my best to search and see no specific mention of a problem, only that it's possible to have multiples.
I'm a little concerned about PreferenceManager.getDefaultSharedPreferences() grabbing the wrong pref, but I might simply be misunderstanding the usage.
The only relevant code i could think of from my activity:
SharedPreferences storedVer = getSharedPreferences(VER_NUM, 0);
SharedPreferences savedLayout = getSharedPreferences(LAYOUT_SAVE, 0);

It is not bad practice at all. I think it is the opposite. I think different behaviours should use different sharedPreference files.
.getDefaultSharedPreferences() uses the default com.company.packagename.xml file. And the others create their own files.
The followings advantages of using multiple sharedPreference's come up in my mind.
When you use BackupManager, you can provide which sharedPreference files to backup and restore.
When the user logout, you can delete sharedPreference file with that users private values in it. You may not want to delete some other.

From my experience with the SharedPreferences I have noticed the following:
1) Always use try to make your SharedPreference name and Attributes name unique all over the device.
2) Do not use the name of your SharedPreference like "myPreference", "preference", "appPreference"...etc. Use your PackageName as a unique identifier for the SharedPreference name.
Example:
SharedPreferences preferences = getSharedPreferences(Context.getPackageName(), Context.MODE_PRIVATE);
3) Use also a unique Keys for your attributes by concatenating the attribute name with the package name.
Example:
Editor editor = sharedpreferences.edit();
boolean isAdminKey = Context.getPackageName()+"admin";
editor.putString(isAdminKey , "value");
editor.commit();
4) No problem with editing multiple Keys values with one commit().
5) Use MODE_PRIVATE when you create your preferences to prevent other applications from reading your SharedPreferences. See step 2 for example
6) Do not rely on the SharedPreferences 100% because it will be cleared if the user pressed Clear Data button from the App info screen. Otherwise, create file in the ExternalDirectory() or send your info to a server.

Late to the party but I would say do not use multiple preferences. Stick with getDefaultSharedPreferences. I have seen many fail to keep track of the names of the saved preferences. In general it makes the code more complicated in just the wrong way (the compiler can't help you manage your names). Moreover shared preferences are for a handful of small values - use the Filesystem for big things and a database for a lot of data.
I have seen the named shared preferences be used a lot and I believe this is an unfortunate trend spread by copyPaste().
Finally, your preference activities write to the default shared preferences - I have recently answered a question where this was the issue - would be completely avoided if default preferences were used. See: Android SharedPreferences not changing
You might consider wrapping the default shared preferences methods to make them even less verbose as I've done here

Related

What is the best way to share data throughout all activites?

So all of my activities will need the current location of the device, as well as a set of data retrieved through a Http request. I was wondering what is the best way to find this information once, and share it across all my activities?
To pass (or persist) data between application's activities, you can either use:
SharedPreferences:
Shared Preferences allows activities and applications to keep preferences, in the form of key-value pairs similar to a Map that will persist even when the user closes the application.
Android stores Shared Preferences settings as XML file in shared_prefs folder under DATA/data/{application package} directory. The DATA folder can be obtained by calling Environment.getDataDirectory().
Link to SharedPreferences example tutorial.
Intent.putExtra(...)
Whenever you need data from an activity to be in another activity, you can pass data between then while starting the activities. Intents in android offer this convenient way to pass data between activities using Extras.
Link to Intent pass data through extras tutorial.
You can use shared preferences to save data for Android. And get preferences when you want it.
Find your scenario:
If you are going to use a very small amount of data like name, phone
no, or some value, which you want to store even if the app is closed, then use shared preference.
If you are going to use a list of object (List<Object>) and is a
large amount of data, which you want to store even if the app is closed, then use ROOM/SQLite for it.
If you are going to use a list of object(List<Object>) and is a
small amount of data, which you want to store only when the app is
active, then use the static object.
I Think, you should use shared preference for location and static variable which is being retrieved from the network.
If you want to use the current location of the device, use fusedLocationProviderClient once you get it, store it in shared preference. Whenever you the location is provided by fusedLocationProviderClient update the shared preference data.
If the data retrieved from the network is an object and changes every time you open the app and is a small amount of data, then use the static variable, or else use ROOM/SQLite

save application setting in java & javafx

I'm very new to this topic and trying to gain some understanding. I'm writing an application that allows user to personalize it and create his/own preferences, such as font color, size, certain nodes' positions and etc. While doing my research, I found couple examples using xml files to store users' perferenace.
Is this the best way to store information? Is there a more secure way to do it? since xml file is readable for people and not just the machine.
If you need to save more user informations, you can use a database.
But if you need to save one user information, you can use Preferences :
Preferences pref;
pref = Preferences.userNodeForPackage(yourClass.class);
pref.put("yourPreferenceName","yourPreferenceValue");
//This create a String preference if it not exists or modify the value if
//exists
Preferences pref;
pref = Preferences.userNodeForPackage(yourClass.class);
String preference = pref.get("yourPreferenceName","yourPreferenceValue");
//This give you the value of the preference
If you want to know more about the preferences go here.
There is framework named PreferencesFX which is built using JavaFx (supports Java 8 and Java 11). You can use that framework API according to your use case to save preferences in better way with proper UI.

Non-localized strings in android

How do I avoid (some) of my string resources getting localized?
Sometimes I need the same string multiple places. For instance when defining a preference I need the preference key both in my preferences.xml and in my java code in order to get the preference value. Either I can manually define the key twice (which I do now) but I feel that my list of keys is getting large and error prone.
I could also define the key in my strins.xml but then I fear it will get translated (sooner or later (by mistake?)). I fear this could cause problems to have the same preference value store multiple times with different keys. What if the user changes language and all the settings got reset?
Is there a way to define a string - accessible both in code and xml - which will not get translated as a part of the localization process?
In general, if you provide the string only in your default strings.xml it will appear the same on all locales. In addition you can use the "translatable" attribute which will tell Lint that this string is not designed to be translated, and will serve for documentation purposes.
Just use translatable=false. And I suggest putting your preferences keys to separate resource file as it would be easier to manage.
<string name="Key" translatable="false">my key</string>

Determine number of uses of an app - Android

Is there a way to know how many time a user used the app?
basicly i want to do some stuff after 3 uses, 5 uses etc... How can i hold this kind of information after it closed?
You could save that in the preferences. The following code opens the preferences, gets the number of times stored in it, and increments it.
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
int times = preferences.getInt("openKey", 0);
preferences.edit().putInt("openKey", times+1).commit();
You can call this code in your activity's onCreate method.
You can use the SharedPreferences object to store and get any arbitrary information about your application.
Use the Context.getSharedPreferences method to get and instance of this object.
To edit use the edit method to get the editor. don't forget to call commit when you are done.
Important note: if the user uninstalls the application the preferences go away to (just something to keep in mind....)
How about saving the it somewhere? Like in a Database, a SharedPreference or an XML-File?

Android storage advice?

When I log a user in, I pull down some user data. It's just a userid and stuff like that. A couple of strings really. The thing is I don't want to pull this down every time if it's the same user over and over and so I want to store it locally across sessions. I'm aware of SQLite but is making a table just for 1 row really the best solution? Is there not another, better way?
Check the developer.android.com site. Data Storage :
http://developer.android.com/guide/topics/data/data-storage.html#pref
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types
If primitive types is all you need, and the boundary is your application (no multi process stuff), then you should be OK with just using SharedPrefs. Anything else (files,sqlLite) is overkill. SharedPrefs has a clean api that should be sufficient for your needs.
See the developer.android.com site for shared pref usage.
You could use Shared Preferences. It is meant for that.
This other question asks about storing files on the device. The recommendation is to store files on the SD card (if available) and that could be a solution to your problem.

Categories

Resources