Native Shopify Mobile App with 20 new features
Kickstart your hyperlocal marketplace in Corona pandemic with a starter guide
Android App Development
iOS App Development
Cross Platform App Development
Hire on-demand project developers and turn your idea into working reality.
Big thanks to Webkul and his team for helping get Opencart 126.96.36.199 release ready!
Owner and Founder. Opencart
In this blog, we will learn about using shared Preference Change Listener.
We know App development is a big task but, there is much fun associated with it. While working on one of the applications, I ran into a situation where I had changed the values of some keys in the Shared preference but if the user back pressed, the changes would not be reflected in the previous activity.
Of course, there are many ways to overcome this situation like overriding the default onBackPressed() method, overriding the onResume() method of the previous activity and then setting the value again and perhaps many more.
But what I needed was something much simpler, like just check one or two keys of a shared preference and fetch the current value of the keys into some views and display them.
When I was traversing through the shared preference functions using the the mighty Ctrl+Space, provided by the Android Studio IDE.
I encountered the registerOnSharedPreferenceChangeListener() method.
I thought of giving this method a try and while trying I found that using this is super easy.
I have more than two activities which are accessing some values stored in shared preferences say A, B , C. Now the user starts with Activity A, goes to activity B and then to C. From Activity C the user changes some value and now the value stored in shared preference has changed. Now user presses back button and the activity B pops up from the stack and since the views were already created, the views in activity hold the values that were stored in the shared preferences at the time of creation of B, which currently is wrong.
Shared Preference ChangeListener can be very useful in this case.
Changes in the onCreate() method of your activity.
And you have done it.
Keep coding and Keep Sharing 🙂
Your email address will not be published. Required fields are marked*
Save my name email and website in this browser for the next time I comment.
Enquiry or Requirement
If you have more details or questions, you can reply to the received confirmation email.