Android数据存储之SharedPreferences与Editor

SharedPreferences保存的数据只要是类似于配置信息格式的数据,因此它保存的数据只要是简单类型的key-value对.

SharedPreferences接口主要负责读取应用程序的Preferences数据,它提供了如下常用方法来访问SharedPreferences中的key-value对.

> boolean contains(String key): 判断SharedPreferences是否包含特定key的数据.

> abstract Map<String, ?> getAll(): 获取SharedPreferences数据里全部的key-value对.

> boolean getXxx(String key, xxx defValue): 获取SharedPreferences数据里指定key对应的value.如果该key不存在,返回默认值defValue.其中xxx可以是boolean, float, int, long, String等各种基本类型的值.

SharedPreferences接口本身并没有提供写入数据的能力,而是通过SharedPreferences的内部接口,SharedPreferences调用edit()方法即可获取它所对应的Editor对象.Editor提供了如下方法来向SharedPreferences写入数据.

> SharedPreferences.Editor clear(): 清空SharedPreferences里所有数据.

> SharedPreferences.Editor putXxx(String key, xxx value): 向SharedPreferences存入指定key对应的数据.其中xxx可以是boolean, float, int, long, String等各种基本类型的值.

> SharedPreferences.Editor remove(String key): 删除SharedPreferences里指定key对应的数据项.

> boolean commit(): 当Editor编辑完成后,调用该方法提交修改.

从用法角度看,SharedPreferences和SharedPreferences.Editor组合起来非常想Map,其中SharedPreferences负责根据key读取数据,而SharedPreferences.Editor则用于写入数据.

SharedPreferences本身是一个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例,该方法的第二个参数支持如下几个值.

> Context.MODE_PRIVATE: 指定该SharedPreferences数据只能被本应用程序读,写.

> Context.MODE_WORLD_READABLE: 指定该SharedPreferences数据能被其它应用程序读,但不能写.

> Context.MODE_WORLD_WEITEABLE: 指定该SharedPreferences数据能被其它应用程序读,写.

SharedPreferences的存储位置和格式

当程序完成SharedPreferences写入,写入完成后打开DDMS的File Explorer面板,然后展开文件浏览树,可以看出,SharedPreferences数据总是保存在/data/data/<package name>/shared_prefs目录下,SharedPreferences数据总是以XML格式保存.通过File Explorer面板的导出文件按钮将该XML文件导出到XML文档,打开该XML文档可看到如下文件内容:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>

<map>

<int name="random" value="86" />

<string name="time">2015年01月01日 04:23:00</string>

</map>

从上面的文件不难看出,SharedPreferences数据文件是一个根元素为<map.../>的根元素,该元素里每个子元素代表一个key-value对,当value是整数类型的值时使用<int.../>子元素,当value是字符串类型时,使用<string.../>子元素.......以此类推..

读, 写其他应用SharedPreferences

要读, 写其他应用的SharedPreferences,前提是创建该SharedPreferences的应用程序指定相应的访问权限,例如指定MODE_WORLD_READABLE,这表明SharedPreferences可被其他应用程序读取;制定了MODE_WORLD_WRITEABLE,表明该SharedPreferences可被其他程序写入.

为了读取其他程序的SharedPreferences,可按如下步骤进行.

(1) 需要创建其他程序对应的Context,例如如下代码:

useCount = createPackageContext("com.example.androidioanddatastore",Context.CONTEXT_IGNORE_SECURITY);

上面的代码中, com.example.androidioanddatastore 就是其他应用程序的包名------实际上Android系统就是用应用程序的包名来作为该程序的标识的.

(2) 调用其他应用程序的Context的getSharedPreferences(String name, int mode)即可获取相应的SharedPreferences对象.

(3) 如果需要向其他应用的SHaredPreferences数据写入数据,调用SharedPreferences的edit()方法获取相应的Editor即可.


事实上,如果不通过先获取其他应用程序的Context,在获取SharedPreferences的方式也可读取SharedPreferences的数据-------开发者完全使用以IO流的方式先读取SharedPreferences对应的XML文件,再通过XML解析来获取数据也是可行的,只是这种方式过于烦琐,而使用SharedPreferences来读写数据这简单得多.

提示:

访问其他应用程序的SharedPreferences的关键就是获取其他应用程序的Context.Context代表了访问该Android应用的全局信息的接口,而Android应用的包名正式该应用的唯一标识,因此程序可根据Android应用的包名来获取相应的Context.



下面的将是两个小小的demo

一,SharedPreferences的简单读, 取操作

1.activity.java文件

package com.example.androidioanddatastore.share_preferences;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.example.androidioanddatastore.R;

/***
 * 使用SharedPreferences存,取数据的简单demo
 *
 */
public class SharedPreferencesActivity extends Activity {
	public final static String SHAREDPREFERENCES_NAME = "SharedPreferences";
	private SharedPreferences preferences;
	private SharedPreferences.Editor editor;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shared_preferences);
		preferences = getSharedPreferences(SHAREDPREFERENCES_NAME,
				MODE_WORLD_READABLE);
		// 读取SharedPreferences里的count数据
		int count = preferences.getInt("count", 0);
		// 显示以前程序使用的次数
		Toast.makeText(SharedPreferencesActivity.this,
				"程序以前被使用了" + count + "次...", Toast.LENGTH_SHORT).show();
		editor = preferences.edit();
		// 存入数据
		editor.putInt("count", ++count);
		//提交修改
		editor.commit();
	}

	/**
	 * 使用SharePreferences进行数据存取的一个小的例子
	 */
	// @Override
	// protected void onCreate(Bundle savedInstanceState) {
	// super.onCreate(savedInstanceState);
	// setContentView(R.layout.activity_shared_preferences);
	// // 获取只能被本应用程序读,写的SharePreferences对象
	// preferences = getSharedPreferences(SHAREDPREFERENCES_NAME, MODE_WORLD_READABLE);
	// editor = preferences.edit();
	// Button read = (Button) findViewById(R.id.read);
	// Button write = (Button) findViewById(R.id.write);
	// read.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// // 读取字符串数据
	// String time = preferences.getString("time", null);
	// // 读取int类型数据
	// int randNum = preferences.getInt("randNum", 0);
	// String result = TextUtils.isEmpty(time) ? "您还未写入数据..." : "写入时间为:" + time + "\n上次生成的随机数为:" + randNum;
	// //使用Toast提示信息
	// Toast.makeText(SharedPreferencesActivity.this, result, Toast.LENGTH_SHORT).show();
	// }
	// });
	//
	// write.setOnClickListener(new OnClickListener() {
	// @Override
	// public void onClick(View v) {
	// SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日   " + "hh:mm:ss");
	// //存入当前时间
	// editor.putString("time", sdf.format(new Date()));
	// //存入一个随机数
	// editor.putInt("randNum", (int)(Math.random() * 100));
	// //提交所有存入的数据
	// editor.commit();
	// }
	// });
	//
	// }

}
2.布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal" >

    <Button
        android:id="@+id/read"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="read" />

    <Button
        android:id="@+id/write"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="write" />

</LinearLayout>

二.这个为读取其他应用程序SharedPreferences的demo

1.activity.java文件

package com.example.androidioanddatastore.share_preferences;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView;

import com.example.androidioanddatastore.R;

/***
 * 使用其它应用程序的SharedPreferences
 *
 */
public class ReadOtherPreferences extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.readotherpreferences);
		Context useCount = null;
		try {
			//获取其他程序所对应的Context
			useCount = createPackageContext(
					"com.example.androidioanddatastore",
					Context.CONTEXT_IGNORE_SECURITY);
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		// 使用其它程序的Context获取对应的SharedPreferences
		SharedPreferences preferences = useCount.getSharedPreferences(
				SharedPreferencesActivity.SHAREDPREFERENCES_NAME,
				Context.MODE_WORLD_READABLE);
		// 读取数据
		int count = preferences.getInt("count", 0);
		//显示读取的数据内容
		((TextView)findViewById(R.id.show)).setText("UseContext应用程序以前被使用了"+count+"次");
	}
}
呵呵,不好的地方,欢迎留言哦...

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值