Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 444
bad_keypoints Avatar asked Oct 28 '25 10:10

bad_keypoints


2 Answers

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);
like image 137
Chirag Avatar answered Oct 30 '25 02:10

Chirag


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
like image 32
Warpzit Avatar answered Oct 30 '25 02:10

Warpzit