Search code examples
arraysjsonkotlingsonsharedpreferences

How to access shared preferences inside object


I am trying to access my gson json shared preferences inside object. I dont know how to access it. This is my code for accessing shared preferences inside a fragment.

        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)
    ``` 

This is my object class. I am trying to access the shared preferences inside the calculateTheDistance function. I am getting error when I type 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"
    }

} ```

Solution

  • In your function calculateTheDistance pass context of activity if you cannot access application, this is how

    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"
        }
    
    }
    

    and for using this add requireContext in your parameters if from fragment OR this if from activity.