android中使用SharedPreferences进行数据存储的操作方法
发布时间:2023-06-16 17:37:42
很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是 j2se应用,我们会采用properties属性文件或者xml进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?Android 平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用 SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:
SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "林计钦");
editor.putInt("age", 24);
editor.commit();//提交修改
生成的ljq.xml文件内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">林计钦</string>
<int name="age" value="24" />
</map>
因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。
访问SharedPreferences中的数据
访问SharedPreferences中的数据代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);
//getString()第二个参数为缺省值,如果preference中不存在该key,将返回缺省值
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。
如:有个<package name>为com.ljq.action的应用使用下面语句创建了preference。
getSharedPreferences("ljq", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("com.ljq.action", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("ljq", Context.MODE_WORLD_READABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 0);
如果不通过创建Context访问其他应用的preference,也可以以读取xml文件方式直接访问其他应用preference对应的xml文件,如:
File xmlFile = new File("/data/data/<package name>/shared_prefs/itcast.xml");//<package name>应替换成应用的包名
案例:
string.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, SpActivity!</string>
<string name="app_name">软件配置参数</string>
<string name="name">姓名</string>
<string name="age">年龄</string>
<string name="button">保存设置</string>
<string name="showButton">显示</string>
</resources>
main.xml布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/name"
android:textSize="20px"
android:id="@+id/nameLable" />
<EditText android:layout_width="80px"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/nameLable"
android:layout_alignTop="@id/nameLable"
android:layout_marginLeft="10px"
android:id="@+id/name" />
</RelativeLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="20px"
android:text="@string/age"
android:id="@+id/ageLable" />
<EditText android:layout_width="80px"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/ageLable"
android:layout_alignTop="@id/ageLable"
android:layout_marginLeft="10px"
android:id="@+id/age" />
</RelativeLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button"
android:id="@+id/button" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/showButton"
android:layout_toRightOf="@id/button"
android:layout_alignTop="@id/button"
android:id="@+id/showButton" />
</RelativeLayout>
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="20px"
android:id="@+id/showText" />
</LinearLayout>
package com.ljq.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.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SpActivity extends Activity {
private EditText nameText;
private EditText ageText;
private TextView resultText;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
nameText = (EditText)this.findViewById(R.id.name);
ageText = (EditText)this.findViewById(R.id.age);
resultText = (TextView)this.findViewById(R.id.showText);
Button button = (Button)this.findViewById(R.id.button);
Button showButton = (Button)this.findViewById(R.id.showButton);
button.setOnClickListener(listener);
showButton.setOnClickListener(listener);
// 回显
SharedPreferences sharedPreferences=getSharedPreferences("ljq123",
Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
String nameValue = sharedPreferences.getString("name", "");
int ageValue = sharedPreferences.getInt("age", 1);
nameText.setText(nameValue);
ageText.setText(String.valueOf(ageValue));
}
private View.OnClickListener listener = new View.OnClickListener(){
public void onClick(View v) {
Button button = (Button)v;
//ljq123文件存放在/data/data/<package name>/shared_prefs目录下
SharedPreferences sharedPreferences=getSharedPreferences("ljq123",
Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
switch (button.getId()) {
case R.id.button:
String name = nameText.getText().toString();
int age = Integer.parseInt(ageText.getText().toString());
Editor editor = sharedPreferences.edit(); //获取编辑器
editor.putString("name", name);
editor.putInt("age", age);
editor.commit();//提交修改
Toast.makeText(SpActivity.this, "保存成功", Toast.LENGTH_LONG).show();
break;
case R.id.showButton:
String nameValue = sharedPreferences.getString("name", "");
int ageValue = sharedPreferences.getInt("age", 1);
resultText.setText("姓名:" + nameValue + ",年龄:" + ageValue);
break;
}
}
};
}
运行结果
如何访问其他应用中的Preference?
package com.ljq.sp;
import java.io.File;
import java.io.FileInputStream;
import android.content.Context;
import android.content.SharedPreferences;
import android.test.AndroidTestCase;
import android.util.Log;
public class AccessSharePreferenceTest extends AndroidTestCase{
private static final String TAG = "AccessSharePreferenceTest";
/**
* 访问SharePreference的方式一,注:权限要足够
* @throws Exception
*/
public void testAccessPreference() throws Exception{
String path = "/data/data/com.ljq.activity/shared_prefs/ljq123.xml";
File file = new File(path);
FileInputStream inputStream = new FileInputStream(file);
//获取的是一个xml字符串
String data = new FileService().read(inputStream);
Log.i(TAG, data);
}
/**
* 访问SharePreference的方式二,注:权限要足够
* @throws Exception
*/
public void testAccessPreference2() throws Exception{
Context context = this.getContext().createPackageContext("com.ljq.activity",
Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = context.getSharedPreferences("ljq123",
Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
Log.i(TAG, name + " : " +age);
}
}
猜你喜欢
- 问题: 在win10系统中,使用IDEA 查看源码的时候,经常跳转代码,这样会让使用者感觉和方便,但是当你想要返回上次跳转的位置时,却不知道
- 这几天面试中有遇到关于main数组中的args数组传值的问题,一般是从命令提示符中传值,也可以直接在java代码中赋值。而且这个数组的长度是
- Android中判断当前网络是否可用 应用场景:实现判断当前网络是否可用当前有可用网络,如下图:当前没有可用网络,如下图:实现步骤:1、获取
- 条形码,是由宽度不等的多个黑条和空白所组成,用以表达一组信息的图形标识符。通过给文档添加条形码,可以直观,快捷地访问和分享一些重要的信息。本
- 本文实例讲述了java实现简单的英文文本单词翻译器功能。分享给大家供大家参考,具体如下:直接上代码:package fanyi;import
- 前言项目使用redis作为缓存数据,但面临着问题,比如,项目A,项目B都用到redis,而且用的redis都是一套集群,这样会带来一些问题。
- " 梧桐更兼细雨,到黄昏、点点滴滴。"C语言朱武大战数据结构专栏C语言植物大战数据结构快速排序图文示例C语言植物大战数据
- Android MediaPlayer实现音乐播放器1、布局文件<?xml version="1.0" encod
- 如下所示:#include "GeneralHashFunctions.h" unsigned int RSHash(c
- 关于在Android中实现ListView的弹性效果,有很多不同的方法,网上一搜,也有很多,下面贴出在项目中经常用到的两种实现ListVie
- 环境信息名称版本号Spring Boot2.4.5Idea2021.3.2服务端实现导入依赖<dependency>  
- 模型对象的作用主要是保存数据,可以借助它们将数据带到前端。常用的模型对象有以下几个:ModelAndView(顾名思义,模型和视图,既可以携
- 本文实例为大家分享了Java中Stream流去除List重复元素的具体代码,供大家参考,具体内容如下业务场景在开发中我们常常需要过滤List
- 一、 应用程序直接建立数据库连接模型应用程序直接每次访问数据库时,都建立创建一个数据库的链接,这样每次建立这样的连接都需要耗费的资源,当同时
- 重要属性1、scale: 小数点后的位数。如将1.234构建为BigDecimal,scale属性则为32、RoundingMode(对照数
- 阿姆斯特朗数阿姆斯特朗数是一个数字,等于每个数字的幂乘以总位数。 例如,诸如0、1、153、370、371和407、1634、8208、94
- 1. 准备工作首先我们创建一个 Spring Boot 工程,引入 Web 和 Redis 依赖,同时考虑到接口限流一般是通过注解来标记,而
- 一、设置Fira_Code字体1.下载字体这里给出github下载链接,点击链接后在README.md中的Download & In
- 参考文章Android中实时获取音量分贝值详解:https://www.jb51.net/article/64806.htmpublic c
- 很多人都知道:浮点数值不适用于无法接受舍入误差的金融计算中,即:我们常说的丢失精度问题。这是为什么呢?很多人还知道这样一句话:这种舍入误差的