0

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.

Mike M.
  • 38,532
  • 8
  • 99
  • 95
Fuad Paşayev
  • 51
  • 1
  • 10
  • You can't modify the `Set` returned by `getStringSet()` and then write that same object back. You need to create a new a `Set` object first, modify that, and then save that new one back. It's kinda tricky, and certainly non-obvious, unless you have happened to read the docs for that particular method. – Mike M. Jan 30 '19 at 07:01
  • Please don't edit to add SOLVED to the title. Also, you don't need to add the link in the body. It's already in a banner at the top of your question. – Mike M. Jan 30 '19 at 07:47

1 Answers1

0

Try this sharedPreferences.edit().putStringSet("protocols", protocols).apply();

You are applying to reference variable

manj1790
  • 104
  • 7