Android: SharedPreferences Issue (Multiple SharedPreferences) - android

I have multiple SharedPreferences that are each storing one int value each. I have successfully created multiple SharedPreferences before, but I am trying a slightly different approach for this one. I am only keeping the highest 5 values. I am getting each value from its SharedPreference, then I am adding the 5 values + the current value I want to compare against the others in an ArrayList. I am calling the reverse sort method on it, then I am removing the last value (because it is extra). I am then putting each index into the editor of the SharedPreferences. Here is what I have:
prefs1 = this.getSharedPreferences("key1", Context.MODE_PRIVATE);
int value1 = prefs1.getInt("number1", 0);
prefs2 = this.getSharedPreferences("key2", Context.MODE_PRIVATE);
int value2 = prefs2.getInt("number2", 0);
prefs3 = this.getSharedPreferences("key3", Context.MODE_PRIVATE);
int value3 = prefs3.getInt("number3", 0);
prefs4 = this.getSharedPreferences("key4", Context.MODE_PRIVATE);
int value4 = prefs4.getInt("number4", 0);
prefs5 = this.getSharedPreferences("key5", Context.MODE_PRIVATE);
int value5 = prefs5.getInt("number5", 0);
ArrayList<Integer> numList = new ArrayList<Integer>();
Collections.addAll(numList, value0, value1, value2, value3, value4, value5);
Collections.sort(numList, Collections.reverseOrder());
numList.remove(numList.size()-1);
value1 = numList.get(0);
value2 = numList.get(1);
value3 = numList.get(2);
value4 = numList.get(3);
value5 = numList.get(4);
Editor editor = prefs1.edit();
editor.putInt("number1", value1);
editor.commit();
editor = prefs2.edit();
editor.putInt("number2", value2);
editor.commit();
editor = prefs3.edit();
editor.putInt("number3", value3);
editor.commit();
editor = prefs4.edit();
editor.putInt("number4", value4);
editor.commit();
editor = prefs5.edit();
editor.putInt("number5", value5);
editor.commit();
The problem I am having is that is showing 0s for each one of the values in my other activity even after value0 is positive after it executed through.
Is there anything wrong with how I am doing this? (If not then it must be when I get these values in another activity, but I am almost positive I have that right.)
EDIT*
Perhaps it is in the retrieval, here is from the retrieving activity:
prefs1 = this.getSharedPreferences("key1", Context.MODE_PRIVATE);
num1 = prefs1.getInt("number1", 0); //0 is the default value
tv1 = (TextView) findViewById(R.id.val1);
tv1.setText(String.valueOf(num1));
prefs2 = this.getSharedPreferences("key2", Context.MODE_PRIVATE);
num2 = prefs2.getInt("number2", 0); //0 is the default value
tv2 = (TextView) findViewById(R.id.val2);
tv2.setText(String.valueOf(num2));
prefs3 = this.getSharedPreferences("key3", Context.MODE_PRIVATE);
num3 = prefs3.getInt("number3", 0); //0 is the default value
tv3 = (TextView) findViewById(R.id.val3);
tv3.setText(String.valueOf(num3));
prefs4 = this.getSharedPreferences("key4", Context.MODE_PRIVATE);
num4 = prefs4.getInt("number4", 0); //0 is the default value
tv4 = (TextView) findViewById(R.id.val4);
tv4.setText(String.valueOf(num4));
prefs5 = this.getSharedPreferences("key5", Context.MODE_PRIVATE);
num5 = prefs5.getInt("number5", 0); //0 is the default value
tv5 = (TextView) findViewById(R.id.val5);
tv5.setText(String.valueOf(num5));

You can think of SharedPreferences like a giant map for all your stuff, but unless you are doing anything funky, you should store and retrieve data from the same giant map (i.e. the same SharedPreferences). What you are doing is creating named shared preferences. I would recommend just using the default. If you are curious to learn more about what that means check out this question.
So, in your case if you are storing 5 values, you can do so within the same SharedPreferences by just supplying different keys as follows:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
mSharedPreferencesEditor.putInt("numberX", numberX);
mSharedPreferencesEditor.putInt("numberY", numberY);
mSharedPreferencesEditor.commit()
mSharedPreferences.getInt("numberX", numberX);
mSharedPreferences.getInt("numberY", numberY);
You can easily get and put with different keys into the same sharedPrefs. Your code would become:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
int value1 = mSharedPreferences.getInt("number1", 0);
int value2 = mSharedPreferences.getInt("number2", 0);
int value3 = mSharedPreferences.getInt("number3", 0);
int value4 = mSharedPreferences.getInt("number4", 0);
int value5 = mSharedPreferences.getInt("number5", 0);
...
mSharedPreferencesEditor.putInt("number1", value1);
mSharedPreferencesEditor.putInt("number2", value2);
mSharedPreferencesEditor.putInt("number3", value3);
mSharedPreferencesEditor.putInt("number4", value4);
mSharedPreferencesEditor.putInt("number5", value5);
mSharedPreferencesEditor.commit();
Your issue concerning all your values being 0 may be different. I would fully expect all your calls to getInt to be 0 because you are never storing anything but 0 in the sharedPrefs. It looks like you are just adding zeros and putting zeros. I am not sure what you are trying to do here, but it sure would help to, at some point before calling this function, assign numbers 1-5 to something other than 0 by calling mSharedPreferencesEditor.putInt(number); on a sharedPrefs object like so:
SharedPreferences mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor mSharedPreferencesEditor = mSharedPreferences.edit();
//for example, for the key "number5"
mSharedPreferencesEditor.putInt("number5", value5);

Related

Can we Call two different shared preferences data inside one method in java?

SharedPreferences preferences_type = PreferenceManager.getDefaultSharedPreferences(this);
String preferences_typename = preferences_type.getString("name", sname);
String preferences_typeSocietyname = preferences_type.getString("societyname", ssociety);
String preferences_typeFlatno = preferences_type.getString("Flatnumber", sflat);
//Toast.makeText(MainActivity.this,"name"+preferences_typeS,Toast.LENGTH_LONG).show();
name.setText(preferences_typename);
society.setText(preferences_typeSocietyname);
Flatno.setText(preferences_typeFlatno);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
String previouslyEncodedImage = shre.getString("image_data", "");
if( !previouslyEncodedImage.equalsIgnoreCase("") ){
byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
profileImage.setImageBitmap(bitmap);
//profileImage.setImageResource(ContextCompat.getDrawable(this, profileImage);
}
Yes you can. Just use preference name to uniquely address them.
//create shared preference 1 where you want
SharedPreferences data1 = this.getSharedPreferences("pref1", 0);
//put some data
SharedPreferences.Editor editor = data1.edit();
editor.putString("string1", "some string");
editor.commit();
//create shared preference 2 where you want
SharedPreferences data2 = this.getSharedPreferences("pref2", 0);
//put some another data
SharedPreferences.Editor editor = data2.edit();
editor.putString("string2", "some another string");
editor.commit();
You can retrieve that data where ever you want uniquely by refering the name you gave when creating the SharedPreference.
SharedPreferences somedata1 = this.getSharedPreferences("pref1", 0);
String someStr1 = somedata1.getString("string1", "default");
// use data
SharedPreferences somedata2 = this.getSharedPreferences("pref2", 0);
String someStr1 = somedata1.getString("string2", "default");
// use data
hope this helps.

Retrieving SharedPreferences Values not working. Any ideas what I'm doing wrong?

Here's where I store values into SharedPreferences in one activity:
sharedPref = context.getSharedPreferences("sharedPref", Context.MODE_PRIVATE);
String firstPlace = new String("1");
String secondPlace = new String("2");
String thirdPlace = new String("3");
editor = sharedPref.edit();
editor.putString("first", firstPlace);
editor.putString("second", secondPlace);
editor.putString("third", thirdPlace);
editor.commit();
And try to retrieve them in another activity. However, the retrieve doesn't seem to be getting the values I put in and is just using the defaults (so "1st Place: " "2nd Place: " and "3rd Place: " end up with a 'no' next to them).
SharedPreferences sharedPref = getSharedPreferences("sharedPref", MODE_PRIVATE);
String firstPlace = sharedPref.getString("first", "no");
String secondPlace = sharedPref.getString("second", "no");
String thirdlace = sharedPref.getString("third", "no");
highScore1.setText("1st Place: " + firstPlace);
highScore2.setText("2nd Place: " + secondPlace);
highScore3.setText("3rd Place: " + thirdlace);
You can try to direct put value
editor = sharedPref.edit();
editor.putString("first", "1");
editor.putString("second", "2");
editor.putString("third", "3");
You have used separate contexts. To make your sharedpreference accesible to entire application you need default sharedpreference. Declare it as below
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
After this you can edit and fetch data as you did before.
please try this,
this.SharedPrefs = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor localEditor = this.SharedPrefs.edit();
localEditor.putString("first", firstPlace);
localEditor.putString("second", secondPlace);
localEditor.putString("third", thirdPlace);
localEditor.commit();
finish();

Add data fromEeditText to double

I have an app where the user can enter an amount into an EditText but then I want to be able to add or subtract this to/from a double then be able to display this double with a TextView within another activity.
I'm not sure how to go about this and would appreciate some help.
Thanks in advance!
Edit: I forgot to mention that I also want this data to be kept between app launches/closes.
In your activity that accepts the input from the EditText:
double value = Double.parseDouble(yourEditText.getText().toString());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (adding) {
value = prefs.getFloat("your.float.key", 0f) + value;
} else {
value = prefs.getFloat("your.float.key", 0f) - value;
}
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("your.float.key", value);
editor.apply();
In your activity that shows the value:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Double value = prefs.getFloat("your.float.key", 0f);
yourTextView.setText(value.toString());
Firstly you will need to parse the data from your EditText, you can get a String from an EditText using
EditText.getText().toString()
and then use some form of
Double.parseDouble(String)
Integer.parseInt(String)
to get a numeric value from the string, with which you can then use for whatever math you need. After you calculate this value you will want to send it to another Activity via intent
Intent i = new Intent(this, ActivityTwo.class);
i.putExtra("KEY", myDouble);
startActivity(i);
to receive the intent in your next activity use
Bundle extras = getIntent().getExtras();
if (extras != null) {
Double myDouble = extras.getDouble("KEY");
}
and then if you want to save the value you will want to look into SharedPreferences
to save
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putFloat("KEY", myFloat);
editor.commit();
to get
SharedPreferences prefs = getSharedPreferences("KEY", Context.MODE_PRIVATE);
myFloat = prefs.getFloat("KEY", myFloat);

How to save value in SharedPeference in the actitvity and access it all other classes

I want to save totalBalance in this activity to SharedPreferances and the retrive it in another class.
so i want totalbalance to be displayed in another activities in same application...
if possible also edit it in other activites...
please help... thanks
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
// Genrating random number Random number
Random rn = new Random();
randomNumber = (int) rn.nextInt(9) + 1;
// changes textView1 equals to random number
textView1.setText("Random Number is "
+ Integer.toString(randomNumber));
button1.setText("Play Again");
// Matching random number to ArrayList
if (positive_IDs.contains(randomNumber)) {
// if matched then changes textView2 to Matched Number
textView2.setText("Number: "
+ Integer.toString(randomNumber) + " Matched");
totalBalance = totalBalance + winingPrize;
textView5.setText("Total Balance = Rs: "
+ String.format("%.2f", totalBalance));
}
}
try this,
public void saveValue(String lock, Context context) {
Editor editor = context
.getSharedPreferences(KEY, Activity.MODE_PRIVATE).edit();
editor.putString("Value", lock);
editor.commit();
}
public String getValue(Context context) {
SharedPreferences savedvalue = context.getSharedPreferences(KEY,
Activity.MODE_PRIVATE);
return savedvalue.getString("Value", "");
}
Save Value as Following
int Value;
private void saveValues(){
SharedPreferences readSP = getSharedPreferences("String", MODE_PRIVATE);
SharedPreferences.Editor editor = readSP.edit();
editor.putString("String", Value);
editor.commit();
}
Retrive value in any of your Class As following
int value;
private void getSavedValue()
{
SharedPreferences settings = getSharedPreferences("String", MODE_PRIVATE);
value=settings.getString("String", "");
}
// try this
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("balance", String.format("%.2f", totalBalance));
editor.commit();
SharedPreferences sharedPreferences = getSharedPreferences("yourSharePreferenceName", MODE_PRIVATE);
String total = sharedPreferences.getString("balance");
Use following code to retrive your value from SharedPreference,write this in other class where you want to retrive value of total balance
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
Editor edit1 = remembermepref.edit();
edit1.putInt("totalbalance_key",totalBalance);
edit1.commit();
and to store total balance into ShardPreference use in your activity:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(YourActivityName.this);
int totalbalance = pref.getInt("totalbalance_key");
Now use totalbalance way you want.
Most important thing is to check whether you have used same key to restore as well as tostore the value in SharedPreference
Hope this helps..

SharedPreferences keep getting default value

I keep Getting the Default value either my UI will display null or if I use integers it displays that default value as well here it is in the string form plz help
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2= PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString(newUserScore1, NewUserScore1);
editor.commit();
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
I have added some comment to you code please check:
//putting the information in shared preferences
TextView pScore1=(TextView)findViewById(R.id.pScore1f);
SharedPreferences peepsScores2=
PreferenceManager.getDefaultSharedPreferences(GamePlayFirst.this);
SharedPreferences.Editor editor2 =peepsScores2.edit();
String userScore11 = pScore1.getText().toString();
editor2.putString("userScore11",userScore11);
editor2.commit();
//getting it and editing it
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
int u;
int one =1;
int newUsrScore1=1;
String userScore11 = peepsScores2.getString("userScore11",null);
u=Integer.parseInt(userScore11);
newUsrScore1 = u+one;
String newUserScore1 = Integer.toString(newUsrScore1);
SharedPreferences.Editor editor = peepsScores2.edit();
//#Praful: here newUserScore1 seems to be integer value and you are storing
//null here. I think it it should be
//`editor.putString("NewuserScore1", newUsrScore1);`
editor.putString(newUserScore1, null);
//#Praful: call commit here
editor.commit;
//getting it and displaying it on the UI
SharedPreferences peepsScores2 = PreferenceManager.getDefaultSharedPreferences(this);
String userScore11 = peepsScores2.getString("NewuserScore1",null);
pScore1.setText(" "+userScore11);
This line
editor.putString(newUserScore1, null);
should be
editor.putString("NewuserScore1",newUserScore1);
and also don't forget to commit your changes using editor.commit();
Whenever you working with SharedPreference never forget to call commit() to save your changes.
SharedPreferences.Editor editor = peepsScores2.edit();
editor.putString("NewuserScore1", newUserScore1);
editor.commit();

Categories

Resources