我已经成功实施了一个具有历史记录活动的计算器,它将在列表视图中显示旧结果 但我面临的问题是第一行始终为空
我试图制作默认字符串“Old Calculation”
> 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);
更新方法,其中我用String 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();
}
}
}
答案 0 :(得分:0)
当您存储来自活动 A 的数据并且您想要从其他活动中检索数据时,您必须使用SharedPreferences
,如下所示:
SharedPreferences prefs = getSharedPreferences(String, int);
String
是FileName,如“result”
int
的模式类似于 MODE_PRIVATE
例如,请参阅this link
另外我wrote a simple code寻求帮助