【发布时间】:2023-03-21 16:33:02
【问题描述】:
我已经成功实现了一个带有历史活动的计算器,它将在列表视图中显示旧结果 但我面临的问题是第一行始终为空
我尝试将默认字符串设为“旧计算”
> String w = "Old Calculation";
但这没有用, 我的应用程序将结果保存在 SharedPreferences 中的多行字符串中,并通过意图将其传递给另一个活动
>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute
在 onCreate 下,我将 String 值设置为 sharedpref
> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
w = prefs.getString("saved", null);
更新方法,其中我用字符串 s 更新结果字符串值(字符串 s 是计算结果)
> public void update(String s){
editor= getPreferences(MODE_PRIVATE).edit();
w = w
+ System.getProperty ("line.separator")
+ s
+ System.getProperty ("line.separator");
editor.putString("saved", w);
editor.apply();
}
将 W 值传递给我将在 TextView 列表中显示结果的活动
> public void History(View v){
Intent myIntent = new Intent(MainActivity.this, History.class);
myIntent.putExtra("message", w);
startActivity(myIntent);
overridePendingTransition(R.anim.anim_slide_in_left,
R.anim.anim_slide_out_left);
}
历史活动
public class History extends AppCompatActivity {
TextView tv1;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
String w ="Old calculation is showed here";
tv1 = (TextView) findViewById(R.id.tv1);
print(w);
}
public void print(String w) {
Bundle bundle = getIntent().getExtras();
w = bundle.getString("message");
tv1.setMovementMethod(new ScrollingMovementMethod());
tv1.setText(w);
}
@Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
}
public void deleteAppData(View v) {
try {
// clearing app data
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
【问题讨论】:
标签: java android sharedpreferences calculator history