Search code examples
javaandroiddatabasepreferencesshared

How to use shared Preferences on Android?


I am creating a very simple application that only has a seek bar that the user can use. My code looks like this :

    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    int number=50;
    SeekBar sb = (SeekBar)findViewById(R.id.slider);
    sb.setMax(100);
    sb.setProgress(number);
    sb.setOnSeekBarChangeListener(this);
}

@Override
public void onProgressChanged(SeekBar v, int progress, boolean isUser) {
    TextView tv = (TextView)findViewById(R.id.percent);
    tv.setText(Integer.toString(progress)+"%");


}

What i want to do is store the seek bars state and when the application is killed and the user opens it again , the last change is displayed on the seek bar and not the default. So i must use shared preferences on my int number variable? I cant understand how i can do that since when the application starts again the line int number=50 will be run again , so the value will go to 50 again.


Solution

  • something like this ought to work:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        SharedPreferences sp;
        SharedPreferences.Editor spe;
    
    
        sp = PreferenceManager.getDefaultSharedPreferences(this);
        spe = sp.edit();
    
    
        int number= sp.getInt("seekNum", 50);
        SeekBar sb = (SeekBar)findViewById(R.id.slider);
        sb.setMax(100);
        sb.setProgress(number);
        sb.setOnSeekBarChangeListener(this);
    }
    
    @Override
    public void onProgressChanged(SeekBar v, int progress, boolean isUser) {
        TextView tv = (TextView)findViewById(R.id.percent);
        tv.setText(Integer.toString(progress)+"%");
    
    
    }
    
    
    @Override
    public void onStop(){
        super.onStop();
    
        spe.putInt("seekNum", sb.getProgress());
        spe.commit();
    }