【问题标题】:How to access shared preferences inside object如何访问对象内的共享首选项
【发布时间】:2021-10-27 21:56:46
【问题描述】:

我正在尝试访问对象内部的 gson json 共享首选项。我不知道如何访问它。 这是我在片段中访问共享首选项的代码。

        val gson = Gson()
        val json = sharedPreferences.getString("loclists", "")
        val type = object: TypeToken<MutableList<LatLng>>() {}.type

        if(json == null || json == "")
            loclists = mutableListOf<LatLng>()



        else
            loclists = gson.fromJson(json, type)
    ``` 

这是我的对象类。我正在尝试访问 calculateTheDistance 函数中的共享首选项。输入 requireContext() 时出现错误。


    val PREFS_FILENAME = "com.app.app.prefs"
    private var loclistsDT= mutableListOf<LatLng>()



   fun calculateTheDistance(locationList: MutableList<LatLng>): String {


        val sharedPreferences = requireContext().getSharedPreferences(PREFS_FILENAME, 0)
        val gson = Gson()
        val json = sharedPreferences.getString("loclists", "")
        val type = object : TypeToken<MutableList<LatLng>>() {}.type

        if (json == null || json == "")
            loclistsDT = mutableListOf<LatLng>()
        else
            loclistsDT = gson.fromJson(json, type)
       

 if(locListsDT.size > 1){
            val meters =
                SphericalUtil.computeDistanceBetween(locListsDT.first(), locListsDT.last())
            val kilometers = meters / 1000
            return DecimalFormat("#.##").format(kilometers)
        }
        return "0.00"
    }

} ```

【问题讨论】:

  • requireContext 返回父上下文,你需要的是application
  • 我试过了。但还是报错
  • 你能说出什么错误吗?
  • 当输入application 时不显示。输入后显示为红色。

标签: arrays json kotlin gson sharedpreferences


【解决方案1】:

如果您无法访问application,则在您的函数calculateTheDistance 中传递活动上下文,这就是方法

fun calculateTheDistance(mContext : Context , locationList: MutableList<LatLng>): String {


        val sharedPreferences = mContext.getSharedPreferences(PREFS_FILENAME, 0)
        val gson = Gson()
        val json = sharedPreferences.getString("loclists", "")
        val type = object : TypeToken<MutableList<LatLng>>() {}.type

        if (json == null || json == "")
            loclistsDT = mutableListOf<LatLng>()
        else
            loclistsDT = gson.fromJson(json, type)
       

 if(locListsDT.size > 1){
            val meters =
                SphericalUtil.computeDistanceBetween(locListsDT.first(), locListsDT.last())
            val kilometers = meters / 1000
            return DecimalFormat("#.##").format(kilometers)
        }
        return "0.00"
    }

}

如果来自片段,则在参数中添加requireContext,如果来自活动,则添加this

【讨论】:

    猜你喜欢
    • 2016-02-14
    • 2012-09-20
    • 2015-10-09
    • 2016-01-17
    • 2018-02-06
    • 2019-10-01
    • 1970-01-01
    • 2016-11-10
    • 2017-01-22
    相关资源
    最近更新 更多