我今天在这里得到了一些帮助来制作一个字符串,按下按钮后会显示:
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
它显示为:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
但我注意到这只是暂时的。一旦我离开应用程序或转到其他活动,字符串就会重置..
我的问题是:如何将本地字符串存储到真实字符串中,从而将其显示在其他活动上,甚至在应用程序关闭后也是如此?
是stringxy吗?
由于
答案 0 :(得分:1)
是stringxy吗?
否 - 这是只读的,在编译期间使用。
如何将本地字符串存储到真实字符串中,从而在其他活动中显示它,甚至在应用程序关闭后显示?
您所谈论的是持久存储。你有3个主要选项(还有其他选项,但因为这是一个非常广泛的主题,我会保持简单):
将其存储在文件中
将字符串保存到文件并在应用程序启动时或任何需要时加载它。
请参阅此SO帖子,阅读/撰写文本文件Android write file
使用SharedPreferences
此帖显示此android read/write user preferences
上的代码可能是存储简单字符串和易于编码的最佳答案。如果您启动了Activity并且没有传递意图,那么您可以从SharedPreferences加载字符串。
mTextview.setText(getIntent().getStringExtra("mytext"));
变为
final String myString = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE).getString("SOME_STRING", "Default if not found");
mTextview.setText(myString);
上述内容纯粹是为了展示并可能需要整理和改进以满足您自己的需求。
使用数据库
对你来说可能是最糟糕的选择,但值得考虑。如果您开始使用多个String或复杂选项,则SQLite将内置于Android中。
这里有一个很好的教程http://www.vogella.com/articles/AndroidSQLite/article.html
答案 1 :(得分:0)
我更喜欢使用Shared Preferences
来存储价值。
的 MainActivity.java 强> 的
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
SharedPreferences sp = getSharedPreferences("MyPrefs", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("mytext", text);
editor.commit();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
startActivity(myIntent);
}
});
的 Calculated.java 强> 的
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getSharedPreferences("MyPrefs", MODE_PRIVATE).getString("mytext",null););
}