20240204
Android 的数据存储
Android系统中主要提供了3种方式用于简单地实现数据持久化功能:文件存储、
SharedPreferences存储以及数据库存储
文件存储
fun save(inputText: String) {
try {
val output = openFileOutput("data", Context.MODE_PRIVATE)
val writer = BufferedWriter(OutputStreamWriter(output))
writer.use {
it.write(inputText)
}
} catch (e: IOException) {
e.printStackTrace()
}
}
//读取
fun load(): String {
val content = StringBuilder()
try {
val input = openFileInput("data")
val reader = BufferedReader(InputStreamReader(input))
reader.use {
reader.forEachLine {
content.append(it)
}
}
} catch (e: IOException) {
e.printStackTrace()
}
return content.toString()
}
SharedPreferences存储
//存储
val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
editor.putString("name", "Tom")
editor.putInt("age", 28)
editor.putBoolean("married", false)
editor.apply()
//读取
val prefs = getSharedPreferences("data", Context.MODE_PRIVATE)
val name = prefs.getString("name", "")
val age = prefs.getInt("age", 0)
val married = prefs.getBoolean("married", false)
SQLite数据库存储
//新建MyDatabaseHelper类继承自SQLiteOpenHelper
class MyDatabaseHelper(val context: Context, name: String, version:Int) :SQLiteOpenHelper(context, name, null, version) {
private val createBook = "create table Book (" +
" id integer primary key autoincrement," +
"author text," +
"price real," +
"pages integer," +
"name text)"
override fun onCreate(db: SQLiteDatabase) { //建表
db.execSQL(createBook)
Toast.makeText(context, "Create succeeded", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
//更新数据库
db.execSQL("drop table if exists Book")
db.execSQL("drop table if exists Category")
onCreate(db)
}
}
//插入数据库
val db = dbHelper.writableDatabase
val values1 = ContentValues().apply {
// 组装数据
put("name", "The Da Vinci Code")
put("author", "Dan Brown")
put("pages", 454)
put("price", 16.96)
}
//插入
db.insert("Book", null, values1)
//更新数据
val db = dbHelper.writableDatabase
val values = ContentValues()
values.put("price", 10.99)
db.update("Book", values, "name = ?", arrayOf("The Da Vinci Code"))
//删除数据
val db = dbHelper.writableDatabase
db.delete("Book", "pages > ?", arrayOf("500"))
//查询数据
val cursor = db.query("Book", null, null, null, null, null, null)
//query的参数 table,columns,selection,groupBy,having,orderBy
数据和文件存储概览
- 应用专属存储空间:存储仅供应用使用的文件,可以存储到内部存储卷中的专属目录或外部存储空间中的其他专属目录。使用内部存储空间中的目录保存其他应用不应访问的敏感信息。
- 共享存储:存储您的应用打算与其他应用共享的文件,包括媒体、文档和其他文件。
- 偏好设置:以键值对形式存储私有原始数据。
- 数据库:使用 Room 持久性库将结构化数据存储在专用数据库中。