Android storing string array - android

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.

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!

Android Saving data on Button

I have a button in a customView which has several numbers on it individually,it counts backward
now my program doesn't keep value on it when user taps back and closes the program How can I prevent this ?
You can pass value from one activity to other using intents. If you want to persist data,the simplest way to achieve this would be saving it in Shared Preferences.
Developer link has good information on how to implement this -
You can save the value Key, Value pair and then retrieve it when the app is up again.
you can Use SharedPreferences its easy to write and get.
You can create one like this
SharedPreferences prefs = getSharedPreferences("yours", MODE_PRIVATE);
and write to like this
SharedPreferences.Editor prefsEditor=prefs.edit();
prefsEditor.putString("what you want", "value of what you want");
prefsEditor.apply();
and retrive like this
String s=prefs.getString("what you want", "value to be retrived if failur happens in retreiving")
if the value not important after end the program you can save it into public static variable
but if you need the variable after end the program you can use SharedPreferences
follow this tutorial http://developer.android.com/reference/android/content/SharedPreferences.html

How to store values in preferences over one another

When i write anything into shared preferences it overwrites the previous value, how can i continuously inject values in preferences and fetch it out all at once like an array? I do not want to use database for this operation.
Thanks
You can use JSON as #CommonsWare points out to store your data in SharedPreferences. I have such an answer that using GSON here:
https://stackoverflow.com/a/5968562/617044
Though not ideal, if you want to use Preferences only, You can store String in preferences. When next value is to be added, retrive the old one add 'comma' and new value.
Whenever you want to use these values, use StringTokeniser. Tokenise elements by 'comma' character.

Keeping data when Android does an onExit()

I have a String array that I want to keep to display in a ListView, but every time I exit the activity, the global String array is deleted and the ListView doesn't display. Is there anyway that I can keep a String array in the application's storage for the next use?
It's actually pretty easy for just a string. You can store it in shared preferences. See this link: http://developer.android.com/guide/topics/data/data-storage.html#pref

android save settings and information

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

Categories

Resources