【发布时间】:2015-01-11 23:39:29
【问题描述】:
我正在尝试将一个值作为字符串保存在设备的内存中,以便在应用程序关闭并通过单击另一个按钮重新打开时可以访问它。当我运行程序时,我为输入 A 和 B 输入值,我知道它会通过计算处理它们,因为我对其进行了修改,以便它在计算后立即显示答案。 但是在这个版本中,如果我单击保存按钮,然后单击访问按钮以显示答案和标记为上一个答案的文本视图,它只会显示“xx”,这是我试图保存的字符串的初始值。所以要么它不存储包含答案的更新版本,要么访问按钮只能访问字符串的原始值。
Button jSave = (Button) findViewById(R.id.iSave);
Button jAccess = (Button) findViewById(R.id.iAccess);
final String saveName="Name";
final String saveValue = "xx";
jSave.setOnClickListener(
new Button.OnClickListener(){
public void onClick(View v){
//Calculations. These are a part of a more complex series of
//calculations between several classes, but I've simplified it
//somewhat for this post.
EditText jInputA = (EditText)findViewById(R.id.iInputA);
double dInputA = Double.parseDouble(jInputA.getText().toString());
EditText jInputB = (EditText)findViewById(R.id.iInputB);
double dInputB = Double.parseDouble(jInputB.getText().toString());
double myAnswer = Double.parseDouble(ProfileCalculations.functionQ(jInputA, jInputB));
//Update the value of saveValue to match that of myAnswer
final String saveValue = "The answer is " myAnswer;
//Save saveValue as a string under file saveName
try{
FileOutputStream jFOS = openFileOutput(saveName, Context.MODE_PRIVATE);
jFOS.write(saveValue.getBytes());
jFOS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
);
jAccess.setOnClickListener(
new Button.OnClickListener() {
public void onClick(View v) {
try {
FileInputStream jFIS = openFileInput(saveName);
jFIS.read(saveValue.getBytes());
jFIS.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Profile.class.getName()).log(Level.SEVERE, null, ex);
}
TextView jPreviousAns = (TextView) findViewById(R.id.iPreviousAns);
jPreviousAns.setText(saveValue + "");
}
}
);
【问题讨论】:
-
不确定,至于您的文件处理...我太新了。但是,你为什么不使用共享偏好?这似乎是他们使用的教科书案例。
标签: java android string methods save