how to implement SharedPreferences

Put your problem here if it does not fit any of the other categories.

how to implement SharedPreferences

Postby Cereal Killer » Wed Mar 07, 2012 12:48 pm

Hello,

I'm fairly new to Android. As one of my first applications (other than Hello World), I've been developing an application that counts how many times you've pressed a button. That's all. I've managed to do this, but now I want to autosave the amount of button presses on exit. So what I'm trying to do is make sure that when the application is closed, the amount of button presses is saved, so you start with that number on the next startup. I've heard something about using SharedPreferences, but I'm having trouble finding out how to implement this. It would be a tremendous help if any of you could help me out with this.
User avatar
Cereal Killer
Freshman
Freshman
 
Posts: 4
Joined: Sun Mar 04, 2012 3:38 pm

Top

Re: how to implement SharedPreferences

Postby nuetronprotron » Wed Mar 07, 2012 1:22 pm

H Cereal,
I think u can get lot on this topic in developer.android.com
here is the link http://developer.android.com/guide/topi ... .html#pref
i Hope this will start your journey
nuetronprotron
Developer
Developer
 
Posts: 37
Joined: Tue Jan 10, 2012 10:22 am

Re: how to implement SharedPreferences

Postby Phyll » Wed Mar 07, 2012 9:15 pm

Hi Cereal Killer,

Here are a couple of simple methods to save and retrieve a preference like that:

Code: Select all
    //global constants and prefs variable
    public static final String PRESSES = "press_count";
    SharedPreferences prefs;
    int pressCount = 0;

    //in onCreate()
    prefs = PreferenceManager.getDefaultSharedPreferences(this);

    //save and retrieve methods
    private void getMyPreferences() {
        pressCount = prefs.getInt(PRESSES, 0);
        }//getpreferences

    private void savePreferences() {
        Editor editor = prefs.edit();
        editor.putInt(PRESSES, pressCount);
        editor.commit();
        }//savepreferences


Hope this helps.

Phyll
Phyll
Master Developer
Master Developer
 
Posts: 648
Joined: Fri Oct 14, 2011 11:19 am

Top

Return to Other Coding-Problems

Who is online

Users browsing this forum: No registered users and 16 guests