private RadioGroup rgTravel;
SharedPreferences sharedPreferences;
private static final String PREFS = "PREFS";
private static final String Travel = "travel";
private RadioButton radioButton;
String travel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
final Button btnOk = (Button)findViewById(R.id.btnOk);
btnOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent activity3 = new Intent(MainActivity2Activity.this, MainActivity3Activity.class);
rgTravel = (RadioGroup) findViewById(R.id.rgTravel);
int selectedId = rgTravel.getCheckedRadioButtonId();
radioButton = (RadioButton) findViewById(selectedId);
travel = radioButton.getText().toString();
SharedPreferences preferences-= PreferenceManager.getDefaultSharedPreferences(MainActivity2Activity.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(Travel, travel);
editor.commit();
Toast.makeText(getApplicationContext(), travel, Toast.LENGTH_LONG).show();
startActivity(activity3);
}
});
}
这是我的活动2,我应该创建共享偏好,并保存用户的选择。 (我想在一个radiogroup中保存用户的选择) 请参阅我的活动3,我应该回到这个选择:
public void onCreate(Bundle savedInstanceState) {
String choice;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
SharedPreferences PREFS = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
choice = PREFS.getString("Travel", "Beach");
Toast.makeText(getApplicationContext(), choice, Toast.LENGTH_LONG).show();
displayPicture(choice);
Button next = (Button) findViewById(R.id.button3);
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent activity4 = new Intent(MainActivity3Activity.this, MainActivity4Activity.class);
startActivity(activity4);
}
});
}
我已在每个活动中创建了一个Toast,以确保问题确实与首选项有关,而不是另一个步骤。
答案 0 :(得分:5)
它应该是travel
而不是Travel
,因为它区分大小写
在下一个活动中使用
choice = PREFS.getString("travel", "Beach");
而不是
choice = PREFS.getString("Travel", "Beach");