18 Oct 2014

Insert and Retrieve Image into Database android | Store and retrieve images from sqlite android

Hello Friends,

In this tutorial I am sharing the code to insert the image into database and retrieve the image from database.

I hope this article might be helpful to all learning developer.



For storing the image we are using the blob type. Blob is a Java interface representing the SQL BLOB type.An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.

The java.sql.Blob interface provides methods for setting and retrieving data in the Blob, for querying Blob data length, and for searching for data within the Blob. More details about Blob Here

Let start to implementation with android Project

Step 1 : Create main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/darker_gray"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:cacheColorHint="@android:color/transparent" >
    </ListView>


</LinearLayout>

Step 2 : Create item_list.xml
-Here it the .xml file for inflate item on list view

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imgIcon"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:contentDescription="@string/app_name"
        android:gravity="center_vertical"
        android:src="@drawable/photo" />

    <TextView
        android:id="@+id/txtTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginLeft="7dp"
        android:layout_weight="1"
        android:gravity="center_vertical"
        android:text="@string/app_name"
        android:textColor="@android:color/black"
        android:textSize="14sp" />


</LinearLayout>

Step 3 : DatabaseHalper.java
-The class have Database operation like - insert , select ,delete , update 

import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHalper extends SQLiteOpenHelper
{
       // All Static variables
       // Database Version
       private static final int DATABASE_VERSION = 1;

       // Database Name
       private static final String DATABASE_NAME = "imagedb";

       // items table name
       private static final String TABLE_Items = "Items";

       // items Table Columns names
       private static final String KEY_ID = "id";
       private static final String KEY_NAME = "name";
       private static final String KEY_IMAGE = "image";

       public DatabaseHalper(Context context)
       {
              super(context, DATABASE_NAME, null, DATABASE_VERSION);
       }

       // Creating Tables
       @Override
       public void onCreate(SQLiteDatabase db)
       {
              String CREATE_itemS_TABLE = "CREATE TABLE " + TABLE_Items + "("
                           + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                           + KEY_IMAGE + " BLOB" + ")";
              db.execSQL(CREATE_itemS_TABLE);
       }

       // Upgrading database
       @Override
       public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
       {
              // Drop older table if existed
              db.execSQL("DROP TABLE IF EXISTS " + TABLE_Items);

              // Create tables again
              onCreate(db);
       }

       /**
        * All CRUD(Create, Read, Update, Delete) Operations
        */

       public// Adding new item
       void addItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();

              ContentValues values = new ContentValues();
              values.put(KEY_NAME, item._name);
              values.put(KEY_IMAGE, item._image);

              // Inserting Row
              db.insert(TABLE_Items, null, values);
              db.close(); // Closing database connection
       }

       // Getting single item
       ItemBean getitem(int id)
       {
              SQLiteDatabase db = this.getReadableDatabase();

              Cursor cursor = db.query(TABLE_Items, new String[] { KEY_ID,KEY_NAME, KEY_IMAGE }, KEY_ID + "=?",
                           new String[] { String.valueOf(id) }, null, null, null, null);
              if (cursor != null)
                     cursor.moveToFirst();

              ItemBean item = new ItemBean(Integer.parseInt(cursor.getString(0)),
                           cursor.getString(1), cursor.getBlob(1));

              // return item
              return item;

       }

       // Getting All items
       public List<ItemBean> getAllItems()
       {
              List<ItemBean> itemList = new ArrayList<ItemBean>();
              String selectQuery = "SELECT  * FROM "+TABLE_Items+" ORDER BY name";

              SQLiteDatabase db = this.getWritableDatabase();
              Cursor cursor = db.rawQuery(selectQuery, null);
             
              // looping through all rows and adding to list
              if (cursor.moveToFirst())
              {
                     do
                     {
                           ItemBean item = new ItemBean();
                           item.setID(Integer.parseInt(cursor.getString(0)));
                           item.setName(cursor.getString(1));
                           item.setImage(cursor.getBlob(2));
                          
                           itemList.add(item);
                     }
                     while (cursor.moveToNext());
              }
              db.close();
              return itemList;

       }

       // Updating single item
       public int updateItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();
             
              ContentValues values = new ContentValues();
              values.put(KEY_NAME, item.getName());
              values.put(KEY_IMAGE, item.getImage());

              // updating row
              return db.update(TABLE_Items, values, KEY_ID + " = ?",new String[] { String.valueOf(item.getID()) });

       }

       // Deleting single item
       public void deleteItem(ItemBean item)
       {
              SQLiteDatabase db = this.getWritableDatabase();
              db.delete(TABLE_Items, KEY_ID + " = ?",new String[] { String.valueOf(item.getID()) });
              db.close();
       }

       // Getting items Count
       public int getItemCount()
       {
              String countQuery = "SELECT  * FROM " + TABLE_Items;
              SQLiteDatabase db = this.getReadableDatabase();
              Cursor cursor = db.rawQuery(countQuery, null);
              cursor.close();

              // return count
              return cursor.getCount();
       }

}

Step 3 : SQLiteDemoActivity.java

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import com.hb.sqlite.R;


public class SQLiteDemoActivity extends Activity
{
       ArrayList<ItemBean> imageArry = new ArrayList<ItemBean>();
       ItemImageAdapter adapter;
      
       @Override
       public void onCreate(Bundle savedInstanceState)
       {
              super.onCreate(savedInstanceState);
              setContentView(R.layout.main);

              DatabaseHalper db = new DatabaseHalper(this);
             
              // get image from drawable
              Bitmap image = BitmapFactory.decodeResource(getResources(),R.drawable.photo);

              // convert bitmap to byte
              ByteArrayOutputStream stream = new ByteArrayOutputStream();
              image.compress(Bitmap.CompressFormat.JPEG, 100, stream);
              byte imageInByte[] = stream.toByteArray();
             
              // Inserting Contacts
              Log.d("Insert: ", "Inserting ..");
              db.addItem(new ItemBean("Android Logo", imageInByte));

              // Reading all contacts from database
              List<ItemBean> contacts = db.getAllItems();
              for (ItemBean cn : contacts)
              {
                     String log = "ID:" + cn.getID() + " Name: " + cn.getName()+ " ,Image: " + cn.getImage();

                     Log.d("Result: ", log);
                    
                     //add contacts data in arrayList
                     imageArry.add(cn);

              }
              adapter = new ItemImageAdapter(this, R.layout.item_list,imageArry);
              ListView dataList = (ListView) findViewById(R.id.list);
              dataList.setAdapter(adapter);

       }

}

Step 4 : ItemBean.java

-Class for which have set and get methods

public class ItemBean {

       int _id;
       String _name;
       byte[] _image;

       // Empty constructor
       public ItemBean() {

       }

       // constructor
       public ItemBean(int keyId, String name, byte[] image) {
              this._id = keyId;
              this._name = name;
              this._image = image;

       }

       // constructor
       public ItemBean(String contactID, String name, byte[] image) {
              this._name = name;
              this._image = image;

       }

       // constructor
       public ItemBean(String name, byte[] image) {
              this._name = name;
              this._image = image;
       }

       // getting ID
       public int getID() {
              return this._id;
       }

       // setting id
       public void setID(int keyId) {
              this._id = keyId;
       }

       // getting name
       public String getName() {
              return this._name;
       }

       // setting name
       public void setName(String name) {
              this._name = name;
       }

       // getting phone number
       public byte[] getImage() {
              return this._image;
       }

       // setting phone number
       public void setImage(byte[] image) {
              this._image = image;
       }

}

Step 5 : ItemImageAdapter.java

import java.io.ByteArrayInputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.hb.sqlite.R;

public class ItemImageAdapter extends ArrayAdapter<ItemBean>
{
       Context context;
       int layoutResourceId;

       ArrayList<ItemBean> data=new ArrayList<ItemBean>();

       public ItemImageAdapter(Context context, int layoutResourceId, ArrayList<ItemBean> data)
       {
              super(context, layoutResourceId, data);
              this.layoutResourceId = layoutResourceId;
              this.context = context;
              this.data = data;
       }

       @Override
       public View getView(int position, View convertView, ViewGroup parent)
       {
              View row = convertView;
              ImageHolder holder = null;

              if(row == null)
              {
                     LayoutInflater inflater = ((Activity)context).getLayoutInflater();
                     row = inflater.inflate(layoutResourceId, parent, false);

                     holder = new ImageHolder();
                     holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
                     holder.imgIcon = (ImageView)row.findViewById(R.id.imgIcon);
                     row.setTag(holder);
              }
              else
              {
                     holder = (ImageHolder)row.getTag();
              }

              ItemBean picture = data.get(position);
              holder.txtTitle.setText(picture._name);
             
              //convert byte to bitmap take from contact class

              byte[] outImage=picture._image;
              ByteArrayInputStream imageStream = new ByteArrayInputStream(outImage);
              Bitmap theImage = BitmapFactory.decodeStream(imageStream);
              holder.imgIcon.setImageBitmap(theImage);
              return row;

       }

       static class ImageHolder
       {
              ImageView imgIcon;
              TextView txtTitle;
       }

}

For more reference visit this post

I will be happy if you will provide your feedback or follow this blog. Any suggestion and help will be appreciated.
Thank you :)




No comments:

Post a Comment