Now that we are able to set the colors to use and also the text to encode in the QR code, it would be nice to be able to keep that data so that it can be automatically filled in when the app is opened again later. We will keep that data using the AndroidX PreferenceManager . To setup the correct dependency, add the AndroidX package reference to the module-level build.gradle file, in the section for dependencies:
If your project uses build.gradle.kts, then:
The current version is 1.2.1 at the time of creating this tutorial, but use the latest version available at the time you are going over the project.
For convenience, the code for interacting with the PreferenceManager will be in a singleton object defined in a class named PreferenceHelper. Create a file named PreferenceHelper.java and add the following code to it:
In the code above, the constructor is private and the only one instance of PreferenceHelper is created for use in the getInstance static method. The constructor uses the PreferenceManager to set a SharedPreferences class member. There is also a call to the App.getInstance() static method. At this point we do not have a class name App. Let’s create the class so that it will provide us with a convenient way to get a valid Context when one is needed anywhere in the app. The App class inherit Application so that it can be used to manage our app’s base state. Add the following code to a file named App.java:
It is important to set the App class in the project’s manifest. Edit AndroidManifest.xml but updating the android:name attribute of the the value of App:
Getting back to the PreferenceHelper, add the instance methods that will be used to save data to or read data from SharedPreferences:
The instance methods are simple getters and setters. Note that the text/string data is stored with base64 encoding, so when it is read using a getter, the text/string is also decoded from base64. The getters and setters use the following strings (declared as static members of PreferenceHelper) as keys to be used in SharedPreferences:
That will be all for the PreferenceHelper class. Build and run your code to make sure that it is building successfully before continuing to the next stage. You can check the complete code for the class on github .