数据存储的五种方式
文件存储是一种较常用的方法,与Java中的文件存储类似,都是通过I/O流的形式存储数据。
SharedPreferences是Android提供的用来存储一些简单的配置信息的一种机制。
SQLite数据库是Android自带的一个轻量级数据库,支持基本SQL语法。Room是官方对 SQLite一个框架。
ContentProvider是Android四大组件之一,可以将自己的数据共享给其他应用程序。
网络存储是通过网络提供的存储空间来存储/获取数据信息。
文件读写:
String fileName = "data.txt";
String content = "helloworld";
FileOutputStream fos;
try {//写文件
fos = Activity.openFileOutput(fileName, MODE_PRIVATE);
fos.write(content.getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
String content = "";
FileInputStream fis;
try {//读文件
fis = Activity.openFileInput("data.txt");
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
content = new String(buffer);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
build.gradle文件中applicationId指定包名,位置在Device File Explorer中data/data/{applicationId}
SharedPreferences
SharedPreferences是Android平台上一个轻量级的存储类。
用于存储应用程序的配置参数,如用户名、密码等。
通过key/value(键值对)的形式将数据保存在XML文件中。
value值只能是float、int、long、boolean、String、StringSet 类型数据。
存储数据:
SharedPreferences sp = Activity.getSharedPreferences("data",MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
editor.putString("name", "woshishabei");
editor.putInt("age", 8);
editor.commit();
获取数据:
获取数据可以直接通过SharedPreferences对象的getXXX()方法 来实现。
SharedPreferences sp = Activity.getSharedPreferences("data",MODE_PRIVATE);
String data = sp.getString("name","亲,没有这个键哦!");//第二个参数是在找不到第一个参数时返回的值
JSON
JSON即JavaScript Object Notation(对象表示法),是一种轻量级的数据交换格式。
JSON是基于纯文本的数据格式,它可以传输String、Number、Boolean类型的数据,也可以 传输数组,或者Object对象。
JSON文件的扩展名为.json。
JSON分为JSON对象和JSON数组两种数据结构。
json的两种解析方式:
org.json,Android sdk中为开发者提供的,通过使用JSONObject和JSONArray两个类完成 对JSON数据的解析。
Gson,由Google公司提供的,在使用Gson库之前,首先需要将gson.jar添加到项目中,然 后才能调用其提供的方法。
Maven Repository: Search/Browse/Explore (mvnrepository.com)
//解析json对象
Gson gson = new Gson();
Person person = gson.fromJson(json1, Person.class);
//解析json数组
Gson gson = new Gson();
Type listType = new TypeToken<List<Integer>>(){}.getType();
//List<Student> list = gson.fromJson(jsonData, new TypeToken<List<Student>>(){}.getType());
List<Integer> ages = gson.fromJson(json2, listType);