简体   繁体   中英

How to save a int with SharedPreferences?

I looked up a lot of tutorials on how to save int variables, but I couldn't find good example for me. My code looks like this:

package com.example.countryclicker;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity; 
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity {
    int exp,level,count,totalCount;
    Button mainButton;
    TextView current,total;
    SharedPreferences pref;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mainButton = (Button) findViewById(R.id.button1);
        current = (TextView) findViewById(R.id.TcurrentCount);
        total =  (TextView) findViewById(R.id.TtotalCount);
        mainButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                count+=1;
                current.setText("Your current count is "+ count);
                totalCount = count;
                total.setText("Your total count is " + totalCount);
            }
        });
    }  


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

So, I have an integer counter, which increases everytime I click a button, but I want that whenever that user clicks that button,a program saves a value to some other integer and that value would still remain even if users closes an app.

If I understood correctly what you need to do is :

  • when you click the button, get the int value from the shared preferences first, it if does not exist, create it
  • increment the value by one
  • save this value to the SharedPreferences again

So it would translate to something like that:

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    int totalCount = mySharedPreferences.getInt("INT_KEY", -1);
    if(totalCount == -1) {
       totalCount = 0; //initialize the total count value to 0
    }
    count += 1;
    totalCount += 1;
    SharedPreferences.Editor editor = mySharedPreferences.edit();
    editor.putInt("INT_KEY", totalCount);
    editor.commit();
    current.setText("Your current count is "+ count);
    total.setText("Your total count is " + totalCount);
}

For more efficiency, get the totalCount value from the SharedPreferences when you start the app and save it to the SharedPreferences before you finish your activity.

You can read the android doc of the SharedPreferences class for more informations.

Put the following code inside your onClick() method for your button.

 SharedPreferences sharedPref = getActivity()
                                .getPreferences(Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedPref.edit();
    editor.putInt("variableName", count);
    editor.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM