本文是威哥总结了Android存储数据存储方式和大家分享,同时重点是介绍威哥自行封装的SharedPreferences存储泛型T数据。
Android存储数据5种方式:
1 、文件存储数据;
2 、SQLite数据库存储数据;
3、 使用SharedPreferences存储数据;
4 、使用ContentProvider存储数据;
5 、网络存储数据。
1)文件存储
文件存储方式是一种较常用的方法,在Android中读取/写入文件的方法,与Java中实现I/O的程序是完全一样的,提供openFileInput()和openFileOutput()方法来读取设备上的文件。
核心原理: Context提供了两个方法来打开数据文件里的文件IO流 FileInputStream openFileInput(String name); FileOutputStream(String name , int mode),这两个方法第一个参数 用于指定文件名,第二个参数指定打开文件的模式。具体有以下值可选:
MODE_PRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可 以使用Context.MODE_APPEND
MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
MODE_WORLD_READABLE:表示当前文件可以被其他应用读取;
MODE_WORLD_WRITEABLE:表示当前文件可以被其他应用写入。
除此之外,Context还提供了如下几个重要的方法:
getDir(String name , int mode):在应用程序的数据文件夹下获取或者创建name对应的子目录
File getFilesDir():获取该应用程序的数据文件夹得绝对路径
String[] fileList():返回该应用数据文件夹的全部文件
文件存储参考代码:
public String read() {
try {
FileInputStream inStream = this.openFileInput("message.txt");
byte[] buffer = new byte[1024];
int hasRead = 0;
StringBuilder sb = new StringBuilder();
while ((hasRead = inStream.read(buffer)) != -1) {
sb.append(new String(buffer, 0, hasRead));
}
inStream.close();
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public void write(String msg){
// 步骤1:获取输入值
if(msg == null) return;
try {
// 步骤2:创建一个FileOutputStream对象,MODE_APPEND追加模式
FileOutputStream fos = openFileOutput("message.txt",
MODE_APPEND);
// 步骤3:将获取过来的值放入文件
fos.write(msg.getBytes());
// 步骤4:关闭数据流
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2)SQLite数据库
SQLite是Android所集成的一个轻量级的嵌入式数据库,它不仅可以使用Andorid API操作,同时它也支持SQL语句进行增删改查等操作,通常Sqlite我们使用封装好的框架:greendao,但是在Android3.0之后greendao引入变得困难。
3)SharedPreferences
SharedPreferences是Android提供的用于存储一些简单配置信息的一种机制,采用了XML格式将数据存储到设备中。不仅可以在同一个包下使用,还可以访问其他应用程序的数据,但是由于SharedPreferences的局限性,在实际操作中很少用来读取其他应用程序的数据。
适用范围:保存少量的数据,且这些数据的格式非常简单:字符串型、基本类型的值。比如应用程序的各种配置信息。
核心原理:保存基于XML文件存储的key-value键值对数据,通常用来存储一些简单的配置信息。通过DDMS的File Explorer面板,展开文件浏览树,很明显SharedPreferences数据总是存储在/data/data/<package name>/shared_prefs目录下。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过SharedPreferences.edit()获取的内部接口Editor对象实现。 SharedPreferences本身是一 个接口,程序无法直接创建SharedPreferences实例,只能通过Context提供的getSharedPreferences(String name, int mode)方法来获取SharedPreferences实例,该方法中name表示要操作的xml文件名,第二个参数具体如下:
Context.MODE_PRIVATE: 指定该SharedPreferences数据只能被本应用程序读、写。
Context.MODE_WORLD_READABLE: 指定该SharedPreferences数据能被其他应用程序读,但不能写。
Context.MODE_WORLD_WRITEABLE: 指定该SharedPreferences数据能被其他应用程序读,写
Editor有如下主要重要方法:
SharedPreferences.Editor clear():清空SharedPreferences里所有数据
SharedPreferences.Editor putXxx(String key , xxx value): 向SharedPreferences存入指定key对应的数据,其中xxx 可以是boolean,float,int等各种基本类型据
SharedPreferences.Editor remove(): 删除SharedPreferences中指定key对应的数据项
boolean commit(): 当Editor编辑完成后,使用该方法提交修改
使用步骤:
1、得到SharedPreferences对象
2、调用SharedPreferences对象的edit()方法来获取一个SharedPreferences.Editor对象。
3、向SharedPreferences.Editor对象中添加数据。
4、调用commit方法将添加的数据提交。
简单代码说明:
存储数据:
//获取sharedPreferences对象
SharedPreferences sharedPreferences = getSharedPreferences("zjl", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //获取editor对象
//开始存储键值对
editor.putString("name", "威哥"); editor.putInt("age", 30);
editor.putBoolean("isMarried", true);
editor.putLong("height", 167L);
editor.putFloat("weight", 60f);
editor.putStringSet("where", set);
editor.commit(); //提交修改
获取数据:
SharedPreferences sharedPreferences = getSharedPreferences("zjl", Context.MODE_PRIVATE);
String name = sharedPreferences.getString("name", ""); i
nt age = sharedPreferences.getInt("age", 1);
4)ContentProvider
ContentProvider主要用于不同应用程序之间共享数据,ContentProvider更好的提供了数据共享接口的统一性,使不同应用共享数据更规范和安全。
5)网络存储数据
通过网络上提供的存储空间来上传。
本文重点是威哥自行封装的泛型T数据处理,威哥直接上代码。
1.SharedPreferences封装帮助类:
package com.example.msh.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;
/**
* SharedPreference帮助类
* Author:William(徐威)
* Create Time:2018-11-06
*/
public class SharedPreferenceHelper {
/**
* 在SharedPreferences存储实体类对象新(实体类必须可以序列化)
* Author:William(徐威)
* Create Time:2018-11-06
*
* @param context
* @param model
* @param key
* @param <T>
*/
public static <T> void putT(Context context, T model, String key) {
try {
String strJosn = JsonHelper.converJavaBeanToJson(model);
SharedPreferences shared = context.getSharedPreferences(String.format("msh_%s", key), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit(); //获取编辑器
editor.putString(key, strJosn); //存储键值对
editor.commit(); //提交
} catch (Exception ex) {
ex.printStackTrace();
Log.e("SharedPreferenceHelper", String.format("putT报错:%s。", ex.getMessage()));
}
}
/**
* 从SharedPreferences取实体类信息
* Author:William(徐威)
* Create Time:2018-11-06
*
* @param context
* @param tClass
* @param key
* @param <T>
* @return
*/
public static <T> T getT(Context context, Class<T> tClass, String key) {
try {
SharedPreferences shared = context.getSharedPreferences(String.format("msh_%s", key), Context.MODE_PRIVATE);
String strJosn = shared.getString(key, "");
T model = null;
if (!TextUtils.isEmpty(strJosn)) {
model = JsonHelper.parsr(strJosn, tClass);
}
return model;
} catch (Exception ex) {
ex.printStackTrace();
Log.e("SharedPreferenceHelper", String.format("getT报错:%s。", ex.getMessage()));
throw ex;
}
}
/**
* 判断某实体类对象是否在SharedPreferences存在
* Author:William(徐威)
* Create Time:2018-11-06
*
* @param context
* @param tClass
* @param key
* @param <T>
* @return
*/
public static <T> boolean isExist(Context context, Class<T> tClass, String key) {
try {
return getT(context, tClass, key) == null ? false : true;
} catch (Exception ex) {
ex.printStackTrace();
Log.e("SharedPreferenceHelper", String.format("isExist报错:%s。", ex.getMessage()));
throw ex;
}
}
}
2.代码使用:
if(SharedPreferenceHelper.isExist(IndexActivity.this,AndroidMachineBaseInfo.class,"AndroidMachineBaseInfo")){
//共享内存存在机器基础信息,直接初始化信息
MachineBaseInfo.initMachineInfo(IndexActivity.this);
}
else {//共享内存SharedPreference中不存在,则发起服务请求,获取信息后调用持久化存储信息
。。。威哥业务省略
StoreAndroidMachineDtoInfo machineModel = response.getResults().get(0);
AndroidMachineBaseInfo machineCurrModel = new AndroidMachineBaseInfo();
machineCurrModel.setMachineSN(MachineBaseInfo.MachineSN);
machineCurrModel.setMachineNo(machineModel.MachineNo);
machineCurrModel.setStockSysNo(machineModel.StockSysNo);
machineCurrModel.setStockName(machineModel.V_StockName);
machineCurrModel.setAddress(machineModel.V_Address);
machineCurrModel.setPhone(machineModel.V_Phone);
machineCurrModel.setFastQRCodeName(machineModel.V_FastQRCodeName);
machineCurrModel.setFastQRCodeUrl(machineModel.V_FastQRCodeUrl);
machineCurrModel.setLongitude(machineModel.getV_Longitude());
machineCurrModel.setLatitude(machineModel.getV_Latitude());
//持久化机器基础信息
SharedPreferenceHelper.putT(IndexActivity.this,machineCurrModel,"AndroidMachineBaseInfo");
}
注意,本文使用到了Gson的封装类,威哥也可以和大家一起分享:
/*Json帮助类
Author :William(徐威)
Create Time:2018-07-21*/
public class JsonHelper {
/**
* 将Json格式数据转换为对应实体类输出
* Author:William(徐威)
* Create Time:2018-08-13
* @param strResJson
* @param tClass
* @param <T>
* @return
*/
public static <T> T convetJsonToClass(String strResJson, Class<T> tClass) {
T response = null;
try {
if (strResJson != null && strResJson.length() != 0) {
JSONObject jsonObject = new JSONObject(strResJson);
String jsonContent = jsonObject.getString("javaJsonContent");
if (jsonContent != null && jsonContent.length() != 0) {
response = parsr(jsonContent, tClass);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return response;
}
/**
* 将JSON字符串转换成javabean
* Author:William(徐威)
* Create Time:2018-08-13
*
* @param json
* @param tClass
* @param <T>
* @return
*/
public static <T> T parsr(String json, Class<T> tClass) {
try {
//判读字符串是否为空
if (TextUtils.isEmpty(json)) {
return null;
}
Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
// if (gson == null) {
// gson = new Gson();
// }
T result = gson.fromJson(json, tClass);
return result;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将javabean转换成JSON字符串
* Author:William(徐威)
* Create Time:2018-08-13
*
* @param obj
* @return
*/
public static String converJavaBeanToJson(Object obj) {
if (obj == null) {
return "";
}
Gson gson = new Gson();
// if (gson == null) {
// gson = new Gson();
// }
String beanstr = gson.toJson(obj);
if (!TextUtils.isEmpty(beanstr)) {
return beanstr;
}
return "";
}
/**
* 将List泛型数据转换为Json字符串
* Author:William(徐威)
* Create Time:2018-10-16
*
* @param list
* @return
*/
public static String converListToJson(List<?> list) {
if (list == null) {
return "";
}
Gson gson = new Gson();
String beanstr = gson.toJson(list);
if (!TextUtils.isEmpty(beanstr)) {
return beanstr;
}
return "";
}
/**
* 将Json转换为泛型List
* Author:William(徐威)
* Create Time:2018-10-16
*
* @param strResJson
* @param <T>
* @return
*/
public static <T> List<T> convetJsonToList(String strResJson, Class<T> tClass) {
List<T> list = null;
try {
if (!TextUtils.isEmpty(strResJson)) {
list = new ArrayList<T>();
Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
List<T> listTemp = gson.fromJson(strResJson, new TypeToken<List<T>>() {
}.getType());
for (int i = 0; i < listTemp.size(); i++) {
String strJsonTemp = gson.toJson(listTemp.get(i));
T bean = gson.fromJson(strJsonTemp, tClass);
list.add(bean);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
/**
* 将Json字符串转换为List泛型数据
* Author:William(徐威)
* Create Time:2018-10-16
*
* @param strJson
* @param type
* @return
*/
public static <T> List<T> convetJsonToList(String strJson, Type type) {
List<T> list = null;
try {
if (!TextUtils.isEmpty(strJson)) {
Gson gson = new GsonBuilder().registerTypeAdapter(Timestamp.class, new TimestampTypeAdapter()).setDateFormat("yyyy-MM-dd HH:mm:ss").create();
list = gson.fromJson(strJson, type);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return list;
}
}
威哥本次博客分享完成,期待下次和大家一起共勉。。。