4数据存储

共享参数SharedPreferences、数据库SQLite、SD卡文件、App的全局内存

4.1共享参数SharedPreferences

SharedPreferences是一个轻量级存储工具,采用的存储结构时Key-Value的键值对方式

SharedPreferences的存储介质是符合XML规范的配置文件。

保存SharedPreferences键值对信息的文件路径时/data/data/应用包名/shared_prefs/文件名.xml

<?xml version='1.0' encoding='utf-8' standalone='yes'?>
<map>
<string name="name"></string>
<int name="age" value="30"/>
<boolean name="married" value="true"/>
<float name="weight" value="100.0"/>
</map>

​ 基于XML格式的特点,SharedPreferences主要适用于如下场合:

  1. 简单且孤立的数据。若是复杂且相互间有关的数据,则要保存在数据库中。
  2. 文本形式的数据。若是二进制数据,则要保存在文件中。
  3. 需要持久化存储的数据。在App退出后再次启动时,之前保存的数据仍然有效。

实际开发中,共享参数经常存储的数据有App的个性化配置信息、用户使用App的行为信息、临时需要保存的片段信息等

SharedPreferences对数据的存储和读取操作类似于Map,也有put函数用于存储数据、get函数用于读取数据。在使用共享参数之前,要先调用getSharedPreferences函数声明文件名与操作模式:

SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);

getSharedPreferences方法的第一个参数是文件名,上面的share表示当前使用的共享参数文件名是share.xml;第二个参数是操作模式,一般都填MODE_PRIVATE,表示私有模式。

共享参数存储数据要借助于Editor类:

SharedPreferences.Editor editor = shared.edit();// 获得编辑器的对象
editor.putString("name","Mr Lee");// 添加一个名叫name的字符串参数
editor.putInt("age",23);// 添加一个名叫age的整形参数
editor.putBoolean("married",true);// 添加一个名叫married的布尔型参数
editor.putFloat("weight",100f);// 添加一个名叫weight的浮点数参数
editor.commit();// 提交编辑器中的修改

共享参数读取数据相对简单,直接使用对象即可完成数据读取方法的调用,注意get方法的第二个参数表示默认值:

String name = shared.getString("name","");// 从共享参数中获得名叫name的字符串
int age = shared.getInt("age",0);// 从共享参数中获得名叫age的整形数
boolean married = getBoolean("married",false);// 从共享参数中获得名叫married的布尔数
float weight = getFloat("weight",0);// 从共享参数中获得名叫weight的浮点数

Write:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:padding="10dp" > <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="姓名:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入姓名"
android:inputType="text"
android:maxLength="12"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_age"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="年龄:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_age"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_age"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入年龄"
android:inputType="number"
android:maxLength="2"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_height"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="身高:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_height"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入身高"
android:inputType="number"
android:maxLength="3"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_weight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="体重:"
android:textColor="@color/black"
android:textSize="17sp" /> <EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="5dp"
android:layout_marginTop="5dp"
android:layout_toRightOf="@+id/tv_weight"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="请输入体重"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textColorHint="@color/grey"
android:textCursorDrawable="@drawable/text_cursor"
android:textSize="17sp" />
</RelativeLayout> <RelativeLayout
android:layout_width="match_parent"
android:layout_height="50dp" > <TextView
android:id="@+id/tv_married"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:gravity="center"
android:text="婚否:"
android:textColor="@color/black"
android:textSize="17sp" /> <Spinner
android:id="@+id/sp_married"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toRightOf="@+id/tv_married"
android:gravity="left|center"
android:spinnerMode="dialog" />
</RelativeLayout> <Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存到共享参数"
android:textColor="@color/black"
android:textSize="20sp" /> </LinearLayout>
public class ShareWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private SharedPreferences mShared;
private EditText et_name;
private EditText et_age;
private EditText et_height;
private EditText et_weight;
private boolean bMarried = false; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_write);
et_name = (EditText) findViewById(R.id.et_name);
et_age = (EditText) findViewById(R.id.et_age);
et_height = (EditText) findViewById(R.id.et_height);
et_weight = (EditText) findViewById(R.id.et_weight);
findViewById(R.id.btn_save).setOnClickListener(this); ArrayAdapter<String> typeAdapter = new ArrayAdapter<String>(this,
R.layout.item_select, typeArray);
typeAdapter.setDropDownViewResource(R.layout.item_dropdown);
Spinner sp_married = (Spinner) findViewById(R.id.sp_married);
sp_married.setPrompt("请选择婚姻状况");
sp_married.setAdapter(typeAdapter);
sp_married.setSelection(0);
sp_married.setOnItemSelectedListener(new TypeSelectedListener()); mShared = getSharedPreferences("share", MODE_PRIVATE);
} private String[] typeArray = {"未婚", "已婚"};
class TypeSelectedListener implements AdapterView.OnItemSelectedListener {
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
bMarried = (arg2==0)?false:true;
} public void onNothingSelected(AdapterView<?> arg0) {
}
} @Override
public void onClick(View v) {
if (v.getId() == R.id.btn_save) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
if (name==null || name.length()<=0) {
showToast("请先填写姓名");
return;
}
if (age==null || age.length()<=0) {
showToast("请先填写年龄");
return;
}
if (height==null || height.length()<=0) {
showToast("请先填写身高");
return;
}
if (weight==null || weight.length()<=0) {
showToast("请先填写体重");
return;
} SharedPreferences.Editor editor = mShared.edit();
editor.putString("name", name);
editor.putInt("age", Integer.parseInt(age));
editor.putLong("height", Long.parseLong(height));
editor.putFloat("weight", Float.parseFloat(weight));
editor.putBoolean("married", bMarried);
editor.putString("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"));
editor.commit();
showToast("数据已写入共享参数");
}
} private void showToast(String desc) {
Toast.makeText(this, desc, Toast.LENGTH_SHORT).show();
} }

Read:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
android:orientation="vertical"
android:padding="10dp" > <TextView
android:id="@+id/tv_share"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="@color/black"
android:textSize="17sp" /> </LinearLayout>
public class ShareReadActivity extends AppCompatActivity {

    private SharedPreferences mShared;
private TextView tv_share; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_share_read);
tv_share = (TextView) findViewById(R.id.tv_share);
readSharedPreferences();
} private void readSharedPreferences() {
SharedPreferences mShared = getSharedPreferences("share", MODE_PRIVATE);
String desc = "共享参数中保存的信息如下:";
Map<String, Object> mapParam = (Map<String, Object>) mShared.getAll();
for (Map.Entry<String, Object> item_map : mapParam.entrySet()) {
String key = item_map.getKey();
Object value = item_map.getValue();
if (value instanceof String) {
desc = String.format("%s\n %s的取值为%s", desc, key,
mShared.getString(key, ""));
} else if (value instanceof Integer) {
desc = String.format("%s\n %s的取值为%d", desc, key,
mShared.getInt(key, 0));
} else if (value instanceof Float) {
desc = String.format("%s\n %s的取值为%f", desc, key,
mShared.getFloat(key, 0.0f));
} else if (value instanceof Boolean) {
desc = String.format("%s\n %s的取值为%b", desc, key,
mShared.getBoolean(key, false));
} else if (value instanceof Long) {
desc = String.format("%s\n %s的取值为%d", desc, key,
mShared.getLong(key, 0l));
} else {
desc = String.format("%s\n参数%s的取值为未知类型", desc, key);
}
}
if (mapParam==null || mapParam.size()<=0) {
desc = "共享参数中保存的信息为空";
}
tv_share.setText(desc);
} }

Android——共享参数SharedPreferences的更多相关文章

  1. Android 共享参数 SharedPreferences

    完成共享参数的读写 public class SharedPreference { private Context context; public SharedPreference(Context c ...

  2. Android数据存储之共享参数SharedPreferences

    SharedPreferences是Android的一个轻量级存储工具,采用的存储结构是Key-Value的键值对方式,类似于Java的Properties类,二者都是把Key-Value的键值对保存 ...

  3. 数据存储 共享参数 SharedPreferences

    先要声明文件名和操作方式,第一个参数:文件名为"share.xml",第二个参数:私有模式SharedPreferences shared = getSharedPreferenc ...

  4. Kotlin入门(25)共享参数模板

    共享参数SharedPreferences是Android最简单的数据存储方式,常用于存取“Key-Value”键值对数据.在使用共享参数之前,要先调用getSharedPreferences方法声明 ...

  5. 数据存储之 SharedPreference 共享参数 (转)

        在上一讲中,我们学习了如何将数据存储在SD卡中[数据存储之File文件存储 [即SD卡的写入与读取]],这是一种存储方式,这一讲我们来学习一下使用SharedPreferences存储数据. ...

  6. Android 开发笔记___存储方式__共享参数__sharedprefences

    Android 的数据存储方式有四种,这次是[共享参数__sharedprefences] 听起来挺别扭的,平时看到的app里面,当用户删除了一些软件以后下次安装,发现原来的设置还在,这种情况就是把一 ...

  7. android 开发-数据存储之共享参数

    android提供5中数据存储方式 数据存储之共享参数 内部存储 扩展存储 数据库存储 网络存储  而共享存储提供一种可以让用户存储保存一些持久化键值对在文件中,以供其他应用对这些共享参数进行调用.共 ...

  8. Android学习之SharedPreferences类

    SharedPreferences类 android.content.SharedPreferences 类概括: 访问和修改由函数getSharedPreferences(String,int)返回 ...

  9. Android应用开发SharedPreferences存储数据的使用方法

    Android应用开发SharedPreferences存储数据的使用方法 SharedPreferences是Android中最容易理解的数据存储技术,实际上SharedPreferences处理的 ...

  10. 共享参数ContentProvider 类与数据库绑定,如何通过共享参数测试类,测试数据库的增删改查功能

    Intent可以传一个对象 当两个界面之间跳转时,需要传递一个对象过去,是通过使用Bundle类,并且实体类需要serializable实现序列化,传递方法如下: 定义一个静态常量作为key值 pub ...

随机推荐

  1. 从零玩转Yaip使用-cong-ling-wan-zhuan-yaip-shi-yong

    title: 从零玩转Yaip使用 date: 2021-07-16 15:47:17.624 updated: 2021-12-26 17:43:12.255 url: https://www.yb ...

  2. k8s在删除pod时优雅关闭sigterm信号传输失败

    背景 随着云原生技术的流行,越来越多的应用选择容器化,容器化的话题自然离不开 Kubernetes .Pod 是 Kubernetes 中创建和管理的.最小的可部署的计算单元,一个 Pod 中有多个容 ...

  3. 5分钟就能实现的API监控,有什么理由不做呢?基调听云

    API深度影响着你的应用 今天的数字应用世界其实是一个以API为中心的世界,我们只是没有意识到这些API的重要性.比如在电子商务交易.社交媒体等对交互高度依赖的领域,可以说API决定了应用的质量一点也 ...

  4. Java 给PPT中的表格设置分布行和分布列

    在表格中可设置"分布行"或"分布列"将行高.列宽调整为协调统一的高度或宽度,是一种快速实现表格排版的方法之一.下面,通过Java后端程序代码介绍如何在PPT幻灯 ...

  5. C# 在Word中添加Latex 数学公式和符号

    本篇内容介绍使用Spire.Doc for .NET在Word中添加Latex数学公式和符号的方法.编辑代码前,将Spire.Doc.dll文件添加引用至VS程序.dll文件包可通过官网下载导入(如果 ...

  6. 图解 Redis丨这就是 RDB 快照,能记录实际数据的

    摘要:所谓的快照,就是记录某一个瞬间东西,比如当我们给风景拍照时,那一个瞬间的画面和信息就记录到了一张照片.RDB 快照就是记录某一个瞬间的内存数据,记录的是实际数据. 本文分享自华为云社区<图 ...

  7. 华为云UGO:醒醒!你的异构数据库迁移难题有救了

    摘要:华为云推出的数据库和应用迁移 UGO,正是一款专注于异构数据库结构迁移和应用SQL转换的专业云服务. 数字化时代下,上云已成为企业管理者的基本共识,随着技术日新月异,上云也变得轻松简单起来,但异 ...

  8. SyntaxError: Non-ASCII character #-*- coding:utf-8 -*-

    执行python报错 /usr/bin/python2.7 /root/demo.py File "/root/demo.py", line 2 SyntaxError: Non- ...

  9. 莉莉丝游戏与火山引擎 ByteHouse 达成合作,为实时数仓建设提速

    中国头部游戏公司莉莉丝游戏(Lilith Games)和火山引擎 ByteHouse 达成合作,共同致力于加速莉莉丝游戏的实时数仓建设.此次合作将利用 ByteHouse 的创新技术和功能,为莉莉丝的 ...

  10. allowedOrigins cannot contain the special value "*"

    Spring Boot的版本高于 2.4以后 ,原来的配置已经不适合目前的版本 将代码中的allowedOrigins改为allowedOriginPatterns @Configuration pu ...