I wrote some test code to learn how to use SharedPreferences. The app saves data fine, but when I ran the application again by pressing “run” on eclipse, the console window said it was uploading, installing, and starting the application. Since it said installing again, I was expecting the data stored with SharedPreferences to be deleted. However, the old data was still displayed when i went into the activity.
My program runs like this:
- splash screen
- list menu activity with 3 activity options
- the target activity where i implemented the saving function
Here is my code for that specific activity:
public class StartingPoint extends Activity {
/** Called when the activity is first created. */
int counter;
Button add;
Button sub;
TextView display;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter=0;
add= (Button) findViewById(R.id.bAdd);
sub= (Button) findViewById(R.id.bSub);
display= (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText(""+counter);
display.setTextSize(counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
display.setText(""+counter);
display.setTextSize(counter);
}
});
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
SharedPreferences prefs = getPreferences(0);
int getfromfile = prefs.getInt("counter_store", 1);
counter=getfromfile;
display.setText(""+getfromfile);
display.setTextSize(getfromfile);
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putInt("counter_store", counter);
editor.commit();
}
}
Re-running the application from Eclipse is akin to doing an upgrade on the app in production. All data associated with the app is left intact.
You can clear out the old data in the emulator by the same means as you would use on a phone, via the Settings application and its Applications screen.