Kotlin:如何在SharedPreferences中存储数组列表对象

时间:2019-12-19 08:35:22

标签: android kotlin sharedpreferences

我用Kotlin创建了一个Android应用,我创建了一个数据类“ ProductQuantityData”,其中包含两个属性:“ Quantity”:Int和“ Product”:ProductData,该产品是DataClass。我要存储并在sharedPreferences中获取类型为“ ProductQuantityData”的arrayList。这是我的代码:

  private val sharedPreferences: SharedPreferences =
            context.getSharedPreferences(context.packageName, Context.MODE_PRIVATE)
       fun getProductInArrayListWithQuantities(key: String): ArrayList<ProductQuantityData> {
                val emptyList = Gson().toJson(ArrayList<ProductQuantityData>())
                return Gson().fromJson(
                    sharedPreferences.getString(key, emptyList),
                    object : TypeToken<ArrayList<ProductQuantityData>>() {}.type

                )
            }

        fun setProductInArrayListWithQuantities(DataArrayList:ArrayList<ProductQuantityData>, key: String) {
            val jsonString = Gson().toJson(DataArrayList)
            sharedPreferences.edit().putString(key, jsonString).apply()
        }

我收到以下错误:

  

E / Android运行时:致命异常:主要       流程:com.app.honey,PID:18325       java.lang.RuntimeException:无法启动活动ComponentInfo {com.app.honey / com.app.honey.activity.product.ProductDetail}:   com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:   预期为BEGIN_OBJECT,但位于第1行第3列的路径$ [0]           在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)           在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)           在android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78).......

我知道问题出在sharedPreferences.getString(key, emptyList),因为类型不是String,是对象。 因此,我该如何更正我的代码以使其正常工作。 我只需将getProductInArrayListWithQuantities更改为以下代码即可解决我的问题:

fun getProductInArrayListWithQuantities(key: String): ArrayList<ProductQuantityData> {
    var prodQte: ArrayList<ProductQuantityData>
    val json = sharedPreferences.getString(key, "")
    prodQte = if (json!!.isEmpty()) {
        ArrayList()
    } else {
        val type = object : TypeToken<ArrayList<ProductQuantityData>>() {
        }.type
        Gson().fromJson<ArrayList<ProductQuantityData>>(json, type)
    }
    return prodQte
}

0 个答案:

没有答案