How To Store And Retrieve The Image Using SharedPreferences In Android

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

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
 xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageview"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginTop="76dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.218"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.492"
        app:srcCompat="@android:drawable/ic_menu_camera" />

    <Button
        android:id="@+id/clickpicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="100dp"
        android:text="Take Picture"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.495"
        app:layout_constraintStart_toEndOf="@+id/imageview"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.456" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="428dp"
        android:text="Reterive Image"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.498"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageview"
        app:layout_constraintVertical_bias="1.0" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here we take 1 imageview and 2 buttons.

activity_main.xml layout 

  

Step 3

Create PreferenceManager.java class inside the java folder.

package com.example.sharedpreferenceexample;

import android.content.Context;
import android.content.SharedPreferences;

public class PreferenceManager {

    private static  PreferenceManager INSTANCE;
    private  static SharedPreferences preferences;

    synchronized public static PreferenceManager getInstance(Context context){
        if(INSTANCE==null){
            INSTANCE=new PreferenceManager();
            preferences=context.getSharedPreferences("userinfo3",Context.MODE_PRIVATE);
        }
        return INSTANCE;
    }

    public void setString(String key,String value){
        preferences.edit().putString(key, value).apply();
    }

    public String getString(String key){
        return preferences.getString(key,"");
    }

}

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

 <uses-permission android:name="android.permission.CAMERA"/>

Step 5

Go to MainActivity and add the below code

MainActivity.java

package com.example.sharedpreferenceexample;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.ByteArrayOutputStream;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    ImageView imgbtn;
    Button button,takepicture;
    PreferenceManager preferenceManager;
    Intent camera;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.VmPolicy.Builder builder=new StrictMode.VmPolicy.Builder();
        StrictMode.setVmPolicy(builder.build());
        imgbtn=findViewById(R.id.imageview);
        button=findViewById(R.id.button3);
        takepicture=findViewById(R.id.clickpicture);
        preferenceManager=PreferenceManager.getInstance(this);
        button.setOnClickListener(this);
        takepicture.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.clickpicture:
                imgmethod();
                break;
            case R.id.button3:
                Intent intent=new Intent(this,DashboardActivity.class);
                startActivity(intent);
                finish();
        }
    }

    private void imgmethod() {
        if((ActivityCompat.checkSelfPermission(
                this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED)){
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{
                        Manifest.permission.CAMERA,
                },123);
            }
        }
        else{
            camera=new Intent();
            camera.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(camera,118);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==118&& resultCode==RESULT_OK){
            Bitmap photo= (Bitmap) data.getExtras().get("data");
            imgbtn.setImageBitmap(photo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            byte[] b = baos.toByteArray();
            String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
            preferenceManager.setString("image_data",encodedImage);
            Toast.makeText(this, "Image saved in SharedPreferences", Toast.LENGTH_SHORT).show();
        }
        else{
            Toast.makeText(this, "could not captured", Toast.LENGTH_SHORT).show();
        }
    }

}

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)

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".DashboardActivity">


    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="DashBoard"
        android:textColor="@color/teal_700"
        android:textSize="40dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.094" />

    <ImageView
        android:id="@+id/img1"
        android:layout_width="180dp"
        android:layout_height="130dp"
        android:layout_marginTop="72dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.497"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView" />

</androidx.constraintlayout.widget.ConstraintLayout>

Here, we take 1 textview and 1 imageview.

activity_dashboard.xml layout

 

Step 2

Go to DashboardActivity.java and add the below code 

package com.example.sharedpreferenceexample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Base64;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class DashboardActivity extends AppCompatActivity {
    ImageView imageView;
    PreferenceManager preferenceManager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dashboard);
        imageView=findViewById(R.id.img1);
        preferenceManager=PreferenceManager.getInstance(this);

        String previouslyEncodedImage = preferenceManager.getString("image_data");

        if( !previouslyEncodedImage.equalsIgnoreCase("") ){
            byte[] b = Base64.decode(previouslyEncodedImage, Base64.DEFAULT);
            Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
            imageView.setImageBitmap(bitmap);
        }
    }
}

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.


Similar Articles