Using Shared Preferences for High Score saving - android

Hell I am trying to make highscore for my project but my code is only saving last value not highest value
How can I store only highest value? here is my code .
This is saving process ->
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
TextView outputView = (TextView)findViewById(R.id.textscore);
CharSequence textData = outputView.getText();
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
This is Reading process
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
String textData = prefs.getString(TEXT_DATA_KEY, "No Preferences!");
TextView outputView = (TextView) findViewById(R.id.textread);

You need to check the previously saved value to see which is highest else it you will just save the latest value, not the highest
E.g.
if (textData != null) {
int score = Integer.parseInt(textData.toString());
if(score > prefs.getInt(TEXT_DATA_KEY, 0)) // Or get String, with parse Int.
{
//editor.putString(TEXT_DATA_KEY, textData.toString()); // Should be saved as int
editor.putInt(TEXT_DATA_KEY, score);
editor.commit();
}
}

You need to store a new value only if the existing value in shared preferences is lesser than the new value.
You don't seem to be having this value check in your code

Replace
if (textData != null) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
with
if (textData != null) {
if(Integer.parseInt(prefs.getString(TEXT_DATA_KEY, "0")) < Integer.parseInt(outputView.getText())) {
editor.putString(TEXT_DATA_KEY, textData.toString());
editor.commit();
}
}

First of all why are you saving high scrore as string, use int or float (if you must).
The simplest way is to read high score before saving it and compare to the one you try to save.

You'll want to keep track of your in-game high score. That's easiest done using a number rather than using a text view's string:
int hiScore = 0;
In your startup, perhaps in onCreate(), you'll want to obtain the previous high score:
SharedPreferences prefs = getSharedPreferences(MY_PREFERENCES, Context.MODE_PRIVATE);
try {
hiScore = prefs.getInt(HI_SCORE, 0);
} catch (NumberFormatException e) {
hiScore = 0;
}
When a new score is obtained, you'll want to record it if it's higher than the previous high score:
if (newScore > hiScore) {
hiScore = newScore;
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HI_SCORE, hiScore);
editor.commit();
}

Related

Similar like Php session for Android Studio

I'm newbie for Android Studio & Java, i'm PHP user.
Just want to know how to do like PHP session in Android Studio.
No matter which Activity i go to, i can easily get the session value example like the User ID. (session["USERID"])
now the method i using is putting extra everytime i call for another activity.
i'm sure there will be a better way to do this.
anyone have any good suggestion?
PS: I google around and it keep return me PHP session tutorial/example/etc but not for Android Studio....(may be i enter work #keyword or sentence)
Thank You Very Much
Thanks to fillobotto & Arshid KV
here is my code
first_main activity
sharedpreference = getSharedPreferences(BIZInfo, Context.MODE_PRIVATE);
sharedpreference.edit().putString(userid, "12345");
sharedpreference.edit().commit();
second_main activity
sharedpreference = PreferenceManager.getDefaultSharedPreferences(this);
String restoredText = sharedpreference.getString("text", null);
if (restoredText != null) {
sp_name = sharedpreference.getString("userid", "No name defined");
}
Log.i("TAG", "onCreate: [" + sp_name + "]");
log show empty value/nothing...
what went wrong!?
You can use SharedPreferences as session in php
Demo code :-
Setting values in Preference:
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("name", "Arshid");
editor.putInt("Age", 22);
editor.commit();
Retrieve data from preference:
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String name = prefs.getString("name", "No name defined");//"No name defined" is the default value.
int Age = prefs.getInt("Age", 0); //0 is the default value.
}
You were really near to the solution. This is what I use:
public static String getSession(Activity context) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
return sharedPreferences.getString("session", null);
}
public static void setSession(Activity context, String session) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("session", session);
editor.apply();
}
I'm actually passing the Activityto get SharedPreferences, but in this way you will obtain an instance of the object which is not activity-related.

How to store and retrieve integer using Android Shared Preferences

I am trying to save an integer value and retrieve the value using a same button using shared preferences.
To be more precise, when i click a button the value should be incremented(i++) and then it should be stored. When i close and open the application, it should retrieve the same value from where i left it. How do i do this?
I am using eclipse.
This works for me
public class OnPreferenceManager {
private SharedPreferences.Editor editor;
private SharedPreferences prefs;
private String startHour = "startHour";
private OnPreferenceManager() {}
private OnPreferenceManager(Context mContext) {
prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
editor = prefs.edit();
}
public static OnPreferenceManager getInstance(Context mContext)
{
OnPreferenceManager _app = null;
if (_app == null)
_app = new OnPreferenceManager(mContext);
return _app;
}
public void setStartHour(int hour){
editor.putInt(startHour, hour);
editor.apply();
}
public int getStartHour(){
int selectionStart = prefs.getInt(startHour, -1);
return selectionStart;
}
}
When you need to set integer just write as below
OnPreferenceManager.getInstance(this).setStartHour(theValueYouWantToStore);
And to retrieve write
OnPreferenceManager.getInstance(this).getStartHour()
You can use shared preferences as below.
//To save integer value
SharedPreferences preference = getSharedPreferences("YOUR_PREF_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YOU_KEY",you_int_value);
editor.commit();
//To retrieve integer value
SharedPreferences settings = getSharedPreferences("YOUR_PREF_NAME", 0);
int snowDensity = settings.getInt("YOU_KEY", 0); //0 is the default value
Check this gist https://gist.github.com/john1jan/b8cb536ca51a0b2aa1da4e81566869c4
I have created a Preference Utils class that will handle all the cases.
Its Easy to Use
Storing into preference
PrefUtils.saveToPrefs(getActivity(), PrefKeys.USER_INCOME, income);
Getting from preference
Double income = (Double) PrefUtils.getFromPrefs(getActivity(), PrefKeys.USER_INCOME, new Double(10));

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..

Check if key exists in Shared Preferences

I'm creating Shared Preferences as follows
preferences = getSharedPreferences("text", 0);
final Editor editor = preferences.edit();
String s1 = serverIP.getText().toString();
String s2 = serverPort.getText().toString();
String s3 = syncPass.getText().toString();
String s4 = proxyServer.getText().toString();
String s5 = proxyPort.getText().toString();
editor.putString("SERVERIP", s1);
editor.putString("SERVERPORT", s2);
editor.putString("SYNCPASS", s3);
editor.putString("PROXYSERVER", s3);
editor.putString("PROXYPORT", s3);
and onCreate I want to display the values in a new set of TextViews, but the first time I don't have any values stored in the shared preferences and will get a NULL Pointer exception.
I want to know if there is any built-in method which can check if the SharedPreferences contains any value or not, so that I can check if the key exists and if not, then replace the new set of TextViews with the preferences value.
Try contains(String key) Accorting to the Javadocs,
Checks whether the preferences contains a preference. Returns true if
the preference exists in the preferences, otherwise false.
Every method for fetching values from SharedPreferences has default value which is returned in case the key does not exist
preferences = getSharedPreferences("text", 0);
String value = preferences.getString("unknown_key",null);
if (value == null) {
// the key does not exist
} else {
// handle the value
}
Try out
SharedPreferences shf = getSharedPreferences("NAME_SharedPref", MODE_WORLD_READABLE);
String strPref = shf.getString("SERVERIP", null);
if(strPref != null) {
// do some thing
}
I know this is a late answer but for those who want to know if a shared preference is either empty or zero size, you can check it two ways.
preferences = getSharedPreferences("text", 0);
Map<String, ?> entries = preferences.getAll();//get all entries from shared preference
Set<String> keys = entries.keySet();//set all key entries into an array of string type
//first option
if(keys.isEmpty()){
//do your staff here
}
//second option
if(keys.size()==0){
//this shows that it is empty as well
//do your staff here
}
//Below is extra
//If you want to get the names of each keys also, you can use
//For each loop as well
//Go through the set of keys
for (String key : keys) {
String keyName = key;//get each key name
}
LoadRuns();
if (loadedruns == 1) {
Toast.makeText(MainActivity.this, "First run", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(MainActivity.this, "No. runs: " + loadedruns,
Toast.LENGTH_SHORT).show();
}
loadedruns++;
SaveRuns("runs", loadedruns);
public void SaveRuns(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadRuns(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
loadedruns = sharedPreferences.getInt("runs", 1);
}

Categories

Resources