我的应用有两项活动。在这两个活动中都有EditText和Button。你在里面写了一个数字然后,按下按钮后,数字通过TextView显示。但是活动A中的数字与活动B中的数字不同,我希望保存这两个数字。
为了做到这一点,我使用了getSharedPreferences,为每个指定了一个字符串名称:
活动A:
EditText mark1;
public static final String Mark1 = "mark1Key";
TextView marksem1;
public static final String MarkSem1 = "marksem1Key";
Button calcsem1;
double mark1calc=0;
public static final String MyPREFERENCES = "MyPrefsA" ;
SharedPreferences sharedpreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.etsam_gfa_layout);
initControls();
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
mark1 = (EditText) findViewById(R.id.mark1);
if (sharedpreferences.contains(Mark1))
{
mark1.setText(sharedpreferences.getString(Mark1, ""));
}
marksem1 = (TextView) findViewById(R.id.total1calc);
if (sharedpreferences.contains(MarkSem1))
{
marksem1.setText(sharedpreferences.getString(MarkSem1, ""));
}
public static Double safeParse(String input) {
try {
return Double.parseDouble(input);
} catch (NumberFormatException e) {
return 0d;
}
}
private void initControls() {
mark1=(EditText)findViewById(R.id.mark1);
marksem1=(TextView)findViewById(R.id.total1calc);
calcsem1=(Button)findViewById(R.id.total1);
calcsem1.setOnClickListener(new Button.OnClickListener()
{public void onClick
(View v) {calcsem1();}
private void calcsem1() {
mark1calc=safeParse(mark1.getText().toString());
totalsem1=(6*mark1calc);
marksem1.setText(Double.toString(totalsem1));
marksem1.setText(String.format("%.2f", totalsem1));
}});
public void run1(View view){
Editor editor = sharedpreferences.edit();
String mark1string = mark1.getText().toString();
String marksem1string = marksem1.getText().toString();
editor.putString(Mark1, mark1string);
editor.putString(MarkSem1, marksem1string);
editor.commit();
}
}
与活动B相同,但使用公共静态最终字符串MyPREFERENCES =" MyPrefsB";
结果是,活动A可以正常工作,但活动B,当我退出应用程序并再次输入时,EditText为空(它没有保存任何东西)。
有关于此的任何想法?非常感谢你!