android save settings and information - android

i am new to android, i searched a lot and couldn't find a satisfying answer; what i need is to save some setting for my application such as
1> language, number of items to display, display/not display images, etc...
which i think is best done using the shared preferences
2> save which data categories to get from the internet...
here is my problem:
i have data divided into category objects with key, name, type, data[]...(data[] is changing all the time and not saved after exiting the application),(key, name, type are final values defined by programmer).
and because there are many categories which the user may or may not want to load(around 25), he/she can choose which categories to display, and these choices must be saved.
i think using shared preferences will not help because of the complexity of the data; i was thinking of using sqlite or xml, not sure which is the best choice keeping in mind efficiency and memory size.
note: i am using a global variable for the category information array, that is because data[] needs to be refreshed automatically every 2-3 minutes and must be available to all activities also efficiency and memory space are an issue.
i will appreciate any advice, thank you in advance.

1> SharedPreferences is the right choice
2> you have multiple possibilities
a) Use the internal storage and use Object Serialization (for simplicity reasons), xml (if you want to exchange the data) or use a own format
b) SQLite is the fastest solution. But you have to do more programming for that
b would be my choice, so create a DB-Object (static or singleton pattern) and write functions for every database task

1) Yes, SharedSettings should help youy. There is plenty information around, but post back if you are lost.
2) I would make a table with all the categories and a boolean value thats says "show" where you can keep if the user wants to show it or not.
Of course it depends on the size of the categories and how much they change, because otherwise you will be updating the database forever.

User shared preference in store your setting,
SharedPreferences sharedPreferences = this.applicationContext.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
//For saving the setting:
//for storing long
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putLong(key, value);
//for storing string editor.commit();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
//and similarly for int,float etc
//For Retrieving the string:
sharedPreferences.getLong(key, defaultValue); //for long value
sharedPreferences.getSting(key, defaultValue); //for string value

Related

Why does SharedPreferences need two keys?

I'm trying to build a single object that handles all my SharedPreferences, since they are mostly used in the whole app, and I don't quite Understand why it takes two keys to get a value.
The call looks like this:
context.getSharedPreferences(FirstKey, Context.MODE_PRIVATE).getString(SecondKey, default)
I get that its basically built up as a two dimensional array.
The FirstKey gives me a collection of key-value pairs I can use my SecondKey on to get my value. And I get that If I have dozens of SharedPreferences this might come in handy to manage them and prevent mixups/unwanted overwriting.
But is this necessary If I only have like 10 preferences I save anyway or is it reasonable to just use one FirstKey for all of my preferences?
But is this necessary If I only have like 10 preferences I save anyway
or is it reasonable to just use one FirstKey for all of my
preferences?
So for this case you can avoid the use of that FirstKey by using getDefaultSharedPreferences() like this:
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(context).edit();
editor.putString("myKey", "myValue");
editor.apply();
or read already set preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String myPref = prefs.getString("myKey", "myDefaultValue");
I guess it is to encapsulate, organize and manage better groups (first key values) of data you want to store (second keys values). So in case you want for example to retrieve all settings preferences you can group them by a Settings file (first key). Or in case you would like to delete all stored values regarding a user preferences (preferred language, preferred currency.. ) then you can organize those data within a "UserPref" file (first key) and then you can iterate within it to either delete all of them when you logout or whatever pogic you see useful for your user experience.
First key
Retrieve and hold the contents of the preferences file
Second key
Retrieve and hold value in this file
You can use only your "FirstKey" for all your preferences and normally dev us it like this only. You can create multiple instances of shared preference by changing the "First key" at the time of getSharedPreference(). Suppose you want two different shared preference for two different modules in your project then change the "FirstKey" parameter, in this case, you have two be careful while storing and fetching data from preference as you have two different shared preference.
As you rightfully stated, the first key represents a group of key-value pairs (which is actually very similar to a single file) and the second key helps you fetch the values in that file/group.
I personally believe this design is great especially in cases where you may want to separate all your values into different categories. If your app is "small", you can save all your values in one single file/group. Otherwise, you can split all your values into separate files/groups.
I hope this helps.. Merry coding!

SharedPreferences - Difference between these two ways of retrieving the Preference value?

I am using the Preference-API..
Typically when I need to retrieve the value of a Preference, I currently do something like this:
final SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(getActivity());
boolean isThisPrefEnabled = getPrefs.getBoolean(REFERENCE_TO_PREF_NAME, false);
// OR
String theChosenPref = getPrefs.getString(PREF_NAME, DEFAULT_VALUE);
But I'm curious, couldn't I also do it like this? and if so, what is the difference?
Preference nameOfPref = findPreference(PREFERENCE_KEY);
boolean isPrefEnabled = nameOfPref.isEnabled();
// OR
String thePrefValue = nameOfPref.toString();
It seems to be more efficient, but the first example seems to be what get's used. Why is this?
Thanks.
SharedPreferences is an android specific interface documentation
android.content.SharedPreferences : is a key/value store where you can save a data under certain key. To read the data from the store you have to know the key of the data. This makes reading the data very easy. But as easy as it is to store a small amount of data as difficult it is to store and read large structured data as you need to define key for every single data, furthermore you cannot really search within the data except you have a certain concept for naming the keys.
Preferences is a core java class documentation
java.util.prefs.Preferences : This class allows applications to store
and retrieve user and system preference and configuration data. This
data is stored persistently in an implementation-dependent backing
store.

Android Google Fit select max results

I try to develop some fitness application which will use Google Fit.
And i have one question. Assume that user make some sport activity a few days in a week. And want to show him his best result. The only way I know I can do this - is load all data from user history and then select the set with maximum value.
And its obvious that I dont like that method because of the fact that I should load all the history. (And the user can have history for a few years).
Another way is to store data in local database (so i dont need to load all history every time the user want to see his best result) and synch it with google fit data, but I think its too dificult.
Do we have some other options for that kind of tasks?
Use sharedpreferences to save the value,
To set value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putInt("key", score);
editor.commit();
To get value
SharedPreferences prefs = this.getSharedPreferences("myhighestscore", Context.MODE_PRIVATE);
int score = prefs.getInt("key", 0);
here is a link.
Using Shared Preferences

Best way to store a single user in an Android app?

I'd like my app to allow a single user to create a profile that is accessed every time they run the app. The user's profile contains a String entry and five int entries. I've thought about using an SQLite database to store the info between sessions, but it seems like overkill since I'd only need one row in a single table to store the data. However, I'm not sure if it's possible to use SharedPreferences on a String type of data.
Can anyone provide some insight into this issue please? Thank you!
Yes you can use SharedPreferences.
To write
Editor editor = getSharedPreferences("file_name", MODE_PRIVATE).edit();
editor.clear();
editor.putString("pref_name", myStringValue);
editor.commit();
To read back
SharedPreferences preferences = getSharedPreferences("file_name", MODE_PRIVATE);
String myStringValue = preferences.getString("pref_name", "default_value");
Regards.

Android storing string array

I've been looking for over the past day and a half at several websites about how to store strings/string arrays/etc. and I can't seem to figure it out. I'm not sure if I'm just not quite comprehending how to implement data storage..or what. But here is my problem, simply put, I have two activity pages (we'll name 'A,B' respectively) . All I want to do is get a string from a text view in Activity B, store it in an array, and then have it accessed by clicking a button in Activity A.
I know it is simple, but I hit a block for some reason... I am trying to use SharedPreferences but how would I obtain the string from Activity B, store it in a global array, and let it be accessed by a different activity (Activity A) ?
Just store it into shared preferences (usually in onPause()):
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putString(GAME_STATE, writer.toString());
editor.commit();
in one activity and load in another (usually in onResume()):
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
String jsonState = preferences.getString(GAME_STATE, null);
And nothing prevents you from using public static variables
You can't store an array directly in shared preferences, but you can store a set.
See putStringSet and getStringSet. You can add all the items from your array to a LinkedHashSet (as long as they are unique) if you wish to store them in SharedPreferences. See Konstantin's answer for the general idea on how to use SharedPreferences.
Yes you can obtain and store value in global array but you will loss everything once you close the application. So its better you create a table and store/get values from the table whenever you required.
Here is an example for creating SQLite example.

Categories

Resources