Trying to import a SharedPreference of values? - android

I used SharedPreferences in one activity to basically store a bunch of data in a HashMap like method. In particular, app names (String) and their respective sorting as either a Category 1, 2, or 3 app. Stuff like:
editor.putString("Cut the Rope", "Category 1");
In another activity, I want to use this SharedPreference to create an ArrayList of only the Category 1 apps. Here is how I thought this could be done:
ArrayList<String> cat1Apps = new ArrayList<String>();
SharedPreferences stored = getSharedPreferences("Sorted Apps", 0);
SharedPreferences.Editor editor = stored.edit();
Map<String, ?> mappedPreferences = stored.getAll();
for(Map.Entry<String, ?> entry: mappedPreferences.entrySet()){
if(entry.getValue().toString().equals("Category 1")){
cat1Apps.add(entry.getKey());
}
}
For some reason though, this isn't working. I'm taking these app names and then later there's some code that creates a GridView display of Category 1 apps. If I just define cat1Apps.add() a bunch of time, this works fine, but if I try to import through the SharedPreferences as above, it doesn't create the GridView.

The problem here is that editor.commit() was never inserted after after adding the Strings to SharedPreferences so they were never saved. Otherwise, this code to retrieve the SharedPreferences was correct.
Some debug links as asked for by the OP
This one isn't necessarily about debugging but has some good information
Eclipse Debugging
YouTube video onDebugging- Note I just scrolled through some of this but looks like it could be helpful
Also not that when they say, "Right click and click toggle breakpoint", you can also double-click in the margin and you should see a green dot which means there's a breakpoint there. Double-click the green dot to remove the breakpoint.

Related

Android - ImageButton Values / SharedPreference

If you have time , please can you take some time for me ? I really need some help.
Let me explain;
Im working on an android app.
There is a layout and it has 5 ImageButton and a webview. When the users click on a imagebutton, without problem it calls a website below..but more or less i have 20 web site.i want to add an option for users..for example the user will choose a web site from Prefs. screen then automatically one of imagebuttons values (i mean icon AND its loadurl function) will change.
I created Pref Screen and i can see my website in this which i wrote in array.xml
but totally im not able to set them to Imagebuttons..
im beggin u.its our last curve..then it ll finish.
Im tried to use this code :
Data = getSharedPreferences(filename, 0);
SharedPreferences.Editor e = data.edit();
e.putString("website", websiteVariable);
e.commit();
but i couldnt.
Please explain me step by step clearly.
also i dont want that only for me,on internet there is no source for this issue.im searching and trying everything what i can think more than 6 days but nothing.
Thank you so much
SharedPreference Data = getSharedPreferences(filename, 0);
SharedPreferences.Editor e = data.edit();
e.putString("website", websiteVariable);
e.commit();
Basically what this does is allows you to store user information such as scores for a game, stats, and other variables.
The first line gets reference or creates the file to write the data to.
The second line allows you to edit the file to write new information to it..
e.putString()
Takes two parameters the first one being the Key to pull the value you out later, and the second being the value you want to put into the file.
The last line commits the data so that it is saved to the file.
You can get more info from the docs here
Also if you want to pull the data out just do
SharedPreference Data = getSharedPreferences(filename, 0);
String value = Data.getString("website"); // use the key here to pull the data out
EDIT:
So for example if the user selects a certain image you could use a key to refer to each image and get the value later to decided which icon the user picked before.

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.

How do I save history in an android app?

I have a listview called history that I call every time that I so something significant (ie open or close the app or record some info) The problem I have is that it records things from top to bottom meaning the most recent information is on the bottom of the listview. The second problem I have is that the listview gets deleted after the app is turned off. How do people usually save their history? (ie shared preferences can only store one variable and thats not enough, I would like to save a maximum of 30 entries to the listview)
Thanks
One option I use is to JSON encode my history list and store the resulting string to SharedPreferences. You can then order it as well (simply add items to the List that backs the ListView with new events first) and save it and restore it from the SharedPreferences file.
EDIT: Try something like this:
org.json.JSONArray tracking_users = new org.json.JSONArray();
tracking_users.put("history 1");
tracking_users.put("history 2");
tracking_users.put("history 3");
You could also consider using a database to store the Log of these events, tends to be more efficient.
See one of these for an introduction to android databases

Android - ListPreference save to file or on entry click listener?

My application has a preference file, "settings", which contains 10 key/value pairs.
The keys act as titles for the user, and the values are URL's
Both the key and the value are changeable by the user e.g. the first setting looks something like "example" with the value "example.com", when a user changes that setting, the key also changes. So the first setting would become "different_example" with the value "different_example.com". All stored under the "settings" preference file.
I have been managing this so far, by opening a dialog containing the current key/value pairs in an ArrayList that has an onItemClickListener that pops up a second dialog containing another ArrayList of the possible key/value pairs. When the new item is clicked, I remove the current setting, add the new one, then re-populate the initial ArrayList with the new settings. This works and allows both the key and value to be simultaneously changed and updated, however it looks awkward with the two dialogs.
I'd like to switch this all over to ListPreferences. As in, have ten different ListPreference items, one for each setting, that when clicked opens the listing of all possible entryValues, and when selected, updates the key from the entry name, and the value from the entry value, and saves this under the same "settings" file. I'm not seeing how to save ListPreferences to a specific file, so that I can call
SharedPreferences settings = getSharedPreferences("settings", 0);
anywhere, though
I've also been looking for some kind of click handler for what to fire when an entry is selected so I can manually update the "settings" file, but not having any luck. Does such a thing exist? Or is there another way for me to do this?
Edit: I can use OnPreferenceChange to manually set the new value, but this doesn't return the value name, e.g. the value used in the human-readable list. Any ideas on how to get that?
See if this can give you a jump start: How do I get preferences to work in Android?
If you customize your ListPreference and come across something like this How to make a Preference not save to SharedPreferences?
Ahh, well this seems incredibly backwards, but what I've done is set each ListPreference to have an onPreferenceChangeListener, and each entryValue for the ListPreference to contain the name as well as the value separated by an arbitrary string. Then in the onPreferenceChange, I can reference the new value (which now also contains the new key) turn it into a String[] split at the arbitrary separator, then assign the String[] 0 index as the new key, and the 1 index as the new value by using SharedPreferences.Editor after removing the original setting.
Unless there's some way to return the Entry name from the ListPreference's entryValues array, or to specify ListPreference to save to a specific settings file, neither of which is documented, then this will probably be the best solution for me.

Strange behaviour for ListPreferences

Here's the problem I'm facing : In my application I have several preferences stored in sharedPreferences that record different settings of the application. These are some strings. Because I want the application to start with some default values for these settings , in onCreate I construct a "Setting" object for each setting in which I check to see if the sharedPreference associated is null and if it is so I put the default Value in the sharedPreference.
Setting(int setting, String default)
{
storedPref=sharedPref.getString(getText(setting),null);
if(storedPref==null)
{
SharedPreferences.Editor edit=sharedPred.edit()
edit.putString(getText(setting),default);
edit.comit
}
}
The views associate to these settings are ListPreferences (). When first opened the application , they are supposed to display a list of options , in which the selected one is the default ,but it happens sometimes no options is selected , not even the default one, which is not intended.
The listPreferences are constructed in xml , by setting an array to the "entries tag" and to the "values tag" . I'm not really sure , what should I pass to the constructor of the Setting object for the default , a member of the entries array , or a something from the values one !!! If I pass a member of the entries some will Listpreferences will have the expected behaviour and some will have the one described above. If I do otherwise and pass something from the values array , the same thing happens ! Has anyone any ideea why this strange behaviour ?
You should check out the preferences file, and recognize the key and format is used by our ListPreference, then you use the same key value pair in your SharedPreferences.Editor
you will find your prefs files in the following folder
/data/data/com.your.package/shared_prefs/
you get there by running in console:
adb shell
cd /data/data/com.your.package/shared_prefs/
ls
Since the second parameter of SharedPreferences.getString() is the default value that will be returned if the key is not present, you could just as easily write
Setting(int setting, String default)
{
storedPref=sharedPref.getString(getText(setting),default);
}

Categories

Resources