Android应用开发SharedPreferences存储数据的使用方法
SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的就是一个key-value(键值对)SharedPreferences常用来存储一些轻量级的数据。
1、使用SharedPreferences保存数据方法如下:
//实例化SharedPreferences对象(第一步)
SharedPreferences mySharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
//实例化SharedPreferences.Editor对象(第二步)
SharedPreferences.Editor editor = mySharedPreferences.edit();
//用putString的方法保存数据
editor.putString("name", "Karl");
editor.putString("habit", "sleep");
//提交当前数据
editor.commit();
//使用toast信息提示框提示成功写入数据
Toast.makeText(this, "数据成功写入SharedPreferences!" , Toast.LENGTH_LONG).show();
执行以上代码,SharedPreferences将会把这些数据保存在test.xml文件中,可以在File Explorer的data/data/相应的包名/test.xml 下导出该文件,并查看。
2、使用SharedPreferences读取数据方法如下:
//同样,在读取SharedPreferences数据前要实例化出一个SharedPreferences对象
SharedPreferencessharedPreferences= getSharedPreferences("test",
Activity.MODE_PRIVATE);
// 使用getString方法获得value,注意第2个参数是value的默认值
String name =sharedPreferences.getString("name", "");
String habit =sharedPreferences.getString("habit", "");
//使用toast信息提示框显示信息
Toast.makeText(this, "读取数据如下:"+"\n"+"name:" + name + "\n" + "habit:" + habit,
Toast.LENGTH_LONG).show();
SharedPreferences是Android平台上一个轻量级的存储类,主要是保存一些常用的配置比如窗口状态,一般在Activity中 重载窗口状态onSaveInstanceState保存一般使用SharedPreferences完成,它提供了Android平台常规的Long长 整形、Int整形、String字符串型的保存,它是什么样的处理方式呢?SharedPreferences类似过去Windows系统上的ini配置文件,但是它分为多种权限,可以全局共享访问,android123提示最 终是以xml方式来保存,整体效率来看不是特别的高,对于常规的轻量级而言比SQLite要好不少,如果真的存储量不大可以考虑自己定义文件格式。xml 处理时Dalvik会通过自带底层的本地XML Parser解析,比如XMLpull方式,这样对于内存资源占用比较好。
这种方式应该是用起来最简单的Android读写外部数据的方法了。他的用法;’存的,保存在了什么地方。当然,如果你愿意保存其他的东西,也没有什么限制。只是在性能上不知道会有什么问题。
在Android系统中,这些信息以XML文件的形式保存在 /data/data/PACKAGE_NAME /shared_prefs 目录下。
SharedPreferencespre = getSharedPreferences("soft",Context.MODE_WORLD_READABLE);
在这里我们可以调用 activity 为我们提供的方法,这个方法有两个参数:
1). 文件名。 在这里要特别注意。 因为在Android 中已经确定了SharedPreferences 是以 xm l形式保存,所以,在填写文件名参数时,不要给定 ” .xml ”后缀, android 会自动添加 。它是采用键值对的形式保存参数。 当你需要获得某个参数值时, 按照参数的键索引即可。
2). 第二个可以理解为创建模式和之前的文件存储的模式是一样的。
Context. MODE_PRIVATE
Context.MODE_APPEND MODE_APPEND
Context.MODE_WORLD_READABLE
Context.MODE_WORLD_WRITEABLE
实验步骤
下图为测试结果
1.写资源文件strings.xml
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string name="name_str">姓名</string>
- <string name="age_str">年龄</string>
- <string name="save_str">保存</string>
- <string name="get_str">读取</string>
- </resources>
2.写布局文件main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="@string/name_text" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/nameEt"
/>
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:layout_width="50dp"
android:layout_height="wrap_content"
android:text="@string/age_text" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/ageEt"
/>
</LinearLayout>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:stretchColumns="*"
>
<TableRow >
<Button
android:id="@+id/saveBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/save_text"
android:layout_margin="10dp"
/>
<Button
android:id="@+id/readBtn"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/read_text"
android:layout_margin="10dp"
/>
</TableRow>
</TableLayout>
</LinearLayout>
3.实现保存和读取
package cn.class3g.activity;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SharedPreferencesTestActivity extends Activity implements OnClickListener {
private static final String MODE_PRIVATE = null;
Button saveBtn,readBtn;
EditText nameEt, ageEt;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViews();
}
private void findViews(){
nameEt=(EditText) this.findViewById(R.id.nameEt);
ageEt=(EditText) this.findViewById(R.id.ageEt);
saveBtn=(Button) this.findViewById(R.id.saveBtn);
readBtn=(Button) this.findViewById(R.id.readBtn);
saveBtn.setOnClickListener( this);
readBtn.setOnClickListener(this);
}
public void OnClick(View v){
String name="无名氏";
int age=-1;
SharedPreferences shared=this.getSharedPreferences("info",Context.MODE_WORLD_READABLE);//+Context.MODE_WORLD_WRITEABLE
switch(v.getId()){
case R.id.saveBtn:
name=nameEt.getText().toString();
age=Integer.valueOf(ageEt.getText().toString().trim());
Editor editor=shared.edit();
editor.putString("name", name);
editor.putInt("age", age);
//保证操作的事务完整性
editor.commit();
break;
case R.id.readBtn:
name=shared.getString("name", "无名氏");
age=shared.getInt("age", -1);
Toast.makeText(this, "name="+name+"age="+age, Toast.LENGTH_LONG).show();
break;
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
当运行程序后,点击保存后,我们来看一下程序有没有保存在xml中了呢?







4. 读取其它应用程序的SharedPreferences
- Context.MODE_WORLD_READABLE+ Context.MODE_WORLD_WRITEABLE
其次,当前工程中读取的代码为
if(v.getId() == R.id.readOther){
try {
Context otherContext=this.createPackageContext("cn.class3g.activity", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences shared = otherContext.getSharedPreferences("info", MODE_PRIVATE);
String res="name"+shared.getString("name", "wms")+"age"+String.valueOf(shared.getInt("age", -1));
Toast.makeText(this, res, Toast.LENGTH_LONG).show();
// Editor editor = shared.edit();
// editor.putString("other", "我写你了!!");
} catch (NameNotFoundException e) {
e.printStackTrace();
}
注意:如果两个工程的package相同的话,即使创建是采用的私有模式也可以在另一个工程中顺利读取