很多时候我们开发的软件需要向用户提供软件参数设置功能,例如我们常用的QQ,用户可以设置是否允许陌生人添加自己为好友。对于软件配置参数的保存,如果是window软件通常我们会采用ini文件进行保存,如果是j2se应用,我们会采用properties属性文件进行保存。如果是Android应用,我们最适合采用什么方式保存软件配置参数呢?
Android平台给我们提供了一个SharedPreferences类,它是一个轻量级的存储类,特别适合用于保存软件配置参数。使用SharedPreferences保存数据,其背后是用xml文件存放数据,文件存放在/data/data/<package name>/shared_prefs目录下:
SharedPreferences sharedPreferences = getSharedPreferences("zyj", Context.MODE_PRIVATE);
Editor editor = sharedPreferences.edit();//获取编辑器
editor.putString("name", "老李");
editor.putInt("age", 4);
editor.commit();//提交修改
生成的zyj.xml文件内容如下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">老李</string>
<int name="age" value="4" />
</map>
因为SharedPreferences背后是使用xml文件保存数据,getSharedPreferences(name,mode)方法的第一个参数用于指定该文件的名称,名称不用带后缀,后缀会由Android自动加上。方法的第二个参数指定文件的操作模式,共有四种操作模式,这四种模式前面介绍使用文件方式保存数据时已经讲解过。如果希望SharedPreferences背后使用的xml文件能被其他应用读和写,可以指定定Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE权限。
另外Activity还提供了另一个getPreferences(mode)方法操作SharedPreferences,这个方法默认使用当前类不带包名的类名作为文件的名称。
SharedPreferences其实用的是pull解释器
访问SharedPreferences中的数据代码如下:
SharedPreferences sharedPreferences = getSharedPreferences("zyj", 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.jbridge.pres.activity的应用使用下面语句创建了preference。
getSharedPreferences("zyj", Context.MODE_WORLD_READABLE);
其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :
Context otherAppsContext = createPackageContext("com.jbridge.pres.activity", Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("zyj", 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/zyj.xml”);//<package name>应替换成应用的包名
下面,编写一个使用SharedPreferences读写配置文件的小例子。

       1.创建Android工程

Project name:sharedPreferences

BuildTarget:Android2.2

Application name:软件参数设置

Package name:com.com.jbridge.pres.activity

Create Activity:PreferencesActivity

Min SDK Version:8

       2.编辑strings.xml:

<?xml version="1.0" encoding="utf-8"?>

<resources>

<string name="hello">Hello World, PreferencesActivity!</string>

<string name="app_name">软件参数设置</string>

<string name="tv_name">姓名</string>

<string name="tv_age">年龄</string>

<string name="bt_write">设置</string>

<string name="bt_read">读取</string>

<string name="save_success">保存成功</string>

<string name="save_failed">保存失败</string>

</resources>

      3.编辑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 android:layout_width="fill_parent"

android:layout_height="wrap_content">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/tv_name"

android:id="@+id/tv_name"

android:textSize="30px"

/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/et_name"

android:layout_toRightOf="@id/tv_name"

android:layout_alignTop="@id/tv_name"

android:layout_marginLeft="30px"

/>

</RelativeLayout>

<RelativeLayout android:layout_width="fill_parent"

android:layout_height="wrap_content">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/tv_age"

android:id="@+id/tv_age"

android:textSize="30px"

/>

<EditText

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/et_age"

android:layout_toRightOf="@id/tv_age"

android:layout_alignTop="@id/tv_age"

android:layout_marginLeft="30px"

/>

</RelativeLayout>

<RelativeLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/bt_write"

android:text="@string/bt_write"

/>

<Button

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:id="@+id/bt_read"

android:text="@string/bt_read"

android:layout_toRightOf="@id/bt_write"

android:layout_alignTop="@id/bt_write"

android:layout_marginLeft="30px"

/>

</RelativeLayout>

<TextView

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:id="@+id/tv_show"

/>

</LinearLayout>

       4.为按钮添加事件代码

package com.jbridge.pres.activity;

import android.app.Activity;

import android.content.Context;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.content.res.Resources.NotFoundException;

import android.os.Bundle;

import android.text.Editable;

import android.view.View;

import android.widget.Button;

import android.widget.EditText;

import android.widget.TextView;

import android.widget.Toast;

public class PreferencesActivity extends Activity {

private EditText etName;

private EditText etAge;

private View.OnClickListener onClickListener=new View.OnClickListener() {

public void onClick(View view) {

Button button=(Button) view;

SharedPreferences sharedPreferences=PreferencesActivity.this.getSharedPreferences("zyj", Context.MODE_PRIVATE);

switch (button.getId()) {

case R.id.bt_write:

try {

Editor editor=sharedPreferences.edit();

editor.putString("name", etName.getText().toString());

editor.putInt("age",Integer.valueOf(etAge.getText().toString()) );

editor.commit();

Toast.makeText(PreferencesActivity.this, R.string.save_success, Toast.LENGTH_LONG).show();

} catch (NumberFormatException e) {

Toast.makeText(PreferencesActivity.this, R.string.save_failed, Toast.LENGTH_LONG).show();;

e.printStackTrace();

} catch (NotFoundException e) {

Toast.makeText(PreferencesActivity.this, R.string.save_failed, Toast.LENGTH_LONG).show();;

e.printStackTrace();

}

break;

case R.id.bt_read:

String name=sharedPreferences.getString("name", "no name");

String age=String.valueOf(sharedPreferences.getInt("age", 0));

TextView tvShow=(TextView) PreferencesActivity.this.findViewById(R.id.tv_show);

tvShow.setText("姓名: "+name+"     年龄: "+age);

break;

default:

break;

}

}

};

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

SharedPreferences sharedPreferences=PreferencesActivity.this.getSharedPreferences("zyj", Context.MODE_PRIVATE);

etName=(EditText) this.findViewById(R.id.et_name);

etAge=(EditText) this.findViewById(R.id.et_age);

etName.setText(sharedPreferences.getString("name", "no name"));

etAge.setText(String.valueOf(sharedPreferences.getInt("age", 0)));

Button btWrite=(Button) this.findViewById(R.id.bt_write);

Button btRead=(Button) this.findViewById(R.id.bt_read);

btWrite.setOnClickListener(onClickListener);

btRead.setOnClickListener(onClickListener);

}

/*

如果访问其他应用中的Preference,前提条件是:该preference创建时指定了Context.MODE_WORLD_READABLE或者Context.MODE_WORLD_WRITEABLE权限。如:有个<package name>为com.jbridge.pres.activity的应用使用下面语句创建了preference。

getSharedPreferences("zyj", Context.MODE_WORLD_READABLE);

其他应用要访问上面应用的preference,首先需要创建上面应用的Context,然后通过Context 访问preference ,访问preference时会在应用所在包下的shared_prefs目录找到preference :

Context otherAppsContext = createPackageContext("com.jbridge.pres.activity", Context.CONTEXT_IGNORE_SECURITY);

SharedPreferences sharedPreferences = otherAppsContext.getSharedPreferences("zyj", Context.MODE_WORLD_READABLE);

String name = sharedPreferences.getString("name", "no name");

int age = sharedPreferences.getInt("age", 0);

*/

}

5. 运行程序

启动模拟器,运行程序。输入名称和年龄,点击保存。我们使用的代码是getSharedPreferences("zyj",Context.MODE_PRIVATE);,当然commit时。它会为我们为”/data/data/com.jbridge.pres.activity/shared_prefszyj.xml”。将 preferences.xml导出,查看它的内容为:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?> <map> <string name="name">zyj</string> <int name="age" value="22" /> </map>

  • sharedPreferences.rar (91.3 KB)
  • 下载次数: 118

读写SharedPreferences中的数据相关推荐

  1. Kotlin中的数据存储

    数据存储 1 持久化技术简介 数据持久化就是指将那些内存中的瞬时数据保存到存储设备中,保证即使在手机或计算机关机的情况下,这些数据仍然不会丢失. 保存在内存中的数据是处于瞬时状态的,而保存在存储设备中 ...

  2. Android 中的数据储存方案, 持久化技术

    为什么80%的码农都做不了架构师?>>>    Android 中储存数据的方法主要有三种: 1,文件储存. 2,SharedPreference储存. 3,数据库储存. 1. 文件 ...

  3. python文件读取输出-Python 读写文件中数据

    1 需求 在文件 h264.txt 中的数据如图1,读入该文件中的数据,然后将第1列的地址删除,然后将数据输出到h264_out.txt中: 图1 h264.txt 数据截图 图2 输出文件 h264 ...

  4. android sharedpreference 清空,Android 从SharedPreferences中存储,检索,删除和清除数据...

    示例 创建SharedPreferences BuyyaPref SharedPreferences pref = getApplicationContext().getSharedPreferenc ...

  5. Java 中如何解决 POI 读写 excel 几万行数据时内存溢出的问题?(附源码)

    >>号外:关注"Java精选"公众号,菜单栏->聚合->干货分享,回复关键词领取视频资料.开源项目. 1. Excel2003与Excel2007 两个版本 ...

  6. C#读写操作app.config中的数据

    原文地址为: C#读写操作app.config中的数据 读语句: String str = ConfigurationManager.AppSettings["DemoKey"]; ...

  7. python读取raw数据文件_Python 读写文件中数据

    1 需求 在文件 h264.txt 中的数据如图1,读入该文件中的数据,然后将第1列的地址删除,然后将数据输出到h264_out.txt中: 图1 h264.txt 数据截图 图2 输出文件 h264 ...

  8. ble 读写特征值特征值_ap.readBLECharacteristicValue 读取低功耗蓝牙设备特征值中的数据 - 支付宝 Alipay JSSDK 开发文档...

    ap.readBLECharacteristicValue(OPTION, CALLBACK) 读取低功耗蓝牙设备特征值中的数据.调用后在 ap.onBLECharacteristicValueCha ...

  9. Dmc雷赛板卡仿写(六):数据在程序中的保存与读取 ,类变量读写,json文件数据读入,ini文件数据读入

    1.类变量读入(之前类的学习中写过) //在.h中实例化了这些类using AxisName = QString;using AxisHash = QMap<AxisName, DmcAxis* ...

  10. VB.net连接、读写SQL服务器数据库,并在窗口表格中显示数据

    有些场合可能需要将读取来的数据进行存储,或者从数据库中读取数据,这时候就可以用到SQL数据库,VB.net和SQL数据库的数据通讯,比较简单. 软件工具:1.visual studio 2019 2. ...

最新文章

  1. HTTP协议Etag详解
  2. 转:用java调用oracle存储过程总结(比较好理解)
  3. PHP用单例模式实现一个数据库类
  4. android 之 百度地图
  5. leetcode 283 Move Zeros; 27 Remove Elements; 26 Remove Duplicated from Sorted Array;
  6. UP-DETR:收敛更快!精度更高!华南理工微信开源无监督预训练目标检测模型...
  7. 从0开始配置Win环境下VScode (VScode For C/C++)
  8. weex scroller
  9. 【转载】关于防火墙的初次接触
  10. git21天打卡day20-合并分支
  11. Atitit.获得向上向下左的右的邻居的方法 软键盘的设计..
  12. qt.qpa.plugin: Could not load the Qt platform plugin xcb in /root/PycharmProjects/pythonPr
  13. 一个屌丝程序员的青春(五一)
  14. 斯坦福公布3D街景数据集:2500万张图像,8个城市模型 | 下载
  15. 某bobo在线视频APP下载暴力流逆向
  16. 语义计算_语义多态性如何在量子计算中起作用
  17. 微电网控制趋势(综述)
  18. 生存分析——cox模型及相关参数求解
  19. Parameter 'arg0' not found. Available parameters are [xxx, xxx, param1, param2]
  20. 芒果改进目录一览|原创改进YOLOv5、YOLOv7等YOLO模型全系列目录 | 人工智能专家唐宇迪老师联袂推荐

热门文章

  1. 用matlab辨识系统,Matlab系统辨识工具箱
  2. 移远BC95系列区别
  3. win10 两台电脑之间共享桌面及共享文件(手把手教学)
  4. Python编写软件与从倍福PLC通讯软件
  5. xcode 找不到头文件
  6. 微信小程序开源源码汇总
  7. 西门子PLC_s7-200免费学习视频教程
  8. html5查看xps文件,c# – 在文档查看器中显示XPS文档
  9. WiFi PowerSave模式以及通过抓包判断是否生效
  10. Java SE、Java EE、Java ME三者之间的区别