android sharedPreferences putString - android

i working sharedPreferences.i wrote code witch can to save information(some strings) and also can show this information in another fragment.now i want to recieve like this result.for example first time i saved 10 and then 20.in a another fragment i can show only 20,but i want to show sum this (10+20).meybe this question is easy but i do not know how i can do this
this is my source
private static String MY_PREFS = "mysessio";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
_price_counter_int = Integer.parseInt(price_counter
.getText().toString().trim());
_price = _price * _price_counter_int;
editor.putString("price",
String.valueOf(_price));
editor.commit();
and another fragment code
String MY_PREFS = "mysessio";
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
String price_result;
sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
price_result = sharedPreferences.getString("price", "");
int ab1 = Integer.parseInt(price_result);
Toast.makeText(getActivity(), String.valueOf(ab1), Toast.LENGTH_SHORT)
.show();

I would suggest to do something like this:
1. Before writing 20, get the value 10
2. Concatenate 20 with 10 with some character (Example 10:20)
3. At the time of getting sum, get the entire string (10:20)
4. Split the string with splitter character :
5. Get the sum
This will allow you to have access to all the consecutive additions to the SharedPreferences.
In case your only concern is to store the sum, you can directly get the value 10, add 20 to it and commit the sum to SharedPreferences.

sharedPreferences = getActivity().getSharedPreferences(MY_PREFS, 0);
editor = sharedPreferences.edit();
_price_counter_int = Integer.parseInt(price_counter.getText().toString().trim());
_price1 = _price * _price_counter_int;
editor.putString("price",String.valueOf(_price));
editor.putString("price1",String.valueOf(_price1));
editor.commit();
Then you can retrieve both the values and display them.

Related

Saving an ArrayList (android)

My application is basically a quiz that presents people with world flags. I want to add a save function that adds the current flag to a separate list. Right now, this is what I do when they click the "save" button:
saveListGC.add(playList.get(1));
(playList.get(1) is the current flag). The problem is, I have to re-define the saveListGC every time the script starts, and that empties the contents:
public static ArrayList<String> saveListGC = new ArrayList<String>();
So what I'm wondering is how can I save this data, and re-load it later? I've seen things about using SharedPrefernces, but I don't really understand it. If someone could please explain it as easily as possible, I would really appreciate it. Thank you!
This a simple example of how you can use SharedPreferences:
//intiat your shared pref
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
Editor editor = pref.edit();
//store data to pref
editor.putString("myString", "value 1");
editor.commit();
//retrieve data from pref
String myString = pref.getString("myString", null);
But the real problem here is that SharedPreferences can not store an Object of type List (ArrayList), but you can store an Object of type Set (like Hashset) using this method
Set<String> mySet = new HashSet<String>();
mySet.add("value1");
mySet.add("value2");
mySet.add("value3");
editor.putStringSet("MySet", mySet);
So to answer your second question, this what i propose for you to do:
//This is your List
ArrayList<String> saveListGC = new ArrayList<String>();
//Convert your List to a Set
Set<String> saveSetGC = new HashSet<String>(saveListGC);
//Now Store Data to the SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Editor editor = pref.edit();
editor.putStringSet("MySet", saveSetGC);
editor.commit();
//After that in another place or in another Activity , Or every where in your app you can Retreive your List back
pref = getApplicationContext().getSharedPreferences("MyPref", 0);
Set<String> mySetBack = pref.getStringSet("MySet", null);
//Convert Your Set to List again
ArrayList<String> myListBack = new ArrayList<String>(mySetBack);
//Here you can se the List as you like...............
Log.i("MyTag", myListBack.get(0));
Log.i("MyTag", myListBack.get(1));
Good Luck :)

Android: SharedPreferences with longs

I want to save a time from a TimePickerDialog to sharedpreferences from my settings menu. I then want to retrieve this data when from another fragment. The time is stored as a long.
In the setting menu - when the positive button is pressed
SharedPreferences preferences = context.getSharedPreferences("TIME", Context.MODE_PRIVATE);
SharedPreferences pref = context.getSharedPreferences(
"any_prefname", Context.MODE_PRIVATE);
Editor editor = pref.edit();
editor.putLong("key_name", 8);
editor.commit();
In the fragment:
SharedPreferences pref = getActivity().getSharedPreferences(
"any_prefname", Context.MODE_PRIVATE);
Long longValue = pref.getLong("key_name", 0);
Toast.makeText(getActivity(), "Hi " + longValue, Toast.LENGTH_SHORT).show();
The problem is that the value "8" that I saved is note being shown in the toast from the fragment. The value being used is the 0.
Thank you
You aren't using the same key. When saving you used "time", when loading you used "key_name". You need to use 1 name.

Saving high scores in Android game - Shared Preferences

Recently I am developing a simple android game. For the scoring part, I have on many websites that shared preferences are best to save the high score. Now, what if I need to save high scores of different levels in my game? I wish to save top three scorers score for each level...
To save your scores you can do something like this:
// prepare the data: put the String values of the scores of the first 3 users
// in one String array for each level
String[] firstLevelHighscores = new String[] {
firstUserLevel1Score, secondUserLevel1Score, thirdUserLevel1Score
};
String[] secondLevelHighscores = new String[] {
firstUserLevel2Score, secondUserLevel2Score, thirdUserLevel2Score
};
String[] thirdLevelHighscores = new String[] {
firstUserLevel3Score, secondUserLevel3Score, thirdUserLevel3Score
};
// now save them in SharedPreferences
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
Editor editor = sharedPref.edit();
editor.putStringSet("level1", firstLevelHighscores);
editor.putStringSet("level2", secondLevelHighscores);
editor.putStringSet("level3", thirdLevelHighscores);
Note that you can put even more user's scores into the String array. And if you need to save scores for more levels, you simply create more arrays.
To retrieve the saved data from SharedPreferences, you do it like this:
SharedPreferences sharedPref = getSharedPreferences("LevelScores",
Context.MODE_PRIVATE);
String[] firstLevelHighscores = sharedPref.getStringSet("level1", null);
String[] secondLevelHighscores = sharedPref.getStringSet("level2", null);
String[] thirdLevelHighscores = sharedPref.getStringSet("level3", null);
I assume you're able to convert int to String and vice versa. Hope it works for you this way.
A lot of ways to save your scores to the SharedPreference. All depending on your style of implementation.
You can simply use the putStringSet(key, String[]) where as the key will be the level and the String[] the 1ste, 2nd and 3th place.
score setting
static final String[] LEVEL = {"level1","level2","level3"};
int bestScore1 = 100;
int bestScore2 = 90;
int bestScore3 = 80;
SharedPreferences sp = getSharedPreferences(LEVEL[0],Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("First", bestScore1);
editor.putInt("Second", bestScore2);
editor.putInt("Third", bestScore3);
editor.commit();
but you need to count LEVEL's index
score getting
SharedPreferences sp = getSharedPreferences(LEVEL[0], Activity.MODE_PRIVATE);
bestScore1 = sp.getInt("First", 0);
bestScore2 = sp.getInt("Second", 0);
bestScore3 = sp.getInt("Third", 0);
hmm.. but I think it is not best way for your question :<

Issue with shared preference

I am using Android 2.1 sdk and I am trying to save user loggin session in to Shared preferences, the thing is after saving the value to the shared preference I am unable to retrive it. Here I am pasting the code I used to save and fetch value from SharedPrefrence.
public void setValue(String name, String value, String prefName) {
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
sharedPref.edit().putString(name, value);
sharedPref.edit().commit();
}
public String getValue(String name, String prefName) {
String value = null;
sharedPref = mContext.getSharedPreferences(prefName, Context.MODE_PRIVATE);
value = sharedPref.getString(name, value);
return value;
}
Did i miss some thing in this code, I am not retrieving any exceptions while saving and retrieving the value. Thanks for any help.
Every call to edit() returns you a new Editor instance. So you get an instance, make a change and leave it alone. Then you get a second one and commit that without changes, which results in no value changes in the preferences.
Rather chain in the commit():
sharedPref.edit().putString(name, value).commit();
Alternatively break it up into multiple lines with one specific instance:
Editor e = sharedPref.edit();
e.putString(name, value);
e.commit();
private SharedPreferences myPrefs;
myPrefs = Actionactivity.this.getSharedPreferences("myPrefs", MODE_WORLD_WRITEABLE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putString("Mobile_no", getText_no.getText().toString().trim());
prefsEditor.commit();
myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
myPrefs.getString("Mobile_no", "");
try this one code work

How to store variable in phone memory android?

i need to store a variable in phone memory, and later get that variable to show it.
Please, give me some information or anything to search. Thanks
static SharedPreferences settings;
static SharedPreferences.Editor editor;
settings = this.getPreferences(MODE_WORLD_WRITEABLE);
editor = settings.edit();
editor.putString("Variablenname_1", "1");
editor.commit();
if you want so get the value use:
String val = settings.getString("Variablenname_1", "0");
I think Shared Preferences is a good idea for you, read this for more information: http://developer.android.com/guide/topics/data/data-storage.html
The final result.
SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
String text = app_preferences.getString("name", "default");
...
SharedPreferences.Editor editor = app_preferences.edit();
editor.putString("name",name.getText().toString());
editor.commit();

Categories

Resources