今天来总结下Android中几种数据存储方式:
本篇文章主要介绍前面的三种存储方式,ContentProvider在学习Android四大组件的时候有过介绍,下面通过一张图先来了解下今天要学习的三种存储方式默认的存储位置。
1.内部存储
Android中写入文件和读取文件提供了openFileOutput()和openFileIntput()方法.下面分别介绍这两个方法的使用.
(1)openFileOutput()
private void writeData() {
String data = "这是我要存储的数据";
FileOutputStream fileOutputStream = null;
BufferedWriter bufferedWriter = null;
try {
fileOutputStream = openFileOutput("data", Context.MODE_PRIVATE);
bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
bufferedWriter.write(data);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
注意:openFileOutput()的第二个参数表示文件的操作模式,常用的可选值如下图所示:
(2)openFileIntput()
private void readData() {
FileInputStream fileInputStream = null;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer = new StringBuffer();
try {
fileInputStream = openFileInput("data");
bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.外部存储
外部存储指的是可移除的存储介质(如SD卡),保存到外部存储的文件是全局可读取文件,其存储也可以分为两种情况.
(1)应用卸载后,存储数据会被删除
File externalCacheDir = getExternalCacheDir();
//返回路径 /storage/emulated/0/Android/data/{packageName}/cache
String absolutePath = externalCacheDir.getAbsolutePath();
File externalFilesDir = getExternalFilesDir(null);
//返回路径 /storage/emulated/0/Android/data/{packageName}/files
String absolutePath1 = externalFilesDir.getAbsolutePath();
File file = new File(absolutePath, "demo.text");
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(file);
//TODO
(2)应用卸载后,存储数据不会被删除
//返回路径 /storage/emulated/0
String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
String directory = absolutePath + "/demo.txt";
try {
FileOutputStream out = new FileOutputStream(directory);
out.write("测试数据".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
二.SharedPreferences
SharedPreferences是一种轻型的数据存储方式,常用来存储一些简单的配置信息,它的本质是基于XML文件存储key-value键值对.
1.使用步骤
存储数据
(1)调用getSharedPreferences()获取SharedPreferences对象,提供两个参数,指定文件名和操作方式.
(2)调用SharedPreferences对象的edit()方法获得SharedPreferences.Editor引用对象.
(3)调用Edit接口的put方法以键值对的形式保存数据.
(4)调用Edit接口的commit方法提交键值对.
注意:SharedPreferences是通过Editor对象来存储和修改数据.
获取数据
(1)调用SharedPreferences对象的get方法.
2.代码示例
//SharedPreferences存储数据
SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
SharedPreferences.Editor edit = sp.edit();
edit.putString("name","admin");
edit.putString("password","123456");
edit.commit();
//SharedPreferences获取数据
String name = sp.getString("name",null);
String password = sp.getString("password", null);
Log.d("login",name+":"+password);
三.SQLite
SQLite是一款轻量级的关系型数据库,它运算快,占用资源少,适用于小数据量的存储.
1.使用步骤
(1)自定义帮助类继承SQLiteOpenHelper,重写两个方法:onCreate()和onUpgrade(),它们分别实现创建和升级数据库的逻辑.
(2)创建数据库时,先实例化一个自定义的帮助类,传入参数(上下文,数据库名,Cursor工厂类,版本号).
(3)用帮助类对象的getReadableDatabase()和getWritableDatabase()方法去创建或打开一个现有的数据库,并返回一个可读写数据库SQLiteDatabase.
(4)利用数据库进行增删改查的操作.
注意:getReadableDatabase()和getWritableDatabase()的区别
getWritableDatabase()取得的实例是以读写的方式打开数据库,如果打开的数据库磁盘满了,则只能读不能写,此时如果调用了getWritableDatabase的实例,就会报异常.
getReadableDatabase()取得的实例是先调用getWritableDatabase()以读写的方式打开数据库,如果数据库磁盘满了,则返回打开失败,继而调用getReadableDatabase()的实例以只读的方式打开数据库.
2.具体使用
(1)自定义帮助类
public class MySQLiteHelper extends SQLiteOpenHelper {
public Context mContext;
public static String CREATE_STUDENT = "create table student ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "age integer,"
+ "grade text)";
public MySQLiteHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_STUDENT);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
(2)创建数据库
MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(this, "student.db", null, 1);
SQLiteDatabase database = mySQLiteHelper.getReadableDatabase();
(3)增删改查操作
//添加数据
ContentValues contentValues = new ContentValues();
contentValues.put("name","lili");
contentValues.put("age","12");
contentValues.put("grade","grade1");
mDatabase.insert("student",null,contentValues);
//删除数据
mDatabase.delete("student","age>?",new String[]{"17"});
//更新数据
ContentValues values = new ContentValues();
values.put("grade","grade2");
mDatabase.update("student",values,"name=?",new String[]{"lili"});
//查询数据
Cursor cursor = mDatabase.query("student", null, null, nmull, null, null, null);
if (cursor != null) {
while (cursor.moveToNext()) {
String name = cursor.getString(cursor.getColumnIndex("name"));
String age = cursor.getString(cursor.getColumnIndex("age"));
String grade = cursor.getString(cursor.getColumnIndex("grade"));
Log.d("student",name+":"+age+":"+grade);
}
cursor.close();
}
(3)升级数据库
这里添加一张新表course ,增加版本号,升级数据库.
public class MySQLiteHelper extends SQLiteOpenHelper {
public Context mContext;
public static String CREATE_STUDENT = "create table student ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "age integer,"
+ "grade text)";
public static String CREATE_COURSE = "create table course ("
+ "id integer primary key autoincrement,"
+ "name text,"
+ "credit integer)";
public MySQLiteHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
this.mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_STUDENT);
db.execSQL(CREATE_COURSE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 1:
db.execSQL(CREATE_COURSE);
break;
}
}
}
MySQLiteHelper mySQLiteHelper = new MySQLiteHelper(this, "student.db", null, 2);