0

I'm trying to do a function that will only save a higher speed than the one already saved. But the var outside the if loop is always 0.0, inside value is different. Does anyone knows some resolve or even better idea how to save only maximum speed?

private fun updateUI(speed: Double, distance: Double){
    val df = DecimalFormat("0.0")
    speed_text_view.text = df.format(speed).plus(" km/h")
    distance_text_view.text = df.format(distance)
    Log.e("getLocationUpdates", df.format(speed))

    var getSpeedDouble = 0.0 //here is problem. The value doesn't change

    if (speed > getSpeedDouble) {
        val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
        val editor = sharedPref.edit()
        editor
            .putString("SPEED", speed.toString())
            .apply()

        val getSharedPref = PreferenceManager.getDefaultSharedPreferences(this)
        getSharedPref.apply {
            val getSpeed = getString("SPEED", "")
             getSpeedDouble = getSpeed!!.toDouble()
            Log.e("GetSpeedDouble", getSpeedDouble.toString())
             max_speed_text_view.text = getSpeed.toString()

        }
    }
}
beginner992
  • 659
  • 1
  • 9
  • 28
  • ["apply() will asynchronously do disk I/O while commit() is synchronous"](https://stackoverflow.com/questions/5960678/whats-the-difference-between-commit-and-apply-in-shared-preference#comment14520813_5960678). You need to use `.commit()` on sharedpreferences in this case. Also, why get the value from sharedpreferences to update `getSpeedDouble`? Just do `getSpeedDouble = speed` – denvercoder9 Sep 19 '19 at 12:17
  • what do you exactly want, please elaborate more – Lakhwinder Singh Sep 19 '19 at 12:21
  • it seems you have to change `editor.putString("SPEED", speed.toString()).apply()` to `editor.putString("SPEED", speed.toString()).commit()` – Andrei Tanana Sep 19 '19 at 12:23
  • @LakhwinderSingh I am getting the data by locationManager and I know how to get Speed, but I also want to take the highest speed reached during the session. – beginner992 Sep 19 '19 at 12:23
  • What issue you are facing? – Lakhwinder Singh Sep 19 '19 at 12:25
  • @LakhwinderSingh The var getSpeedDouble should changes value, but it always 0.0. I need this value to check whether to if() loop – beginner992 Sep 19 '19 at 12:28
  • if is not a loop, Firstly – Lakhwinder Singh Sep 19 '19 at 12:30
  • did you try `commit` instead of `apply` – Lakhwinder Singh Sep 19 '19 at 12:31
  • Yes, still same. – beginner992 Sep 19 '19 at 12:31
  • are you getting this log `Log.e("GetSpeedDouble", getSpeedDouble.toString())`? If not then this `if (speed > getSpeedDouble) {` is always false – denvercoder9 Sep 19 '19 at 12:32
  • @sonnet I have Log. outside to if() and the var getSpeedDouble is 0.0. getSpeedDouble inside if() is changing – beginner992 Sep 19 '19 at 12:34
  • please check my anser – Madhav Sep 19 '19 at 12:37
  • why would it not be 0? You basically say "x = 0, if y > x (which is always 0), do something. – Joozd Sep 19 '19 at 12:38
  • @Joozd If current speed from locationManager is higher than previous, then it should change data in text view. Apps to running have a textview with maximum speed during the run. – beginner992 Sep 19 '19 at 12:45
  • @Joozd And this what I'm writing about. I need a variable that keeps changing the value to compare it to the speed given by GPS. If speed is higher then I should see new value in text view. The problem is in var getSpeedDouble - it doesn't change. So if() works always – beginner992 Sep 19 '19 at 12:54
  • have the speed as a global variable. when you load the activity fetch its value from the shared preferences and when you finish the activity write the value back to the shared preferences. within your method just assign a new value to the variable only if the current reading is bigger than the saved value. Keep your commits instead of applys with the sharedpreferences and you should be fine. – Nikos Hidalgo Sep 19 '19 at 13:06
  • @NikosHidalgo It seems to be a solution. I'll let you know later if it works, I can't check it now. – beginner992 Sep 19 '19 at 13:09

3 Answers3

2

For posterity: Have the speed as a global variable.

val speed:Double = 0.0

when you load the activity fetch its value from the shared preferences:

val preference = getSharedPreferences(yourApp, Context.MODE_PRIVATE)
val editor = preference.edit()
speed = preference.getDouble(“SPEED”,0.0)

when you finish the activity write the value back to the shared preferences:

editor.putDouble(“SPEED”,speed)
editor.commit()

within your method just assign a new value to the variable only if the current reading is bigger than the saved value.

private fun updateUI(newSpeed:Double) {
  if (newSpeed > speed)
  {
    speed = newSpeed
    textview.setText((newSpeed).toString())
  }
}
Nikos Hidalgo
  • 3,666
  • 9
  • 25
  • 39
  • It works, but not like I wanted, but you gave me the solution. It is global variable. I also changed getSharedPreferences as before: val sharedPref = PreferenceManager.getDefaultSharedPreferences(this) and it works like I wanted. Thank you so much for your help. – beginner992 Sep 19 '19 at 20:56
  • @beginner992 I'm glad it helped you. – Nikos Hidalgo Sep 20 '19 at 07:57
1

How about putting it away in a nice class, and when just initializing that class from you activity: speedKeeper = MaxSpeedKeeper(this) then all you have to do is drop in your speeds (ie. speedKeeper.speed = 10.4) and it will stay updated. Apply() will update to disk async, but the value in initialized sharedPref will stay cached, and is read from companion object's maxSpeed anyway.

This way, you can just drop your speedkeeper in any other processes, classes, fragments etc and it will keep doing what it does, or just initialize it again in a new activity.

class MaxSpeedKeeper(context: Context) {
    companion object {
        const val SPEED = "SPEED"
        const val SHAREDPREFS_NAME = "MY_SHAREDPREFS"
        var maxSpeed = 0.0f
    }
    var speed: Double
    get() = maxSpeed.toDouble()
    set(speedToCheck) {
        if (speedToCheck > maxSpeed) {
            maxSpeed=speedToCheck.toFloat()
            with(sharedPref.edit()) {
                putFloat(SPEED, speedToCheck.toFloat()) // you could change this to a string or bits or something if you want more resolution than a float gives
                apply()
            }
        }
    }
    private val sharedPref =
        context.getSharedPreferences(SHAREDPREFS_NAME, Context.MODE_PRIVATE)
    init {
        maxSpeed = sharedPref.getFloat(SPEED, 0.0f)
    }
}
Joozd
  • 501
  • 2
  • 14
  • It seems to be interesting. My current application doesn't need that much code, but it can be useful in many other applications. Thank you. – beginner992 Sep 21 '19 at 10:21
0
private fun updateUI(speed: Double) {
            var getSpeedDouble = 0.0 //here is problem. The value doesn't change
            if (speed > getSpeedDouble) {
                val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
                val editor = sharedPref.edit()
                editor.putString("SPEED", speed.toString()).apply()
                val defaultSpeed = sharedPref.getString("SPEED", "")
                getSpeedDouble = defaultSpeed.toString().toDouble()
                Log.e("updateUI", getSpeedDouble.toString())
            }
        }

        private fun getSpeed() {
            var getSpeedDouble: Double
            val sharedPref = PreferenceManager.getDefaultSharedPreferences(this)
            val defaultSpeed = sharedPref.getString("SPEED", "")
            getSpeedDouble = defaultSpeed.toString().toDouble()
            Log.e("getSpeed", getSpeedDouble.toString())
        }

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        updateUI(10.0)
        getSpeed()
    }

output

updateUI: 10.0 getSpeed: 10.0

Madhav
  • 317
  • 2
  • 12
  • It works, but not like I wanted. In your code getSpeed works just one time, when app starts. I need code which still checks speed from GPS and if speed id higher than last one, then the displayed speed increases. This is main problem and I don't any idea how to count it right way. – beginner992 Sep 19 '19 at 13:04
  • you can call it any time brother – Madhav Sep 20 '19 at 04:57