在Android SDK 30中,已经废弃了SharedPreferences存储,推荐使用Room Persistence Library来进行持久化值存储。
示例代码:
dependencies {
def room_version = "2.2.6"
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
}
@Entity
class User(
@PrimaryKey val id: Int,
val name: String,
val age: Int
)
@Dao
interface UserDao {
@Query("SELECT * FROM user")
fun getAllUsers(): List
@Insert
fun insertUser(user: User)
@Delete
fun deleteUser(user: User)
}
@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
}
// 初始化数据库
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "database-name"
).build()
// 插入数据
val user = User(1, "John", 22)
db.userDao().insertUser(user)
// 查询数据
val users = db.userDao().getAllUsers()
// 删除数据
db.userDao().deleteUser(user)
下一篇:AndroidSDK30路径问题