Introduction
Generally, SharedPreferences is used when we want to store a small amount of data such as user id, password, user image, etc. In this article, we will learn how to store the image inside SharedPreferences and how to retrieve the image from SharedPreferences.
How to store image using SharedPreferences in android
Step 1
Create a new project in android studio and select Empty Activity
Click on the finish button.
Step 2
Go to activity_main.xml. By default, we get a textview so delete this textview and add the following code
activity_main.xml
Here we take 1 imageview and 2 buttons.
activity_main.xml layout
Step 3
Create PreferenceManager.java class inside the java folder.
Here we define the methods which are responsible for storing data into SharedPreference and retrieving data from SharedPreference. These methods will be called from other activities for storing and retrieving data. "userinfo" is the file name where our image will be saved.
Step 4
Go to AndroidManifest.xml file and add the below permission
Step 5
Go to MainActivity and add the below code
MainActivity.java
Here, we need the user's permission to access the camera so we can perform this task using the checkSelfPermission() method. Once the user allows access to the camera, we can capture an image. We get the captured image inside onActivityResult() method. Now we call the PreferenceManager method and store the captured image into SharedPreferences.
How to retrieve image from SharedPreferences
Step 1
Create a new activity says DashboardActivity, add the below code to their corresponding layout(activity_dashboard.xml)
Here, we take 1 textview and 1 imageview.
activity_dashboard.xml layout
Step 2
Go to DashboardActivity.java and add the below code
Here, we retrieve the captured image by calling the Preference Manager class method.
Output
Conclusion
In this article, we have seen how we can store and retrieve image into SharedPreference.Thanks for reading and hope you like it. If you have any suggestions or queries on this article, please share your thoughts.