How to make a persistent counter variable in an Android app? - android

I'm just starting out.
I'm trying to increment a simple counter, every time I run the project on the emulator.
I thought adding an integer type item in strings.xml would help, but that's final, and can't be modified.
Basically I'd just display in my app's first basic screen:
Started: N where N would be the Nth time I've launched the project from Eclipse.
How can I make such a counter that's persistent across application launches and exits?
Got it:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
int tempN=pref.getInt("N", 0);
tempN++;
SharedPreferences.Editor editor = pref.edit();
editor.putInt("N",tempN);
editor.commit();
msgBox.setText("Started:"+tempN);
One thing I still don't understand, that when I call pref.getInt("N",0), is the key-value pair <N,0> automatically created?

You can use shared preference for that . You can store integer number in shared preference and get value of it when ever you want.
Try this.
SharedPreferences prefs = getSharedPreferences("Share", Context.MODE_PRIVATE );
Editor editor = prefs.edit();
editor.putInt("Value", 1 );
editor.commit();
for get value
prefs.getInt("Value",0);

In your main activity onCreate():
SharedPreferences pref = this.getSharedPreferences();
int count = pref.getInt("your key", 0) //0 is default value.
count++;
SharedPreferences.Editor edit = pref.edit();
edit.putInt("your key", count);
edit.commit();
// display current count

Related

Sharedpreferences: can't get the saved value updated in separate methods

I am writing a game app where I need to save the best score and get it back next time a user plays it. So saving happens when the player dies and retrieving (Read) happens when the game starts again: both are in separate methods.
Save:
SharedPreferences myPrefs = getContext().getSharedPreferences(HIGH, Context.MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = myPrefs.edit();
prefsEditor.putInt(HIGHSCORE, best);
prefsEditor.commit();
Read:
SharedPreferences myPrefs = getContext().getSharedPreferences(HIGH, Context.MODE_PRIVATE);
int highestScore = myPrefs.getInt(HIGHSCORE, 1);
best=highestScore;
As you can see the default value when the highestscore is retrieved is 1. But I always end up getting 1! So may be the saving is not happening correctly. Please help. Thanks.

How to share 1 SharedPreferences file between 2 activities

I have got a SharedPreferences file in my Activity1.
void saveDays(){
Log.w(TAG, "Start saveDays");
SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit();
editor.putInt("Days", days);
editor.commit();
}
Then I need to use days in my Activity2. So how can I load it?
In Activity2, where you want to get access to that preference:
int days = getPreferences(MODE_PRIVATE).getInt("Days", DEFAULT_DAY);
Where DEFAULT_DAY is the default value to use if there is no "Days" preference available.
You want to name the preferences and access them with that name in both
SharedPreferences prefs =
getSharedPreferences("myPrefs", MODE_PRIVATE);
And then its as simple as retrieving the int...
int days = prefs.getInt("Days", 1);

Android: Retrieve int saved in PreferenceManager getDefaultSharedPreferences in another activity

I am trying to save data using default Shared Preferences, but cannot get this code working.
I cant retrieve an int value in another activity.
In my first activity, in onCreate, I want to create a scorecounter that counts up every time you receive points. It will be initiated on first run.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
if (preferences.getBoolean("first_run", true))
{
editor.putInt("totalpoang", 0);
editor.commit();
preferences.edit().putBoolean("first_time", false);
}
In my Activity B I want to retrieve the value, modify it, and then save it in preferences again.
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int poang = preferences.getInt(totalpoang, 0);
editor.putInt("antalpoang", totalpoang);
editor.commit();
However I only get the error totalpoang cannot be resolved as a variable.
I initialized it as a int in the first Activity, and I am trying to retrieve it as an int.
What am I doing wrong?
Change this
int poang = preferences.getInt(totalpoang, 0);
//editor.putInt("totalpoang", 0); // key is "totalpoang"
to
int poang = preferences.getInt("totalpoang", 0);
And then
editor.putInt("antalpoang", poang);

Android SharedPreferences , how to save a simple int variable [duplicate]

This question already has answers here:
How to use SharedPreferences in Android to store, fetch and edit values [closed]
(30 answers)
Closed 9 years ago.
I am trying for the last hour to save an integer in my Android application. I read that this can be done using the SharedPreferences. However i dont understand why it seems so confusing to do so.
How can i simply save an int variable ? And then when i run the application again , how can i interact with this variable again?
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putInt("your_int_key", yourIntValue);
editor.commit();
the you can get it as:
SharedPreferences sp = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE);
int myIntValue = sp.getInt("your_int_key", -1);
The SharedPreference interface gives you access to the an xml file, and a easy way to modify it through its editor. The file is stored in /data/data/com.your.package/shared_prefs/ and you can access it onlu through this SharedPreference API
public void SaveInt(String key, int value){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(key, value);
editor.commit();
}
public void LoadInt(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
savedValue = sharedPreferences.getInt("key", 0);
}
If you want to save the variable somewhere, you have to write SaveInt("key", 5); With this you will save the value 5, while the first default value is 0. If you want to load it and use it in another activity, you have to write both of these methods there, and call LoadInt(); where you need the variable. The savedValue is a predefined integer (this needs to be declared everywhere you would like to use the saved variable)
This is the example of setting Boolean preferences. You can go with Integer also.
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("firstTime", false)) {
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("firstTime", true);
editor.commit();
}
Hope this might be helpful.

how to fix the Pop up 's count?

In my app, i am starting a service in Mainactivity. I show a reminder popup everytime the app is opened. But, I only want to show the pop up 1 time.
How to store the pop up's count accros multiple app launches?
boolean mboolean = false;
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
mboolean = settings.getBoolean("FIRST_RUN", false);
if (!mboolean) {
// do the thing for the first time
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("FIRST_RUN", true);
editor.commit();
} else {
// other time your app loads
}
This code will show something only once, untill you dont reinstall app or clear app data
EXPLANATION:
OK, I'll explain it to you. SharedPreferences are like a private space of your application in which you can store primitive data (strings,int,boolean...) that will be saved untill you dont delete application. My code above works like this, you have one boolean which is false when you start the application, and you will show your popup ONLY if the boolean is false --> if (!mboolean). Once you showed your pop up, you put the boolean value to true in sharedPreferences, and system will next time check there, see that it is true and wont show the pop up again untill you reinstall the application or clear the application data from application manager.
put this code when you push popup.
pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
if (!pref.getBoolean("popupfirst", false)) {
Editor editPref = pref.edit();
editPref.putBoolean("popupfirst", true);
editPref.commit();
}
when your app first start and you push popup then its add true in to Preference else it can't do anything.
Store it in the SharedPreferences.
E.g. to save it in your shared preferences, when showing the popup:
// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Edit the shared preferences
Editor editor = prefs.edit();
// Save '1' in a key named: 'alert_count'
editor.putInt("alert_count", 1);
// Commit the changes
editor.commit();
And afterwards, when you launch the app, you can extract it again, to check how many times it was launched before:
// Get the shared preferences
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Get the value of the integer stored with key: 'alert_count'
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value
if(timesLaunched <= 0){
// Pop up has not been launched before
} else {
// Pop up has been launched 'timesLaunched' times
}
Ideally, when you save the number of times launched in the SharedPreferences, you can first extract it, and than increment the current value.. Like so:
SharedPreferences prefs = getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
// Get the current value of how many times you launched the popup
int timesLaunched = prefs.getInt("alert_count", 0); // 0 is the default value
Editor editor = prefs.edit();
editor.putInt("alert_count", timesLaunched++);
editor.commit();

Categories

Resources