網(wǎng)站首頁 編程語言 正文
1、文件存儲
文件存儲是Android中最基本的數(shù)據(jù)存儲方式,它不對存儲的內(nèi)容進(jìn)行任何格式化處理,有數(shù)據(jù)都是原封不動地保存在文件當(dāng)中的,因此它比較適合存儲一些簡單的文本數(shù)據(jù)或者二進(jìn)制數(shù)據(jù)。
(1)將數(shù)據(jù)存儲在文件中
Context類中提供了一個openFileOutput()方法,用于將數(shù)據(jù)存儲到指定的文件中。
第一個參數(shù):文件名(系統(tǒng)會自動創(chuàng)建這個文件)。
第二個參數(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版本中被廢除。
具體實現(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
//表達(dá)式中的代碼全部執(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表達(dá)式中。
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:只有當(dāng)前的應(yīng)用程序才可以對這個SharedPreferences文件進(jìn)行讀寫。
將數(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):當(dāng)數(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ù):表明當(dāng)前數(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ù)進(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():對數(shù)據(jù)進(jìn)行更新。
參數(shù):第一個參數(shù):表名,指定更新哪張表的數(shù)據(jù)。
第二個參數(shù):ContentValues對象,要把更新數(shù)據(jù)在這里組裝進(jìn)去。
第三、四個參數(shù):用于約束更新某一行或某幾行的數(shù)據(jù),不指定的話默認(rèn)會更新所有行。
步驟
獲取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ù),不指定的話會默認(rèn)刪除所有行。
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ù)的指針移動到第一行的位置,
//然后進(jìn)入一個循環(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ù)庫
使用SQL來完成前面學(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)
原文鏈接:https://blog.csdn.net/weixin_63357306/article/details/126705050
相關(guān)推薦
- 2024-03-14 SpringBoot中事務(wù)
- 2023-06-13 Python?Beautiful?Soup模塊使用教程詳解_python
- 2023-03-25 Redis實現(xiàn)UV統(tǒng)計的示例代碼_Redis
- 2021-12-06 Flutter多項選擇彈窗實現(xiàn)詳解_Android
- 2022-11-20 Postgresql刪除數(shù)據(jù)庫表中重復(fù)數(shù)據(jù)的幾種方法詳解_PostgreSQL
- 2022-07-06 Python?dataframe如何設(shè)置index_python
- 2022-09-29 Python3中map(),reduce(),filter()的詳細(xì)用法_python
- 2022-03-27 Android實現(xiàn)井字游戲_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細(xì)win安裝深度學(xué)習(xí)環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎(chǔ)操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認(rèn)證信息的處理
- Spring Security之認(rèn)證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權(quán)
- redisson分布式鎖中waittime的設(shè)
- maven:解決release錯誤:Artif
- restTemplate使用總結(jié)
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務(wù)發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結(jié)構(gòu)-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標(biāo)對象命令
- Spring中的單例模式應(yīng)用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠(yuǎn)程分支