当前位置:网站首页>Learning Android VI from scratch -- data persistence
Learning Android VI from scratch -- data persistence
2022-04-22 19:32:00 【Scattered moon】
Catalog
SharedPreferences Storage
SharedPreferences It uses key value pairs to store data . in other words , When saving a piece of data , You need to provide a key for this data , In this way, when reading data, you can pass Use this key to get the corresponding value . and SharedPreferences It also supports different types of data storage , If The stored data type is integer , So the data read out is also integer ; If the data stored is a string , that The read data is still a string .
Store data to SharedPreferences in
adopt getSharedPreferences() Method specification SharedPreferences The file name of is data, And got SharedPreferences.Editor object . Then add... To the object 3 Different types of data , most After the call apply() Method to submit , Thus, the operation of data storage is completed
val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
editor.putString("name", "Tom")
editor.putInt("age", 28)
editor.putBoolean("married", false)
editor.apply()
from SharedPreferences Read data from
from SharedPreferences Reading data from a file will be easier .SharedPreferences In the object A series of get Method , Used to read stored data , Each of these get All methods correspond SharedPreferences.Editor One of the put Method , For example, read a Boolean data to use getBoolean() Method , Read a string and use getString() Method . these get Methods both receive two arguments Count : The first parameter is the key , You can get the corresponding value by passing in the key used to store the data ; The second parameter is the default value , That is, what default value will be returned when the incoming key cannot find the corresponding value .
Call its... Respectively getString()、getInt() and getBoolean() Method , To get the name stored in front of 、 Age and whether married , If no corresponding value is found , The default value passed in the method will be used instead of
val prefs = getSharedPreferences("data", Context.MODE_PRIVATE)
val name = prefs.getString("name", "")
val age = prefs.getInt("age", 0)
val married = prefs.getBoolean("married", false)
App remember password
You can see , Here first onCreate() Method SharedPreferences object , And then call it. getBoolean() Method to get remember_password The value of this key . At first, of course, there was no corresponding The value of , So default values are used false, So that nothing happens . Then after the login is successful , Would call CheckBox Of isChecked() Method to check if the check box is selected . If it's selected , It means that the user wants to remember Live code , This will be remember_password Set to true, And then put account and password The corresponding values are Deposit in SharedPreferences Document and submit ; If not selected , Just call clear() Method , take SharedPreferences Erase all the data in the file .
When the user selects the remember password check box , And after a successful login ,remember_password The value of the bond is true 了 , If you restart the login interface at this time , It will start from SharedPreferences The account number and... Will be saved in the file The passwords are read out , And fill in the text input box , Then select the remember password check box , This completes remembering the password The function of .
val prefs = getPreferences(Context.MODE_PRIVATE)
val isRemember = prefs.getBoolean("remember_password", false)
if (isRemember) {
// Set both account and password in the text box
val account = prefs.getString("account", "")
val password = prefs.getString("password", "")
accountEdit.setText(account)
passwordEdit.setText(password)
rememberPass.isChecked = true
}
login.setOnClickListener {
val account = accountEdit.text.toString()
val password = passwordEdit.text.toString()
// If the account number is admin And the code is 123456, I think the login is successful
if (account == "admin" && password == "123456") {
val editor = prefs.edit()
if (rememberPass.isChecked) {
// Check that the check box is selected
editor.putBoolean("remember_password", true)
editor.putString("account", account)
editor.putString("password", password)
} else {
editor.clear()
}
editor.apply()
val intent = Intent(this, MainActivity::class.java)
startActivity(intent)
finish()
} else {
Toast.makeText(this, "account or password is invalid", Toast.LENGTH_SHORT).show()}
SQLite Database storage
Add data :
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",arrayOf("The Da Vinci Code", "Dan Brown", "454", "16.96"))
db.execSQL("insert into Book (name, author, pages, price) values(?, ?, ?, ?)",arrayOf("The Lost Symbol", "Dan Brown", "510", "19.95"))
Update data :
db.execSQL("update Book set price = ? where name = ?", arrayOf("10.99", "The Da Vinci Code"))
Delete data :
db.execSQL("delete from Book where pages > ?", arrayOf("500"))
Query data :
val cursor = db.rawQuery("select * from Book", null)
Business
Android Standard usage of transactions in , First call SQLiteDatabase Of beginTransaction() Method to open a transaction , Then execute the specific database in an exception caught code block operation , When all operations are completed , call setTransactionSuccessful() Indicates that the transaction has been executed into Thanks , Last in finally Call in code block endTransaction() End the business . observe , We're deleting old After the data operation is completed, a... Is thrown manually NullPointerException, In this way, the code to add new data will execute Not yet . However, due to the existence of transactions , An exception in the middle will lead to the failure of the transaction , At this time, the old data should not be deleted Of .
val db = dbHelper.writableDatabase db.beginTransaction() // Open transaction
try {
db.delete("Book", null, null)
if (true) {
// Manually throw an exception , Let the transaction fail
throw NullPointerException()
}
val values = ContentValues().apply {
put("name", "Game of Thrones")
put("author", "George Martin")
put("pages", 720)
put("price", 20.85)
}
db.insert("Book", null, values)
db.setTransactionSuccessful() // Transaction executed successfully
} catch (e: Exception) {
e.printStackTrace()
} finally {
db.endTransaction() // End the business
}
Room
Google Another one has been launched specifically for Android The database framework of the platform ——Room.
版权声明
本文为[Scattered moon]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204221917121257.html
边栏推荐
- The function of final and why string is immutable
- 11-Aggregating Streams
- ReDet 代码逐行解读
- 07-Complex Types
- dotnet 通过 WMI 获取设备厂商
- 【面试普通人VS高手系列】请说一下网络四元组
- Understanding of string constant pool and intern method
- 对《继续树莓派4B+OLED:开机自动显示IP地址》的补充,针对 Raspberry Pi OS Lite 64-bit
- 消息队列最佳实践
- Where is the fastlist in the database connection pool hikaricp
猜你喜欢

.net 用supersocket搭建socket server

ArrayList learning notes

Huawei equipment configuration policy routing to the side hanging firewall

Type of Flink window

String.join()和StringUtils.join()优雅解决数组或者集合拼接

Learn this framework by using the mastering ABP framework

The SQL statement obtains each day, week, month and year according to the start and end date

mmocr DBLoss

WebRTC:Mesh/MCU/SFU三种通信架构

Incorrect string value: ‘\xF0\x9F\x92\x95\’
随机推荐
dbnet字符检测详细网络结构图
sqlserver中查询是否有死锁存在
.net socket.io客户端使用过程
MYSQL,组合的唯一索引中,处理NULL值的问题
Detailed explanation of redis deployment in Linux Environment
ASP. Net webapi and WebService return JSON data
mysql 学习笔记
10.4.4 51单片机控制系统8个LED“跑马灯”实验
短链接设计和思考
07-Complex Types
12-Delta Lake
DBFS CLI : 01-Setting up the CLI
Arithmetic overflow error converting IDENTITY to data type int(SqlServer主键自增长引起的问题)
Configure interceptor not to intercept swagger
调用mysql存储过程报错:mysql 1449 : The user specified as a definer ('root'@'%') does not exist
Type of Flink window
How about CITIC Securities? Is it safe for qiniu school to open an account?
指针与对象的一些注意事项
工商银行分布式服务C10K场景的解决方案
Database index