我是新來的android編程,我只是想使用共享首選項將一些數據從一個活動發送到另一個活動,但我的代碼不起作用。Android - 使用共享首選項不工作發送數據
這是我在輸入數據的活動。
public class MainActivity extends ActionBarActivity {
private Button BTN;
private EditText EDTXT,EDTXT2,EDTXT3;
private CheckBox CHKBX;
private final String mName = "Middle Name";
private final String fName = "First Name";
private final String lName = "Last Name";
private final String isReg = "Is Registered";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BTN=(Button)findViewById(R.id.button);
CHKBX=(CheckBox)findViewById(R.id.checkBox);
EDTXT=(EditText)findViewById(R.id.editText);
EDTXT2=(EditText)findViewById(R.id.editText2);
EDTXT3=(EditText)findViewById(R.id.editText3);
BTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(CHKBX.isChecked()){
setPreferenceData();
Intent INT = new Intent(MainActivity.this,SharedPreferenceData.class);
startActivity(INT);
}
}
});
}
public void setPreferenceData(){
SharedPreferences sp = this.getSharedPreferences("MyPref",MODE_WORLD_READABLE);
SharedPreferences.Editor spEditor = sp.edit();
spEditor.putBoolean(isReg, CHKBX.isChecked());
spEditor.putString(fName, EDTXT.getText().toString());
spEditor.putString(mName, EDTXT2.getText().toString());
spEditor.putString(lName, EDTXT3.getText().toString());
spEditor.commit();
}
這是我想要的數據傳遞活動。
public class SharedPreferenceData extends ActionBarActivity {
private TextView TXTVW,TXTVW1,TXTVW2,TXTVW3;
private final String fName = "First Name";
private final String mName = "Middle Name";
private final String lName = "Last Name";
private final String isReg = "Is Registered";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shared_preference_data);
TXTVW = (TextView) findViewById(R.id.textView);
TXTVW1 = (TextView) findViewById(R.id.textView2);
TXTVW2 = (TextView) findViewById(R.id.textView3);
TXTVW3 = (TextView) findViewById(R.id.textView4);
getSharedPreferencesData();
}
public void getSharedPreferencesData(){
SharedPreferences spf = this.getSharedPreferences("My Pref",MODE_WORLD_READABLE);
TXTVW.setText("First Name:" + spf.getString(fName,""));
TXTVW1.setText("Middle Name:" + spf.getString(mName,""));
TXTVW2.setText("Last Name:" + spf.getString(lName,""));
TXTVW3.setText("Is Registered:" + spf.getBoolean(isReg,true));
}
爲什麼您的偏好名稱不同(「MyPref」與「My Pref」)?你爲什麼使用'MODE_WORLD_READABLE'? – tachyonflux 2015-02-23 18:42:33