最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Kotlin數(shù)據(jù)存儲(chǔ)方式全面總結(jié)講解

 更新時(shí)間:2022年12月02日 10:06:13   作者:Hdnw  
在開發(fā)過程中,數(shù)據(jù)存取是較為頻繁的,今天我們來(lái)了解下android幾種常見的數(shù)據(jù)存取方式,有需要的朋友可以借鑒參考下,希望能夠有所幫助

1、文件存儲(chǔ)

文件存儲(chǔ)是Android中最基本的數(shù)據(jù)存儲(chǔ)方式,它不對(duì)存儲(chǔ)的內(nèi)容進(jìn)行任何格式化處理,有數(shù)據(jù)都是原封不動(dòng)地保存在文件當(dāng)中的,因此它比較適合存儲(chǔ)一些簡(jiǎn)單的文本數(shù)據(jù)或者二進(jìn)制數(shù)據(jù)。

(1)將數(shù)據(jù)存儲(chǔ)在文件中

Context類中提供了一個(gè)openFileOutput()方法,用于將數(shù)據(jù)存儲(chǔ)到指定的文件中。

第一個(gè)參數(shù):文件名(系統(tǒng)會(huì)自動(dòng)創(chuàng)建這個(gè)文件)。

第二個(gè)參數(shù):文件的操作模式。

文件的操作模式有以下幾種:

  • Context.MODE_PRIVATE:私有覆蓋模式。只能被當(dāng)前應(yīng)用訪問,并且如果寫入,則覆蓋。
  • Context.MODE_APPEND:私有追加模式。只能被當(dāng)前應(yīng)用訪問,并且如果寫入,則追加。
  • Context.MODE_WORLD_READABLE和Context.MODE_WORLD_WRITEABLE已在Android4.2版本中被廢除。

具體實(shí)現(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,它會(huì)保證在Lambda
                //表達(dá)式中的代碼全部執(zhí)行完之后自動(dòng)將外層的流關(guān)閉,這
                //樣就不再需要我們寫一個(gè)finally語(yǔ)句,手動(dòng)關(guān)閉流。
                writer.use {
                    it.write(inputText)
                }
                Toast.makeText(this,inputText,Toast.LENGTH_SHORT).show()
            }catch (e:IOException){
                e.printStackTrace()
            }
    }

如何證實(shí)數(shù)據(jù)是否已經(jīng)保存成功了呢?

使用快捷鍵Ctrl+Shift+A(Mac系統(tǒng)是command+shift+A)打開搜索功能,在搜索框輸入“Device File Explorer”即可找到這個(gè)工具,我們?cè)谶@工具里找到/data/data/com.example.filepersistencetest/files/目錄,里面有一個(gè)生成的data文件,雙擊打開,查看里面的內(nèi)容。

(2)從文件中讀取數(shù)據(jù)

Context類提供的openFileinput()方法,用于從文件中讀取數(shù)據(jù)。

參數(shù):文件名。

具體實(shí)現(xiàn):

private fun load():String{
        val content=StringBuilder()
        try {
            val input=openFileInput("data")
            val reader=BufferedReader(InputStreamReader(input))
            //kotlin提供的內(nèi)置擴(kuò)展函數(shù)forEachLine,它會(huì)將讀到的內(nèi)容都回調(diào)到Lambda表達(dá)式中。
            reader.use {
                reader.forEachLine {
                    content.append(it)
                }
            }
        }catch(e:IOException){
            e.printStackTrace()
        }
        return content.toString()
    }

(3)實(shí)戰(zhàn)演練:重新啟動(dòng)程序時(shí)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存儲(chǔ)

不同于文件存儲(chǔ),SharedPreferences是使用鍵值對(duì)的方式來(lái)存儲(chǔ)數(shù)據(jù)的。

Context類中的getSharedPreferences()方法,獲取SharedPreferences對(duì)象。

第一個(gè)參數(shù):指定SharedPreferences文件的名稱。(如果指定文件的名稱不存在就會(huì)創(chuàng)建一個(gè),SharedPreferences文件都是存放在/data/data/<package name>/shared_prefs目錄)。

第二個(gè)參數(shù):指定操作模式。只有MODE_PRIVATE可選,MODE_PRIVATE:只有當(dāng)前的應(yīng)用程序才可以對(duì)這個(gè)SharedPreferences文件進(jìn)行讀寫。

將數(shù)據(jù)存儲(chǔ)到SharedPreferences中

具體實(shí)現(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í)數(shù)據(jù)是否已經(jīng)保存成功了呢?

使用快捷鍵Ctrl+Shift+A(Mac系統(tǒng)是command+shift+A)打開搜索功能,在搜索框輸入“Device File Explorer”即可找到這個(gè)工具,我們?cè)谶@工具里找到/data/data/com.example.sharedpreferencestest/shared_prefs/目錄,里面有一個(gè)生成的data.xml文件,雙擊打開,查看里面的內(nèi)容。

從sharedpreferences中讀取數(shù)據(jù)

具體實(shí)現(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ù)庫(kù)存儲(chǔ)

創(chuàng)建數(shù)據(jù)庫(kù)

SQLiteOpenHelper類是一個(gè)抽象類,有兩個(gè)抽象方法,onCreate()和onUpgrade()。

  • onCreate(SQLiteDatabase):在數(shù)據(jù)第一次生成的時(shí)候會(huì)調(diào)用這個(gè)方法,也就是說(shuō),只有創(chuàng)建數(shù)據(jù)庫(kù)的時(shí)候才會(huì)調(diào)用,還可以在這個(gè)方法里生成數(shù)據(jù)庫(kù)表。
  • onUpgrade(SQLiteDatabase,int,int):當(dāng)數(shù)據(jù)庫(kù)需要升級(jí)的時(shí)候,Android系統(tǒng)會(huì)自動(dòng)調(diào)用這個(gè)方法,一般在這個(gè)方法里刪除數(shù)據(jù)表,并建立新的數(shù)據(jù)表。

SQLiteOpenHelper類的構(gòu)造方法:

第一個(gè)參數(shù):Context

第二個(gè)參數(shù):數(shù)據(jù)庫(kù)名

第三個(gè)參數(shù):運(yùn)行我們?cè)诓樵償?shù)據(jù)時(shí)放回一個(gè)自定義的Cursor,一般傳入null即可

第四個(gè)參數(shù):表明當(dāng)前數(shù)據(jù)庫(kù)的版本號(hào)

步驟

定義SQLiteOpenHelper的子類,在該類中創(chuàng)建一個(gè)名為BookStore.db的數(shù)據(jù)庫(kù)

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
    }
}

升級(jí)數(shù)據(jù)庫(kù)

val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)

改為

val dbHelper=MyDatabaseHelper(this,"BookStore.db",2)

表示數(shù)據(jù)庫(kù)升級(jí)

添加數(shù)據(jù)

insert():專門用于添加數(shù)據(jù)。

第一個(gè)參數(shù):表名

第二個(gè)參數(shù):用于在未指定添加數(shù)據(jù)的情況下給某些可為空的列自動(dòng)賦值給NULL,一般用不到這個(gè)功能,傳入null即可。

第三個(gè)參數(shù):ContentValues對(duì)象

步驟

獲取SQLiteDatabase對(duì)象

val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
val db=dbHelper.writableDatabase

使用ContentValues對(duì)要添加的數(shù)據(jù)進(jìn)行組裝

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():對(duì)數(shù)據(jù)進(jìn)行更新。

參數(shù):第一個(gè)參數(shù):表名,指定更新哪張表的數(shù)據(jù)。

第二個(gè)參數(shù):ContentValues對(duì)象,要把更新數(shù)據(jù)在這里組裝進(jìn)去。

第三、四個(gè)參數(shù):用于約束更新某一行或某幾行的數(shù)據(jù),不指定的話默認(rèn)會(huì)更新所有行。

步驟

獲取SQLiteDatabase對(duì)象

val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
val db=dbHelper.writableDatabase

構(gòu)建ContentValues對(duì)象,并且給它指定一組數(shù)據(jù),說(shuō)明把價(jià)格這一系列的數(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ù)。

第一個(gè)參數(shù):表名

第二、三個(gè)參數(shù):用于約束刪除某一行或者某幾行的數(shù)據(jù),不指定的話會(huì)默認(rèn)刪除所有行。

val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
val db=dbHelper.writableDatabase
db.delete("Book","pages>?", arrayOf("500"))

查詢數(shù)據(jù)

步驟

獲取SQLiteDatabase對(duì)象

val dbHelper=MyDatabaseHelper(this,"BookStore.db",1)
val db=dbHelper.writableDatabase

調(diào)用query()方法后會(huì)返回一個(gè)Cursor對(duì)象,查詢到的所有數(shù)據(jù)都可以從這個(gè)對(duì)象中取出。

        val cursor=db.query("Book",null,null,null,null,null,null)
         //查詢完后獲得一個(gè)Cursor對(duì)象,接著我們調(diào)用它的moveToFirst()方法,
         //將數(shù)據(jù)的指針移動(dòng)到第一行的位置,
         //然后進(jìn)入一個(gè)循環(huán)當(dāng)中,去遍歷查詢到的每一行數(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ù)庫(kù)

使用SQL來(lái)完成前面學(xué)過的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ù)存儲(chǔ)方式全面總結(jié)講解的文章就介紹到這了,更多相關(guān)Kotlin數(shù)據(jù)存儲(chǔ)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Android API編程之Assets文件操作示例

    Android API編程之Assets文件操作示例

    這篇文章主要介紹了Android API編程之Assets文件操作,結(jié)合實(shí)例形式分析了Android針對(duì)Assets文件夾下的文件操作相關(guān)技巧,需要的朋友可以參考下
    2017-08-08
  • Android App開發(fā)中自定義View和ViewGroup的實(shí)例教程

    Android App開發(fā)中自定義View和ViewGroup的實(shí)例教程

    這篇文章主要介紹了Android App開發(fā)中自定義View和ViewGroup的實(shí)例教程,分別介紹了進(jìn)度條和圖片上傳并排列的例子,效果很好很強(qiáng)大,需要的朋友可以參考下
    2016-05-05
  • Android Listview中顯示不同的視圖布局詳解及實(shí)例代碼

    Android Listview中顯示不同的視圖布局詳解及實(shí)例代碼

    這篇文章主要介紹了Android Listview中顯示不同的視圖布局詳解及實(shí)例代碼的相關(guān)資料,需要的朋友可以參考下
    2017-02-02
  • Android單選按鈕RadioButton的使用方法

    Android單選按鈕RadioButton的使用方法

    這篇文章主要為大家詳細(xì)介紹了Android單選按鈕RadioButton的使用方法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-05-05
  • Android如何設(shè)置圓角圖片

    Android如何設(shè)置圓角圖片

    這篇文章主要為大家詳細(xì)介紹了Android如何設(shè)置圓角圖片,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2017-02-02
  • Android 用 camera2 API 自定義相機(jī)

    Android 用 camera2 API 自定義相機(jī)

    本文主要介紹了Android 用 camera2 API 自定義相機(jī)的相關(guān)知識(shí)。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧
    2017-04-04
  • Android自定義View驗(yàn)證碼輸入框

    Android自定義View驗(yàn)證碼輸入框

    這篇文章主要為大家詳細(xì)介紹了自定義View驗(yàn)證碼輸入框,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • Android?ContentObserver?監(jiān)聽短信思路詳解

    Android?ContentObserver?監(jiān)聽短信思路詳解

    ContentObserver允許在Android中監(jiān)控特定數(shù)據(jù)的變化,可用于短信等應(yīng)用的數(shù)據(jù)監(jiān)聽,開發(fā)者可通過繼承ContentObserver并實(shí)現(xiàn)onChange方法來(lái)定義當(dāng)目標(biāo)內(nèi)容變化時(shí)的響應(yīng)行為,感興趣的朋友一起看看吧
    2024-09-09
  • Flutter實(shí)現(xiàn)漸變弧形進(jìn)度條的示例詳解

    Flutter實(shí)現(xiàn)漸變弧形進(jìn)度條的示例詳解

    在Flutter開發(fā)中,構(gòu)建一個(gè)具有視覺吸引力的、反映進(jìn)度的圓形弧形進(jìn)度條是一個(gè)常見需求,本文將詳細(xì)介紹如何使用Flutter和Dart語(yǔ)言實(shí)現(xiàn)這一功能,需要的可以參考下
    2023-12-12
  • Android在kts中使用navigation及Args的方法

    Android在kts中使用navigation及Args的方法

    在Android項(xiàng)目中使用Kotlin腳本(kts)替代Groovy配置navigation和Args,需添加相關(guān)依賴,并在build.gradle中進(jìn)行配置,文章詳細(xì)介紹了如何在kts中使用navigation進(jìn)行頁(yè)面導(dǎo)航和參數(shù)傳遞,介紹了使用Bundle和Safe Args兩種方式安全傳遞參數(shù)
    2024-10-10

最新評(píng)論

张家川| 中山市| 中宁县| 那曲县| 永泰县| 新晃| 江山市| 仙桃市| 宁波市| 沈丘县| 嘉禾县| 宁海县| 香港| 宁津县| 大埔县| 灌南县| 绍兴市| 大安市| 梧州市| 莱州市| 金山区| 五家渠市| 武邑县| 大姚县| 原阳县| 永川市| 陈巴尔虎旗| 浦东新区| 汝城县| 万山特区| 锦屏县| 土默特右旗| 大竹县| 奉化市| 景东| 新泰市| 永寿县| 怀安县| 常熟市| 云和县| 进贤县|