Kotlin數(shù)據(jù)存儲方式全面總結(jié)講解
1、文件存儲
文件存儲是Android中最基本的數(shù)據(jù)存儲方式,它不對存儲的內(nèi)容進行任何格式化處理,有數(shù)據(jù)都是原封不動地保存在文件當中的,因此它比較適合存儲一些簡單的文本數(shù)據(jù)或者二進制數(shù)據(jù)。
(1)將數(shù)據(jù)存儲在文件中
Context類中提供了一個openFileOutput()方法,用于將數(shù)據(jù)存儲到指定的文件中。
第一個參數(shù):文件名(系統(tǒng)會自動創(chuàng)建這個文件)。
第二個參數(shù):文件的操作模式。
文件的操作模式有以下幾種:
- Context.MODE_PRIVATE:私有覆蓋模式。只能被當前應用訪問,并且如果寫入,則覆蓋。
- Context.MODE_APPEND:私有追加模式。只能被當前應用訪問,并且如果寫入,則追加。
- Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE已在Android4.2版本中被廢除。
具體實現(xiàn):
private fun save(inputText: String) {
try {
val output=openFileOutput("data", Context.MODE_PRIVATE)
val writer=BufferedWriter(OutputStreamWriter(output))
//這里使用了kotlin的內(nèi)置函數(shù)use,它會保證在Lambda
//表達式中的代碼全部執(zhí)行完之后自動將外層的流關(guān)閉,這
//樣就不再需要我們寫一個finally語句,手動關(guān)閉流。
writer.use {
it.write(inputText)
}
Toast.makeText(this,inputText,Toast.LENGTH_SHORT).show()
}catch (e:IOException){
e.printStackTrace()
}
}如何證實數(shù)據(jù)是否已經(jīng)保存成功了呢?
使用快捷鍵Ctrl+Shift+A(Mac系統(tǒng)是command+shift+A)打開搜索功能,在搜索框輸入“Device File Explorer”即可找到這個工具,我們在這工具里找到/data/data/com.example.filepersistencetest/files/目錄,里面有一個生成的data文件,雙擊打開,查看里面的內(nèi)容。
(2)從文件中讀取數(shù)據(jù)
Context類提供的openFileinput()方法,用于從文件中讀取數(shù)據(jù)。
參數(shù):文件名。
具體實現(xiàn):
private fun load():String{
val content=StringBuilder()
try {
val input=openFileInput("data")
val reader=BufferedReader(InputStreamReader(input))
//kotlin提供的內(nèi)置擴展函數(shù)forEachLine,它會將讀到的內(nèi)容都回調(diào)到Lambda表達式中。
reader.use {
reader.forEachLine {
content.append(it)
}
}
}catch(e:IOException){
e.printStackTrace()
}
return content.toString()
}(3)實戰(zhàn)演練:重新啟動程序時EditText中能保留我們上次輸入的內(nèi)容。、
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val inputText=load()
if(inputText.isNotEmpty()){
val editText:EditText=findViewById(R.id.editText)
editText.setText(inputText)
editText.setSelection(inputText.length)
}
}
override fun onDestroy() {
super.onDestroy()
val editText:EditText=findViewById(R.id.editText)
val inputText=editText.text.toString()
save(inputText)
}
private fun save(inputText: String) {
try {
val output=openFileOutput("data", Context.MODE_PRIVATE)
val writer=BufferedWriter(OutputStreamWriter(output))
writer.use {
it.write(inputText)
}
Toast.makeText(this,inputText,Toast.LENGTH_SHORT).show()
}catch (e:IOException){
e.printStackTrace()
}
}
private 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()
}
}2、SharedPreferences存儲
不同于文件存儲,SharedPreferences是使用鍵值對的方式來存儲數(shù)據(jù)的。
Context類中的getSharedPreferences()方法,獲取SharedPreferences對象。
第一個參數(shù):指定SharedPreferences文件的名稱。(如果指定文件的名稱不存在就會創(chuàng)建一個,SharedPreferences文件都是存放在/data/data/<package name>/shared_prefs目錄)。
第二個參數(shù):指定操作模式。只有MODE_PRIVATE可選,MODE_PRIVATE:只有當前的應用程序才可以對這個SharedPreferences文件進行讀寫。
將數(shù)據(jù)存儲到SharedPreferences中
具體實現(xiàn):
val editor=getSharedPreferences("data", Context.MODE_PRIVATE).edit()
editor.putString("name","Tom")
editor.putInt("age",28)
editor.putBoolean("married",false)
editor.apply()//提交如何證實數(shù)據(jù)是否已經(jīng)保存成功了呢?
使用快捷鍵Ctrl+Shift+A(Mac系統(tǒng)是command+shift+A)打開搜索功能,在搜索框輸入“Device File Explorer”即可找到這個工具,我們在這工具里找到/data/data/com.example.sharedpreferencestest/shared_prefs/目錄,里面有一個生成的data.xml文件,雙擊打開,查看里面的內(nèi)容。
從sharedpreferences中讀取數(shù)據(jù)
具體實現(xiàn)
val prefs=getSharedPreferences("data",Context.MODE_PRIVATE)
val name=prefs.getString("name","")
val age=prefs.getInt("age",0)
val married=prefs.getBoolean("married",false)
Log.d("MainActivity","name is $name")
Log.d("MainActivity","age is $age")
Log.d("MainActivity","married is $married")3、SQLite數(shù)據(jù)庫存儲


創(chuàng)建數(shù)據(jù)庫
SQLiteOpenHelper類是一個抽象類,有兩個抽象方法,onCreate()和onUpgrade()。
- onCreate(SQLiteDatabase):在數(shù)據(jù)第一次生成的時候會調(diào)用這個方法,也就是說,只有創(chuàng)建數(shù)據(jù)庫的時候才會調(diào)用,還可以在這個方法里生成數(shù)據(jù)庫表。
- onUpgrade(SQLiteDatabase,int,int):當數(shù)據(jù)庫需要升級的時候,Android系統(tǒng)會自動調(diào)用這個方法,一般在這個方法里刪除數(shù)據(jù)表,并建立新的數(shù)據(jù)表。

SQLiteOpenHelper類的構(gòu)造方法:
第一個參數(shù):Context
第二個參數(shù):數(shù)據(jù)庫名
第三個參數(shù):運行我們在查詢數(shù)據(jù)時放回一個自定義的Cursor,一般傳入null即可
第四個參數(shù):表明當前數(shù)據(jù)庫的版本號
步驟
定義SQLiteOpenHelper的子類,在該類中創(chuàng)建一個名為BookStore.db的數(shù)據(jù)庫
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)"
private val createCategory = "create table Category(" +
"id integer primary key autoincrement," +
"category_name text," +
"category_code integer)"
override fun onCreate(p0: SQLiteDatabase?) {
if (p0 != null) {
p0.execSQL(createBook)
p0.execSQL(createCategory)
}
Toast.makeText(context,"Create succeeded",Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
if (p0 != null) {
p0.execSQL("drop table if exists Book")
p0.execSQL("drop table if exists Category")
onCreate(p0)
}
}
}調(diào)用MyDatabaseHelper類完成表的創(chuàng)建
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
dbHelper.writableDatabase
}
}升級數(shù)據(jù)庫
把
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
改為
val dbHelper=MyDatabaseHelper(this,"BookStore.db",2)
表示數(shù)據(jù)庫升級
添加數(shù)據(jù)
insert():專門用于添加數(shù)據(jù)。
第一個參數(shù):表名
第二個參數(shù):用于在未指定添加數(shù)據(jù)的情況下給某些可為空的列自動賦值給NULL,一般用不到這個功能,傳入null即可。
第三個參數(shù):ContentValues對象

步驟
獲取SQLiteDatabase對象
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1) val db=dbHelper.writableDatabase
使用ContentValues對要添加的數(shù)據(jù)進行組裝
val values1=ContentValues().apply {
put("name","The Da Vinci Code")
put("author","Dan Brown")
put("pages",454)
put("price",16.96)
}調(diào)用insert()方法將數(shù)據(jù)添加到表中
db.insert("Book",null,values1)更新數(shù)據(jù)
updata():對數(shù)據(jù)進行更新。
參數(shù):第一個參數(shù):表名,指定更新哪張表的數(shù)據(jù)。
第二個參數(shù):ContentValues對象,要把更新數(shù)據(jù)在這里組裝進去。
第三、四個參數(shù):用于約束更新某一行或某幾行的數(shù)據(jù),不指定的話默認會更新所有行。
步驟
獲取SQLiteDatabase對象
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1) val db=dbHelper.writableDatabase
構(gòu)建ContentValues對象,并且給它指定一組數(shù)據(jù),說明把價格這一系列的數(shù)據(jù)更新成10.99。
val values=ContentValues()
values.put("price",10.99)調(diào)用SQLiteDatabase的updata()執(zhí)行具體的更新操作。
db.update("Book",values,"name=?", arrayOf("The Da Vinci Code"))刪除數(shù)據(jù)
delete()方法:專門用于刪除數(shù)據(jù)。
第一個參數(shù):表名
第二、三個參數(shù):用于約束刪除某一行或者某幾行的數(shù)據(jù),不指定的話會默認刪除所有行。
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
val db=dbHelper.writableDatabase
db.delete("Book","pages>?", arrayOf("500"))查詢數(shù)據(jù)

步驟
獲取SQLiteDatabase對象
val dbHelper=MyDatabaseHelper(this,"BookStore.db",1) val db=dbHelper.writableDatabase
調(diào)用query()方法后會返回一個Cursor對象,查詢到的所有數(shù)據(jù)都可以從這個對象中取出。
val cursor=db.query("Book",null,null,null,null,null,null)
//查詢完后獲得一個Cursor對象,接著我們調(diào)用它的moveToFirst()方法,
//將數(shù)據(jù)的指針移動到第一行的位置,
//然后進入一個循環(huán)當中,去遍歷查詢到的每一行數(shù)據(jù)
if(cursor.moveToFirst()){
do{
val name=cursor.getString(cursor.getColumnIndex("name"))
val author=cursor.getString(cursor.getColumnIndex("author"))
val pages=cursor.getInt(cursor.getColumnIndex("pages"))
val price=cursor.getDouble(cursor.getColumnIndex("price"))
Log.d("MainActivity","Book name is $name")
Log.d("MainActivity","Book author is $author")
Log.d("MainActivity","Book pages is $pages")
Log.d("MainActivity","Book price is $price")
}while (cursor.moveToNext())
}
cursor.close()4、使用SQL操作數(shù)據(jù)庫
使用SQL來完成前面學過的CRUD操作。
添加數(shù)據(jù):
db.execSQL("insert into Book(name, author, pages, price) values(?,?,?,?)",
array0f("The Da Vinci Code","Dan Brown","454","16.96")
)
db.execSQL("insert into Book(name, author, pages, price) values(?,?,?,?)",
array0f("The Lost Symbol","Dan Brown","510","19.95")
)更新數(shù)據(jù):
db.execSQL("update Book set price=? where name=?",array0f("10.99","The Da Vinci Code"))刪除數(shù)據(jù):
db.execSQL("delete from Book where pages>?",array0f("500"))查詢數(shù)據(jù):
val cursor=db.rawQuery("select*from Book", null)到此這篇關(guān)于Kotlin數(shù)據(jù)存儲方式全面總結(jié)講解的文章就介紹到這了,更多相關(guān)Kotlin數(shù)據(jù)存儲內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Android實現(xiàn)recyclerview城市字母索引列表
大家好,本篇文章主要講的是Android實現(xiàn)recyclerview城市字母索引列表,感興趣的同學趕快來看一看吧,對你有幫助的話記得收藏一下2022-01-01
Android?實現(xiàn)單指滑動雙指縮放照片demo及過程解析
這篇文章主要為大家介紹了Android?實現(xiàn)單指滑動雙指縮放照片demo及過程解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
MVVMLight項目Model?View結(jié)構(gòu)及全局視圖模型注入器
這篇文章主要為大家介紹了MVVMLight項目中Model及View的結(jié)構(gòu)及全局視圖模型注入器的使用說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-01-01
Android向node.js編寫的服務器發(fā)送數(shù)據(jù)并接收請求
這篇文章主要為大家詳細介紹了Android向node.js編寫的服務器發(fā)送數(shù)據(jù),并接收請求,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
深入Android Handler,MessageQueue與Looper關(guān)系
這篇文章主要介紹了深入Android Handler,MessageQueue與Looper關(guān)系,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-08-08

