I created a RatingBar in my application. It is for rating movies. I want value to be saved. When I login and go to that activity, I want to see that stars that I rated. It is difficult for me to find the answer because it is written in Kotlin and I'm new to it.
I searched for many other questions and answers, but with no result. Can you tell me what I need to change in my code?
class MovieDetailsActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_movie_details)
fiveStars()
val sharedPreference = getPreferences(Context.MODE_PRIVATE)
val rating = sharedPreference.getFloat("numStars", 0f)
ratingBar.rating = rating
}
private fun fiveStars() {
val ratingBar = findViewById<RatingBar>(R.id.ratingBar)
ratingBar.onRatingBarChangeListener = RatingBar.OnRatingBarChangeListener()
{ ratingBar: RatingBar, fl: Float, b: Boolean ->
val sharedPreference = getSharedPreferences("numStars", Context.MODE_PRIVATE)
val editor = sharedPreference.edit()
editor.putFloat("numStars", fl)
editor.apply()
Log.d("rate", ratingBar.rating.toString())
}
}
}
I tried a lot of things, but nothing is working. Hope you could help me. Thanks!
It seems like you're using two different preferences.
Here you are calling getPreferences(Context.MODE_PRIVATE)
:
val sharedPreference = getPreferences(Context.MODE_PRIVATE)
val rating = sharedPreference.getFloat("numStars", 0f)
ratingBar.rating = rating
and here you are using a specific sharedPreferences:
val sharedPreference = getSharedPreferences("numStars", Context.MODE_PRIVATE)
val editor = sharedPreference.edit()
Either use getPreferences(Context.MODE_PRIVATE)
in both cases, or use getSharedPreferences("numStars", Context.MODE_PRIVATE)
in both cases