在android中使用共享首选项保存数据 [英] save the data using shared preference in android
本文介绍了在android中使用共享首选项保存数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 android 应用程序的新开发人员.我想使用共享首选项概念保存数据.我将数据保存在一个活动中并在另一个活动中获取相同的数据.这里我想发送字符串 a[]={"one","two","three"} 一个活动到另一个活动.我写的代码如下
i am new developer in android applications.i would like to save the data using shared preference concept.i am saving the data in one activity and get the same data in another activity.here i would like to send the String a[]={"one","two","three"} one activity to another activity.i have written code as follows
Main1.java
public class Main1 extends Activity
{
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences shp=getSharedPreferences("TEXT", 0);
final Editor et=shp.edit();
((Button)findViewById(R.id.button1)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String s1=((EditText)findViewById(R.id.editText1)).getText().toString();
et.putString("DATA", s1);
String s2[]={"one","two","three"};
//here i would like to save the string array
et.commit();
Intent it=new Intent(Main1.this,Main2.class);
startActivity(it);
}
});
}
Main2.java
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
String kk=getSharedPreferences("TEXT", 0).getString("DATA", null);
//here i would like to get the string array of Main1.java
((EditText)findViewById(R.id.editText1)).setText(kk);
}
我们可以从 Main1.java 到 Main2.java 获取字符串数组值吗?
can we get the string array values from Main1.java to Main2.java?
推荐答案
放到开始的意图中:
Intent it = new Intent(Main1.this,Main2.class);
it.putExtra("MY_STRING_ARRAY", s2);
在第二个活动中取回:
String[] myStringArray = getIntent().getStringArrayExtra("MY_STRING_ARRAY");
这篇关于在android中使用共享首选项保存数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文