Add & Retrieve Image From SQLite Database Example In Android Studio

In this article we are going to discuss about how to add or retrieve image from phone external storage to application using SQLite Database. Basically we create a database and a table in the application using SQLite. The table will hold the image which is fetched from external storage.

There is a difference while retrieving with different API level. The permission concept has changed since API 23. Before API level 23 the user was asked during installation and after API level 23 the user is asked during runtime. So, an additional runtime permission is added in the application operating over the API level above 23.

Here are both ways explained step by step to add or retrieve image from SQLite database.


Example 1: Adding and Retrieving Image From SQLite Database (Below API LEVEL 23)

In this example we used buttons and imageview for creating UI, on button onclick is added and methods are defined in corresponding java class.

Download Code (Password: abhiandroid)

Adding Or Retrieving Image Using SQLite

Step 1: Create a new project and name it SqliteImageDemo.

Step 2:Open AndroidManifest.xml file and add permission to access external storage.

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

Step 3:Open res -> layout -> activity_main.xml (or) main.xml and add following code:

In this code simply add imageview and button with onclick functionality.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sqliteimagedemo.MainActivity">

    <Button
        android:text="@string/get_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="19dp"
        android:id="@+id/button"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="save"/>

    <Button
        android:text="@string/view_image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="29dp"
        android:id="@+id/button2"
        android:layout_below="@+id/button"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:onClick="get"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@mipmap/ic_launcher"
        android:id="@+id/imageView"
        android:layout_below="@+id/button2"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="43dp"
        tools:ignore="ContentDescription" />
</RelativeLayout>

Step 4: Open src -> package -> MainActivity.java

In this step we open MainActivity and add the functions defined over button onclick i.e save or get. The save method contain FileInputStream to get file from the defined path and save it to the database. Further the image is inserted into the table using SQLiteDatabase, Toast is used to indicate the operation is completed. The get method uses SQLite select statement to retrieve the saved image and displaying it in the imageview.

package com.example.sqliteimagedemo;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.FileInputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    ImageView imageView;
    SQLiteDatabase db;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageView = (ImageView) findViewById(R.id.imageView);
        //database created
        db = this.openOrCreateDatabase("test.db", Context.MODE_PRIVATE,null);
        //table created
        db.execSQL("create table if not exists imageTb ( a blob )");
    }
       
    public  void save(View view) throws IOException {
        FileInputStream fis = new FileInputStream("/storage/sdcard/demoImage.jpg");
        byte[] image= new byte[fis.available()];
        fis.read(image);
        ContentValues values = new ContentValues();
        values.put("a",image);
        db.insert("imageTb", null,values);
        fis.close();
        Toast.makeText(this,"Done", Toast.LENGTH_SHORT).show();
    }
    public void get(View view) {
        Cursor c = db.rawQuery("select * from imageTb", null);
        if(c.moveToNext())
        {
            byte[] image = c.getBlob(0);
            Bitmap bmp= BitmapFactory.decodeByteArray(image, 0 , image.length);
            imageView.setImageBitmap(bmp);
            Toast.makeText(this,"Done", Toast.LENGTH_SHORT).show();
        }
    }
}

Output:

Now run the app and click on the button to add and retrieve the image in App.


Example 2: Adding and Retrieving Image From SQLite Database(Above API LEVEL 23)

In this example we used buttons and imageview for creating UI, on button onclick is added and methods are defined in corresponding java class. The basic difference is that we need to define the permissions at the run time.

Download Code (Password: abhiandroid)

Adding Or Retrieving Image Example Using SQLite
Step 1: Create a new project and name it SqliteImageDemo.
Step 2:Open AndroidManifest.xml file and add permission to access external storage.

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

Step 3:Open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this code simply add imageview and button with onclick functionality.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.sqliteimagedemo.MainActivity">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_marginTop="61dp"
        android:id="@+id/imageView"
        android:layout_below="@+id/button1"
        android:layout_alignLeft="@+id/button1"
        android:layout_alignStart="@+id/button1" />

    <Button
        android:text="VIEW  FETCHED IMAGE"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button2"
        android:onClick="viewImage"
        android:layout_below="@+id/button1"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

    <Button
        android:text="FETCH IMAGE FROM EXTERNAL STORAGE"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/button1"
        android:onClick="fetchImage"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

Step 4: Open src -> package -> MainActivity.java

In this step we open MainActivity and add the functions defined over button onclick i.e save or get. The save method contain FileInputStream to get file from the defined path and save it to the database. Further the image is inserted into the table using SQLiteDatabase, Toast is used to indicate the operation is completed. The get method uses SQLite select statement to retrieve the saved image and displaying it in the imageview.

In addition to previous API a statement is added that is basically a permission to read/write external storage.

package com.example.sqliteimagedemo;

import android.Manifest;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;


public class MainActivity extends AppCompatActivity {
   
    private int STORAGE_PERMISSION_CODE = 23;
    ImageView imageView;
    SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Permission to access external storage
        ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},STORAGE_PERMISSION_CODE);
        imageView = (ImageView) findViewById(R.id.imageView);
        //creating database
        db = this.openOrCreateDatabase("test.db", Context.MODE_PRIVATE,null);
        //creating table for storing image
        db.execSQL("create table if not exists imageTb ( image blob )");
    }

    public void viewImage(View view)
    {
        Cursor c = db.rawQuery("select * from imageTb", null);
        if(c.moveToNext())
        {
            byte[] image = c.getBlob(0);
            Bitmap bmp= BitmapFactory.decodeByteArray(image, 0 , image.length);
            imageView.setImageBitmap(bmp);
            Toast.makeText(this,"Done", Toast.LENGTH_SHORT).show();
        }
    }

    public  void fetchImage(View view) throws IOException {

        File folder= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/demoImage.jpg/");
        FileInputStream fis = new FileInputStream(folder);
        byte[] image= new byte[fis.available()];
        fis.read(image);
        ContentValues values = new ContentValues();
        values.put("image",image);
        db.insert("imageTb", null,values);
        fis.close();
        Toast.makeText(this,"Image Fetched", Toast.LENGTH_SHORT).show();
    }
}

Output:

Now run the app and click on the button to add and retrieve the image in App.

  • Is This Tutorial Helps You Understand ?
  • YES   NO

Leave a Reply

Your email address will not be published. Required fields are marked *