问题
I have created a radio group which contains two buttons, I can select one and save it, it works fine, still stored after closing the app. What I want to do is use the value of the radio buttons in another class. Here is my settings class which contains the shared preferences code:
public class Settings extends Activity {
private String settingsTAG = "AppNameSettings";
private SharedPreferences prefs;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
prefs = getSharedPreferences(settingsTAG, 0);
final RadioButton rb0 = (RadioButton) findViewById(R.id.radioInternetYes);
final RadioButton rb1 = (RadioButton) findViewById(R.id.radioInternetNo);
rb0.setChecked(prefs.getBoolean("rb0", true));
rb1.setChecked(prefs.getBoolean("rb1", false));
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
prefs = getSharedPreferences(settingsTAG, 0);
Editor editor = prefs.edit();
editor.putBoolean("rb0", rb0.isChecked());
editor.putBoolean("rb1", rb1.isChecked());
editor.commit();
finish();
}
} );
}
In another class I am trying to check if rb0 is true or false when clicking a button:
share.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
if(rb0 = true){
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{""});
i.putExtra(Intent.EXTRA_SUBJECT, "Check out my awesome score!");
i.putExtra(Intent.EXTRA_TEXT , "I am playing this awesome game called Tap the Button, and I just scored the incredible highscore of " +s+ " Taps!!\n\nCan you beat it!?");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(FailScreen.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
else{
//Display warning that rb0 is false
}
}
});
I have researched Stackoverflow and the developer documentation, but I cant seem to find out how this can be done, any advice is appreciated.
Thank you
回答1:
Instead of if(rb0 = true)
(which should be ==
anyways), you need to access the SharedPreferences again. Quoted from http://developer.android.com/guide/topics/data/data-storage.html:
To read values, use SharedPreferences methods such as getBoolean() and getString().
So you would use something like:
String settingsTAG = "AppNameSettings";
SharedPreferences prefs = getSharedPreferences(settingsTAG, 0);
boolean rb0 = prefs.getBoolean("rb0", false);
if(rb0 == true){
// Do something
}
回答2:
You can also use:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getBoolean("myKey", false)
来源:https://stackoverflow.com/questions/10606237/how-to-access-shared-preference-boolean-value-from-another-class