在kotlin中使用共享偏好



所以我有一个不那么大的产品列表,大约有十个产品(这是一个示例商店应用程序(。我想添加一个按钮,让用户点击并将产品添加到购物车中。共享偏好是否适合存储这么多数据?我也熟悉房间数据库,知道共享偏好是存储非常少量的数据。此处代码:

这是我的清单:

var list = ArrayList<Model>()
list.add(Model("milk", "12000", R.drawable.milk))
list.add(Model("yoghurt", "13000", R.drawable.yoghurt))
list.add(Model("oil", "15000", R.drawable.oil))
list.add(Model("canned tomato paste", "8000", R.drawable.tomato_paste))
list.add(Model("hand wash", "18000", R.drawable.hand_wash))
list.add(Model("ice cream", "5000", R.drawable.ice_cream))
list.add(Model("spaggeti", "8000", R.drawable.spaggeti))
list.add(Model("tomato", "7000", R.drawable.tomato))
list.add(Model("cucumber", "5000", R.drawable.cucumber))
list.add(Model("potato", "4000", R.drawable.potato))

每行只有三个值:标题、价格、图像。使用添加按钮将列表的模型发送到购物车。像这样的事情。

btn.add.setonClicklistener {
// store each row that user clicked in the cart using shared preference
}

在这种情况下使用共同偏好是个好主意吗?

我认为这很好。有一个很好的库可以简化这种SharedPreferences的使用,它叫做TinyDB。我自己用。去看看:https://github.com/kcochibili/TinyDB--Android-Shared-Preferences-Turbo

您也可以自己实现。

如果用户可以向数据库添加食物,我会使用Room,如果不能,我会用SharedPreferences来存储。

为您的项目添加空间:

build.gradle(项目(:

ext {
roomVersion = '2.2.5'
}

build.gradle(模块(

apply plugin: 'kotlin-kapt'

build.gradle(模块(

implementation "androidx.room:room-runtime:$rootProject.roomVersion"
implementation 'androidx.lifecycle:lifecycle-livedata-ktx:2.2.0'
kapt "androidx.room:room-compiler:$rootProject.roomVersion"
implementation "androidx.room:room-ktx:$rootProject.roomVersion"
androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"

Food.kt

@Entity(tableName = "food")
data class Food(
@PrimaryKey @NonNull val id: Int,
val name: String,
val price: String,
@ColumnInfo(name = "drawable_path") val drawablePath: String) {
override fun toString(): String {
return "Food $id: name: $name, price: $price, drawable: $drawablePath"
}

FoodDao.kt

@Dao
interface FoodDao {
@Query("SELECT * FROM food WHERE id=:id LIMIT 1")
fun getFood(id: Int): Food
@Query("SELECT * FROM food")
fun getAllFood(): List<Food>
@Insert
fun addFood(food: Food)
}

FoodRepository.kt

class FoodRepository(private val foodDao: FoodDao) {
fun getFood(id: Int) = symptomDao.getFood(id)
fun getAllFood() = symptomDao.getAllFood()
}

FoodDatabase.kt

@Database(entities = [Food::class], version = 1)
abstract class FoodDatabase : RoomDatabase() {
abstract fun foodDao(): FoodDao
companion object {
@Volatile
private var INSTANCE: FoodDatabase? = null
fun getDatabase(context: Context): FoodDatabase? {
if (INSTANCE == null) {
synchronized(FoodDatabase::class.java) {
if (INSTANCE == null) {
INSTANCE = Room.databaseBuilder(
context.applicationContext,
FoodDatabase::class.java, "food_db"
).build()
}
}
}
return INSTANCE
}
}
}

代码没有经过测试,您可能需要进行小的调整才能编译它

相关内容

  • 没有找到相关文章

最新更新