Search code examples
androidkotlinsharedpreferences

Unable to save and retreive Double from storage


I always get this error java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

  val sharedPreferences = getSharedPreferences("prefs", MODE_PRIVATE)
  val editor = sharedPreferences.edit()
  var myLongitude = 36.892672
  editor.putDouble("longitude", myLongitude)
  editor.apply()

The error is from here:

val savedLongitude : Double = sharedPreferences.getDouble("longitude", 0.0)

I have these methods:

 fun SharedPreferences.Editor.putDouble(key: String, double: Double) =
          putLong(key, java.lang.Double.doubleToRawLongBits(double))

  fun SharedPreferences.getDouble(key: String, default: Double) =
          java.lang.Double.longBitsToDouble(getLong(key, java.lang.Double.doubleToRawLongBits(default)))

My goal is to save a double value to SharedPref and then retrieve it


Solution

  • You can use much elegant approach. https://stackoverflow.com/a/18098090/5422725 this is variant for java. But in case you use kotlin, you could use extension to make it mor eclear.

    Kotlin extension way (much more pretty than using weird utils classes or whatever)

    fun SharedPreferences.Editor.putDouble(key: String, double: Double) =
        putLong(key, java.lang.Double.doubleToRawLongBits(double))
    
    fun SharedPreferences.getDouble(key: String, default: Double) =
        java.lang.Double.longBitsToDouble(getLong(key, java.lang.Double.doubleToRawLongBits(default)))
    

    enter link description here