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.