SharedPreference存储
1、SharedPreferences
是一种轻型的数据存储方式。本质是基于XML文件存储的键值对数据。通常用来存储一些简单的配置信息。
提供了一些基础的信息保存功能,所有的信息都是按照“key-value”的形式保存的,所保存的只能是些基本类型。
sharedPreference对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现的。
保存文件的步骤:
1、得到SharedPreferences对象
2、调用SharedPreferences 对象的edit()方法来获取一个SharedPreferences.Editor 对象, 使SharedPreferences可读写。
3、向SharedPreferences.Editor 对象中添加数据。
4、调用commit()方法将添加的数据提交,从而完成数据存储操作。
保存文件:
<span style="font-size:14px;">public class MainActivity extends Activity {
private static final String NAME="file";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//1、获得SharedPreferences对象
SharedPreferences file=getSharedPreferences(NAME, Activity.MODE_PRIVATE);
//2、使对象处于可编辑状态
SharedPreferences.Editor ed=file.edit();
//3、添加数据
ed.putString("name", "zh");
ed.putInt("age",23);
//4、提交
ed.commit();
</span>}
}
读取文件:只需调用一系列的get方法即可。
<span style="font-size:14px;">public class MainActivity extends Activity {
private static final String NAME="file";
private TextView text1,text2;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1=(TextView) findViewById(R.id.text1);
text2=(TextView) findViewById(R.id.text2);
//找到.xml文件
SharedPreferences getShared=getSharedPreferences("file",Activity.MODE_PRIVATE);
//使用get方法得到数据
String name=getShared.getString("name","没找到数据");
Integer age=getShared.getInt("age", 0);
String ages=age.toString();
text1.setText(name);
text2.setText(ages);
}
}</span>