数据存储与访问之——SharedPreferences
使用SharedPreferences(保存用户偏好参数)保存数据, 当我们的应用想要保存用户的一些偏好参数,比如是否自动登陆,是否记住账号密码,是否在Wifi下才能 联网等相关信息,如果使用数据库的话,显得有点大材小用了!我们把上面这些配置信息称为用户的偏好 设置,就是用户偏好的设置,而这些配置信息通常是保存在特定的文件中!比如windows使用ini文件, 而J2SE中使用properties属性文件与xml文件来保存软件的配置信息;而在Android中我们通常使用 一个轻量级的存储类——SharedPreferences来保存用户偏好的参数!SharedPreferences也是使用xml文件, 然后类似于Map集合,使用键-值的形式来存储数据;我们只需要调用SharedPreferences的getXxx(name), 就可以根据键获得对应的值!使用起来很方便!
SharedPreferences是一种轻型的Android数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。比较经典的使用方式例如用户输入框对过往登录账户的存储。实现SharedPreferences存储的步骤如下:
1、根据Context获取SharedPreferences对象
2、利用edit()方法获取Editor对象。
3、通过Editor对象存储key-value键值对数据。
4、通过apply()方法提交数据。
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。2019-08-28,17:41:40。
作者By-----溺心与沉浮----博客园
SharedPreferences的使用
)写入数据:
//步骤1:创建一个SharedPreferences对象
SharedPreferences sharedPreferences= getSharedPreferences("data",Context.MODE_PRIVATE);
//步骤2: 实例化SharedPreferences.Editor对象
SharedPreferences.Editor editor = sharedPreferences.edit();
//步骤3:将获取过来的值放入文件
editor.putString("name", “Tom”);
editor.putInt("age", );
editor.putBoolean("marrid",false);
//步骤4:提交
editor.commit();(apply()) )读取数据:
SharedPreferences sharedPreferences= getSharedPreferences("data", Context .MODE_PRIVATE);
String userId=sharedPreferences.getString("name",""); )删除指定数据
editor.remove("name");
editor.commit(); )清空数据
editor.clear();
editor.commit();(apply())
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。2019-08-28,17:41:40。
作者By-----溺心与沉浮----博客园
注意:如果在 Fragment 中使用SharedPreferences 时,需要放在onAttach(Activity activity)里面进行SharedPreferences的初始化,否则会报空指针 即 getActivity()会可能返回null !
读写其他应用的SharedPreferences 步骤如下(未实践):
1. 在创建SharedPreferences时,指定MODE_WORLD_READABLE模式,表明该SharedPreferences数据可以被其他程序读取;
2. 创建其他应用程序对应的Context;
3. 使用其他程序的Context获取对应的SharedPreferences;
4. 如果是写入数据,使用Editor接口即可,所有其他操作均和前面一致;
* SharedPreferences数据的四种操作模式:
* 一、Context.MODE_PRIVATE
* 二、Context.MODE_APPEND
* 三、Context.MODE_WORLD_READABLE
* 四、Context.MODE_WORLD_WRITEABLE
*
* Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
* Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
* Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
*
* MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
* MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入
*
* 特别注意:出于安全性的考虑,MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 在Android .2版本中已经被弃用
try {
//这里的com.example.mpreferences 就是应用的包名
Context mcontext = createPackageContext("com.example.mpreferences", CONTEXT_IGNORE_SECURITY); SharedPreferences msharedpreferences = mcontext.getSharedPreferences("name_preference", MODE_PRIVATE);
int count = msharedpreferences.getInt("count", 0); } catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
新建一个安卓项目,在res,layout,activity_main.xml添加代码
<?xml version="1.0" encoding="utf-8"?>
<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="vertical"
tools:context=".MainActivity"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="用户登录"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="请输入用户名"/>
<EditText
android:id="@+id/editUserName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="用户名"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="请输入密码"/>
<EditText
android:id="@+id/editUserPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="密码"/>
<Button
android:id="@+id/button_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="登陆"/>
</LinearLayout>
效果如下:
简单的SharedPreferences工具类编写SharedPreferences.java
package com.Reverse-xiaoyu.sharedpreferencesutillty; import android.content.Context;
import android.content.SharedPreferences;
import android.widget.Toast; import java.util.HashMap;
import java.util.Map; public class SharedHelp {
private Context context; public SharedHelp(){ } public SharedHelp(Context context){
this.context = context;
} public void save(String userName, String passWord){
SharedPreferences sp = context.getSharedPreferences("MyMap", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("userName", userName);
editor.putString("passWord", passWord);
editor.apply();
Toast.makeText(context, "信息已写入SharedPreferences中", Toast.LENGTH_SHORT).show();
} public Map<String, String> read(){
Map<String, String> data = new HashMap<String, String>();
SharedPreferences sp = context.getSharedPreferences("MyMap", Context.MODE_PRIVATE);
data.put("userName", sp.getString("userName", ""));
data.put("passWord", sp.getString("passWord", ""));
return data;
}
}
在MainActivity中实现逻辑
package com.Reverse-xiaoyu.sharedpreferencesutillty; import androidx.appcompat.app.AppCompatActivity; import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText; import java.util.Map; public class MainActivity extends AppCompatActivity {
//实例化layout中EditText的editUserNmae
private EditText editUserName;
//实例化layout中EditText的editUserPassword
private EditText editUserPassword;
//实例化layout中Button的button_login
private Button button_login;
//定义上下文
private Context context;
//定义ShareHelp类的对象
private SharedHelp sharedHelp;
//定义两个字符串名
private String strName;
private String strPassword; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//获取上下文
context = getApplicationContext();
sharedHelp = new SharedHelp();
bindViews();
} private void bindViews(){
//实例化的变量绑定相应的ID
editUserName = findViewById(R.id.editUserName);
editUserPassword = findViewById(R.id.editUserPassword);
button_login = findViewById(R.id.button_login);
//为按钮设置监听事件
button_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//当按钮被按下触发时,从控件中getText()并将其转换成字符串
strName = editUserName.getText().toString();
strPassword = editUserPassword.getText().toString();
//通过SharedHelp类中save方法,将其保存
sharedHelp.save(strName, strPassword);
}
});
} @Override
protected void onStart() {
super.onStart();
//定义一个Map<String, String>类型的变量data用来接收shareHelp.read()方法的返回值
Map<String, String> data = sharedHelp.read();
//将获取到的数据放置到两个EditText中
editUserName.setText(data.get("userName"));
editUserPassword.setText(data.get("passWord"));
}
}
本人十分不建议代码在主程序入口处写,建议另起文件写,方便交流,就在MainActivity中写了
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。2019-08-28,17:41:40。
作者By-----溺心与沉浮----博客园
最后再写一个SharedPreferences的工具集类
SharedPreferencesUtillty.java
package com.Reverse-xiaoyu.sharedpreferencesutillty; import android.content.Context;
import android.content.SharedPreferences; import java.util.Map; public class SharedPreferenceUtillty {
//保存的SP文件名
public static final String FILE_NAME = "MyMap"; /**
* SharedPreferences数据的四种操作模式:
* 一、Context.MODE_PRIVATE
* 二、Context.MODE_APPEND
* 三、Context.MODE_WORLD_READABLE
* 四、Context.MODE_WORLD_WRITEABLE
*
* Context.MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
* Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件.
* Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE用来控制其他应用是否有权限读写该文件.
*
* MODE_WORLD_READABLE:表示当前文件可以被其他应用读取.
* MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入
*
* 特别注意:出于安全性的考虑,MODE_WORLD_READABLE 和 MODE_WORLD_WRITEABLE 在Android 4.2版本中已经被弃用
*/ /**
* 保存数据
*/
public static void putData(Context context, String key, Object object){
//实例化SharedPreferences对象(第一步)
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
//实例化SharedPreferences.Editor对象(第二步)
SharedPreferences.Editor editor = sp.edit();
//用putObject的方法保存数据,取决于第三个参数你使用的什么类型的变量
if (object instanceof Boolean){
editor.putBoolean(key, (Boolean) object);
}else if (object instanceof Float){
editor.putFloat(key, (Float) object);
}else if (object instanceof Integer){
editor.putInt(key, (Integer) object);
}else if (object instanceof Long){
editor.putLong(key, (Long) object);
}else if (object instanceof String){
editor.putString(key, (String) object);
}
editor.apply();
} /**
* 获取指定数据
*/
public static Object getData(Context context, String key, Object object){
//实例化SharedPreferences对象(第一步)
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
//用getObject的方法保存数据,取决于第三个参数你使用的什么类型的变量(第二步)
if (object instanceof Boolean){
return sp.getBoolean(key, (Boolean) object);
}else if (object instanceof Float){
return sp.getFloat(key, (Float) object);
}else if (object instanceof Integer){
return sp.getInt(key, (Integer) object);
}else if (object instanceof Long){
return sp.getLong(key, (Long) object);
}else if (object instanceof String){
return sp.getString(key, (String) object);
}
return null;
} /**
* 返回所有的键值对
*/
public static Map<String, ?> getAll(Context context){
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
Map<String, ?> map = sp.getAll();
return map;
} /**
* 检查对应的数据是否存在
*/
public static boolean contains(Context context, String key){
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
return sp.contains(key);
} /**
* 删除指定key值的数据
*/
public static void remove(Context context, String key){
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
editor.apply();
} /**
* 删除所有的数据
*/
public static void clear(Context context, String key){
SharedPreferences sp = context.getSharedPreferences(FILE_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.clear();
editor.apply();
} }
版权声明:本文为博主原创文章,转载请附上原文出处链接和本声明。2019-08-28,17:41:40。
作者By-----溺心与沉浮----博客园
数据存储与访问之——SharedPreferences的更多相关文章
- Android数据存储(一)----SharedPreferences详解
一.Android数据的存储方式: Android系统一共提供了四种数据存储方式.分别是:SharePreference.SQLite.Content Provider和File:此外还有一种网络存储 ...
- 数据存储与访问之——初见SQLite数据库
本节引言: 本节学习Android数据库存储与访问的第三种方式:SQLite数据库,和其他的SQL数据库不同,我们并不需要在手机上另外安装一个数据库手机软件,Android系统已经集成了这 ...
- Laravel 5.1 中 Session 数据存储、访问、删除及一次性Session实例教程
1.Session的由来及其实现 HTTP协议是无状态的协议,同一个客户端的这次请求和上次请求是没有对应关系的.也就是说我们无法在服务器端确认两次请求是否是同一个用户所为,这为我们在一些应用场景中实现 ...
- Android数据存储与访问
1.文件 1)保存到手要内存,文件保存到/data/data对应的应用程序包下面 如 FILE_PATH = "/data/data/com.diysoul.filedem ...
- 从零開始学android<数据存储(1)SharedPreferences属性文件.三十五.>
在android中有五种保存数据的方法.各自是: Shared Preferences Store private primitive data in key-value pairs. 相应属性的键值 ...
- Android数据存储之共享参数SharedPreferences
SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式,类似于Java的Properties类,二者都是把Key-Value的键值对保存 ...
- android(9)_数据存储和访问3_scard基本介绍
使用Activity的openFileOutput()保存文件的方法,文件存储在手机空间,通常情况下,手机的存储空间不是很大,存储小文件确定.假设你要存储大文件,如视频,是不可行. 对于这样大的文件, ...
- 【Android实验】 数据存储与访问sqlite
目录 实验目的 实验要求 实验过程 功能分析: 实验结果: 实验的代码 实验总结 实验目的 分别使用sqlite3工具和Android代码的方式建立SQLite数据库.在完成建立数据库的工作后 ...
- 【Android】数据存储和访问
一.SharedPreferences 2.SQLite
随机推荐
- luogu P4408 [NOI2003]逃学的小孩
题目描述 Chris家的电话铃响起了,里面传出了Chris的老师焦急的声音:"喂,是Chris的家长吗?你们的孩子又没来上课,不想参加考试了吗?"一听说要考试,Chris的父母就心 ...
- openlayers6结合geoserver实现地图属性查询(附源码下载)
前言 之前写过一篇 openlayers4 版本的地图属性查询文章,但是由于是封装一层 js 代码写的,很多初学者看起来比较有点吃力,所以本篇文章重新写一篇地图属性查询文章,直接基于最新版本 open ...
- ZOJ 2112 Dynamic Rankings(树状数组+主席树)
The Company Dynamic Rankings has developed a new kind of computer that is no longer satisfied with t ...
- Asp.net Core dotnet 发布类库文件 带上注释,发布预发行版,带上所有引用
带上注释 效果图 带上所有引用 效果图 预发行版 效果图 由于微软取消了 project.json 这个json 转而用了csproj 用于保存配置 所以懵逼很大一会 资料来源 project.j ...
- iSensor APP 之 摄像头调试 OV3640 OV2640 MT9d112 ov5642
iSensor APP 之 摄像头调试 OV3640 OV2640 MT9d112 iSensor app 非常适合调试各种摄像头,已测试通过的sensor有: l OV7670.OV7725.O ...
- 重新精读《Java 编程思想》系列之组合与继承
Java 复用代码的两种方式组合与继承. 组合 组合只需将对象引用置于新类中即可. 比如我们有一个B类,它具有一个say方法,我们在A类中使用B类的方法,就是组合. public class B { ...
- SpringAOP在web应用中的使用
之前的aop是通过手动创建代理类来进行通知的,但是在日常开发中,我们并不愿意在代码中硬编码这些代理类,我们更愿意使用DI和IOC来管理aop代理类.Spring为我们提供了以下方式来使用aop框架 一 ...
- Jquery使用ajax与Flask后端进行数据交互
最近做项目碰到一个坑,jquery使用ajax向flask传输数据的时候,在后端采用request.data无论如何都获取不到数据,代码如下: 前端: <script> function ...
- 201871010119-帖佼佼《面向对象程序设计(java)》第十六周学习总结
博文正文开头格式:(2分) 项目 内容 这个作业属于哪个课程 https://www.cnblogs.com/nwnu-daizh/ 这个作业的要求在哪里 https://www.cnblogs.co ...
- mysql重点中的重点---->查询中的关键字优先级
1.from 找到表 2.where 拿着where指定的约束条件,去文件/表中取出一条条记录 3.group by 将取出的一条条记录进行分组group by ,如果没有group by ,则整体作 ...