This question already has answers here:
Misbehavior when trying to store a string set using SharedPreferences
(6 answers)
Closed 4 years ago.
I save some string values in SharedPreference and it is not updating, where I do mistake?
I try to update SharedPreference value from Timer().
I tried to use commit() and apply() after updating SharedPreference.Editor value,but it does not update values.At every step of for loop I add new values to val protocols which is getting own value from SharedPreference
val sharedPreferences = activity!!.getSharedPreferences("session",Context.MODE_PRIVATE)
val protocols = sharedPreferences.getStringSet("protocols",hashSetOf())
Log.d("old protocols",protocols.toString())
Timer().scheduleAtFixedRate(object : TimerTask() {
override fun run() {
Query(context!!).post(url,params,headers,object:ResponseCallBack{
override fun onSuccess(response: String?) {
val res = response?.string()
val document = Jsoup.parse(res)
val bals = document.select("#newspaper-b tbody tr")
if(!protocols.containsAll(bals.eachText())) {
for (bal in bals) {
val bprotokol = bal.allElements[5].text()
if (!protocols.contains(bprotokol)) {
protocols.add(bprotokol)
notification()
}
}
val editor = sharedPreferences.edit()
editor.putStringSet("protocols", protocols)
editor.apply()
val updatedProtocols = sharedPreferences.getStringSet("protocols",null)
Log.d("updated protocols",updatedProtocols.toString())
}
}
})
}
}, 0, 5000)
First Log.d("old protocols") output is {protocols=[MMX6859280]} it is okay first time opening app. In the for loop there are two values MMX6859280 and MMX6859281.
The second Log.d("updated protocols") output is {protocols=[MMX6859280,MMX6859281]},it is also okay. But when close app and open again I expected first Log.d output {protocols=[MMX6859280,MMX6859281]} but it returns {protocols=[MMX6859280]},so it is not updating values. The strange situation is when I add another value to SharedPreference with this updating,I get result what I want,but the second time all is same.
Try this
sharedPreferences.edit().putStringSet("protocols", protocols).apply();
You are applying to reference variable
Related
I am experimenting around with Kotlin's sharedPreferences, however I cannot seem to get the updated value to stick.
val sharedPreferences = getSharedPreferences("Files", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putInt("numbers",1).apply()
val textview = findViewById<TextView>(R.id.textview)
textview.text = sharedPreferences.getInt("numbers",0).toString()
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
editor.putInt("numbers",2).apply()
textview.text = sharedPreferences.getInt("numbers",0).toString()
}
In the code above I set the initial value of the sharedPreference to 1, upon clicking the button the value will be updated to 2 and displayed.That works fine however when closing the app and reopening it, the value reverts to 1. Is there a way to permanatly keep the updated value?
You are setting it to that value every time you open the activity, since onCreate() is called every time it opens. You should check if the value is already set, and if it is, skip that line of code.
if ("numbers" !in sharedPreferences) {
val editor = sharedPreferences.edit()
editor.putInt("numbers",1).apply()
}
By the way, there is an extension function for editing without having to call apply and editor. repeatedly:
if ("numbers" !in sharedPreferences) {
sharedPreferences.edit {
putInt("numbers",1)
}
}
ok soo this is my interface code:
interface CodeService {
#GET("sro-rastro/{code}")
fun list(#Path("code") code : String = "LB524259080HK"
) : Call<Code>
}
And that is my activity getting the value from EditText
binding.btNewPackage.setOnClickListener {
var TrackingNumber = binding.etTrackingNumber.text.toString()
}
so, i want a way to get the value of TrackingNumber and pass it in the interface instead of String = "LB524259080HK"
it is my first time using Retrofit and i'm pretty lost at how i would pass the value to my interface.
I am not sure whether your structure is right calling the API from MainActivity instead of AddActivity because the EditText is defined there. Anyway, what you can do is use SharedPreferences to save the data of trackingNumber whenever btNewPackage is clicked like this:
binding.btNewPackage.setOnClickListener {
val trackingNumber = binding.etTrackingNumber.text.toString()
val sharedPref = getSharedPreferences("preference_file_key", Context.MODE_PRIVATE)
with (sharedPref.edit()) {
putString("tracking_number", trackingNumber)
apply()
}
}
And at the time of calling the API, you can simply fetch the trackingNumber using SharedPreferences and pass it along like this:
val sharedPref = getSharedPreferences("preference_file_key", Context.MODE_PRIVATE)
val trackingNumber = sharedPref.getString("tracking_number", "")
val call = RetrofitInitializer().codeService().list(trackingNumber)
I'm trying to make this so that is saves every time I close the app. The tutorials I found are not clear for me, can anyone please assist me? If needed, here's how my variable I want saved is defined:
private var coins = 0
Here is the GitHub link if needed, which goes straight to MainActivity.
You can use shared preferences to save and retrieve simple data
save data
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
with (sharedPref.edit()) {
putInt("MY_COINS", coins)
apply()
}
Read data
val sharedPref = activity?.getPreferences(Context.MODE_PRIVATE) ?: return
val coins = sharedPref.getInt("MY_COINS"), defaultValue)
You can use Shared Preferences for state management or save data in key-value pair.
lateinit var shared : SharedPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_spactivity)
shared = getSharedPreferences("CoinsDB" , Context.MODE_PRIVATE)
var coins = 0
For Save
val edit = shared.edit()
edit.putInt("coins" , coins )
edit.apply()
For retrieve or read
val coinsValue = shared.getInt("coins")
I recommend using storage in files if that isn't a problem for you.
This question already has answers here:
How to convert String to Int in Kotlin?
(11 answers)
Closed 1 year ago.
I have an EditText which will take a number from the user and save it as sharedPreferences. I have two Buttons to load and save and a TextView to display a saved data. Everything works fine but if the user enters nothing and saves, the app crashes. Here's the Kotlin code,
override fun onClick(p0: View?) {
val sharedPreferences=getSharedPreferences("key", Context.MODE_PRIVATE)
when(p0!!.id){
//saves user data
R.id.btn_save->{
val userAge = Integer.parseInt(ageInput.text.toString()) //the problem is here
val editor=sharedPreferences.edit()
editor.putInt("age",userAge)
editor.apply()
}
//loads or displays user data
R.id.btn_load->{
val age=sharedPreferences.getInt("age",0)
showTv.text="Age: $age"
}
}
}
Use toIntOrNull() instead. Instead of throwing an exception on invalid input, it returns null. Then you can use the Elvis operator to provide the default to use when it's null.
val userAge = ageInput.text.toString().toIntOrNull() ?: 0
You should avoid the Java primitive wrapper classes like Integer when using Kotlin.
private var highScore: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_game)
loadData()
playGame()
}
override fun onDestroy() {
super.onDestroy()
saveData()
}
private fun saveData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.apply{
putInt("INTEGER_KEY", highScore)
}.apply()
}
private fun loadData(){
val sharedPreferences = getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE)
val savedInt = sharedPreferences.getInt("INTEGER_KEY", 0)
highScore = savedInt
binding.highScore.text = "Highscore: $savedInt"
}
I've made a simple game and I need to store the the highscore value and retrieve the value when the app is relaunched. I've tried to use sharedPreferences in the given code. But the highscore data is lost when I close the app and relaunch it. How can I save and retrieve the value?
PS: The highscore value is saved/retrieved properly when running the app in Android Studio's emulator. But it doesn't work when I run the app on my phone. It resets to 0 every time I relaunch it.
you are trying to save, when the app is destroyed. This might work sometimes, when onDestroy is actually called, but that does not happen for sure.
Apply is saving the data asynchronous to the disk, which won't happen as you are trying to do it when the app is destroyed. You have to use commit instead of apply to save the data synchronous.
I would recommend to save the data at another point of your app instead of in onDestroy, as this won't be called every time the app is closed/killed.