我在Android上创建了一个共享首选项屏幕,用于从共享首选项屏幕接收信息到主屏幕,每件事情都运行正常,但是首选项屏幕中的值没有保存,每次我必须打开共享首选项屏幕并键入信息手动...任何建议自动保存首选项?
这是共享的perefrence代码:
Button b1 = (Button)findViewById(R.id.SavePreff);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String ID_NO = ID_NUMBER.getText().toString();
SharedPreferences prefsExample = getSharedPreferences(PREFS, 0);
SharedPreferences.Editor editor = prefsExample.edit();
editor.putString("idNumber", ID_NO);
if (rd1.isChecked())
editor.putString("Network", "STC");
else if (rd2.isChecked())
editor.putString("Network", "Mobily");
else
editor.putString("Network", "Zain");
editor.commit();
Intent i = new Intent(SharedPref.this , MainActivity.class);
startActivity(i);
}
});
这是我正在使用其中信息的主要活动屏幕:
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences example = getSharedPreferences(PREFS, 0);
String ID_NUM = example.getString("idNumber", "123432");
String NETWORK = example.getString("Network", "STC");
String called_num = "";
if (NETWORK.equals("Mobily"))
called_num = "*1400*" + CODE_CHARGE.getText().toString() + "*"+ ID_NUM+ Uri.encode("#");
else if (NETWORK.equals("STC"))
called_num = "*155*" + CODE_CHARGE.getText().toString() + "*"+ ID_NUM+ Uri.encode("#");
else if (NETWORK.equals("Zain"))
called_num = "*141*" + ID_NUM + "*"
+ CODE_CHARGE.getText().toString()+ Uri.encode("#");
Intent i = new Intent("android.intent.action.CALL");
Uri data = Uri.parse("tel:" + called_num);
i.setData(data);
startActivity(i);
}
});
答案 0 :(得分:0)
共享偏好设置就像这两个
//example1 for Shared Prefs that lasts forever
example1= PreferenceManager.getDefaultSharedPreferences(this);
//example for Shared Prefs that lasts only just once each time program is running
example2= getApplicationContext().getSharedPreferences("PREFS", Activity.MODE_PRIVATE);
在您的代码中,使用
example1= PreferenceManager.getDefaultSharedPreferences(this);
希望这对你有用..