Android: persist instance state across multiple sessions

Android: persist instance state across multiple sessions 

freyo
JOINED:
07/27/2010
POSTS:
122
 (Not rated)
July 21, 2011 15:53:47     Last update: July 21, 2011 15:53:47
Use  SharedPreferences to persist an instance state. The state is saved even when the app is killed. 
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
        
    powerStatus = prefs.getString("power", "On");
    RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
    int n = rg.getChildCount();
    for (int i = 0; i < n; i++) {
	RadioButton rb = (RadioButton) rg.getChildAt(i);
	if (powerStatus.equals(rb.getText().toString())) {
	    rg.check(rb.getId());
	    break;
	}
    }
}
      
public void setValues(View view) {
    RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup1);
    powerStatus = ((RadioButton) findViewById(rg.getCheckedRadioButtonId())).getText().toString();
        
    SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);

    // Use Editor to change values
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("power", powerStatus);
 
    // do not forget to commit the changes!
    editor.commit();
}
Share |
|  Comment  |  Tags
 

你可能感兴趣的:(android,RadioButton,2010)