DroidGalaxy DroidGalaxy - 3 months ago 22
Android Question

Save value of Int (Shared Preference)

I'm new to java. I've made a counter which goes up as user holds on a button. I want the app to start with int value of where it left. I know SharedPreference is the way to go but I've no idea how to use it. I'm not sure where to put which part of SharedPreference. Thank you.

public class MainActivity extends AppCompatActivity {
Button button;
int count = 1;
TextView text;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);

button.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
count++;
text.setText(String.valueOf(count));
return false;
}
});

}


}

Answer

Add the following function to your activity

 public int getValue(String key) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        int value = sharedPref.getInt(key, 0);
        return value;
 }
 public void saveValue(String key, int value) {
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putInt(key, value);
        editor.commit();
 }

Some code added in your onCreate() method

final String key = "somekey";
count  = getValue(key); //get value from sharedPreference
button = (Button) findViewById(R.id.button);
text = (TextView) findViewById(R.id.textView);
text.setText(String.valueOf(count)); // set it first
button.setOnLongClickListener(new View.OnLongClickListener() {
    @Override
    public boolean onLongClick(View view) {
        count++;
        saveValue(key,count);
        text.setText(String.valueOf(count));
        return false;
    }
});