Android save image sqlite database


In your application, you might want to allow the user to download images from the internet and save them locally in a database (sqlite database) then later view them in ImageView or in ListView. However, this approach should be used only with small images. For big images, you should save their path in the database and the image data in sdcard instead. In this Android tip, I am going to show you how to download an image from the internet and save it in a sqlite database. The image size is reduced before it is inserted into the database.
Inserting text or numbers to the sql database is simple. However, inserting an image to the database is a bit hard for beginners. Sqlite database has blob data type to store binary data including image data. To insert an image to a blob field, you need to convert the image to byte array using compress() method of the Bitmap object that represents your image. To get the image from the database and display it in an ImageView or ListView, you use the getBlob() method of a Cursor object to get the byte array of data from the blob field. Then convert the byte array to Bitmap object using the decodeByteArray method of BitmapFactory.
Now to have an example application on saving a downloaded image in the sqlite database, you create an Android project. Then in the activity_main.xml file, you add an EditText, a TextView, a Button and an ImageView as shown below.



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools= "http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:orientation="vertical"
   tools:context="com.example.saveimage.MainActivity" >
   <EditText
android:id="@+id/txtedit"
android:layout_width="match_parent"
android:layout_height="wrap_content"

/>
     <Button
android:id="@+id/btdownload"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Download and save to database"
android:onClick="downloadImage"
/>

<TextView
android:id="@+id/txtview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="false"
android:layout_gravity="center"

/>
<ImageView
android:id="@+id/imgview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>

</LinearLayout>


Then in the src folder, your create a class called DataHelper that helps you in creating a sqlite database and a table to store images, inserting image data to the database, and reading the image data to display in the ImageView.

import java.io.ByteArrayOutputStream;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class DataHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "imgdb";
public static final String TABLE_NAME = "tbl_img";
public static final int DATABASE_VERSION = 1;
public static final String CREATE_TABLE = "CREATE TABLE IF NOT EXISTS "+ TABLE_NAME+ "(id INTEGER PRIMARY KEY AUTOINCREMENT, img BLOB NOT NULL, description TEXT NULL)";
public static final String DELETE_TABLE="DROP TABLE IF EXISTS " + TABLE_NAME;

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

}
public void onCreate(SQLiteDatabase db) {
// Create the table
db.execSQL(CREATE_TABLE);

}
//Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop older table if existed
db.execSQL(DELETE_TABLE);
//Create tables again
onCreate(db);
}

public void insertBitmap(Bitmap bm) {

// Convert the image into byte array
ByteArrayOutputStream out = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, out);
byte[] buffer=out.toByteArray();
// Open the database for writing
SQLiteDatabase db = this.getWritableDatabase();
// Start the transaction.
db.beginTransaction();
ContentValues values;

try
{
values = new ContentValues();
values.put("img", buffer);
values.put("description", "Image description");
// Insert Row
long i = db.insert(TABLE_NAME, null, values);
Log.i("Insert", i + "");
// Insert into database successfully.
db.setTransactionSuccessful();

}
catch (SQLiteException e)
{
e.printStackTrace();

}
finally
{
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
}

public Bitmap getBitmap(int id){
Bitmap bitmap = null;
// Open the database for reading
SQLiteDatabase db = this.getReadableDatabase();
// Start the transaction.
db.beginTransaction();

try
{
String selectQuery = "SELECT * FROM "+ TABLE_NAME+" WHERE id = " + id;
Cursor cursor = db.rawQuery(selectQuery, null);
if(cursor.getCount() >0)
{
while (cursor.moveToNext()) {
// Convert blob data to byte array
byte[] blob = cursor.getBlob(cursor.getColumnIndex("img"));
// Convert the byte array to Bitmap
bitmap=BitmapFactory.decodeByteArray(blob, 0, blob.length);

}

}
db.setTransactionSuccessful();

}
catch (SQLiteException e)
{
e.printStackTrace();

}
finally
{
db.endTransaction();
// End the transaction.
db.close();
// Close database
}
return bitmap;

}

}

In the MainActivity class, you write code to download an image from the internet, save it in the database, and read the image to from the database to display in the ImageView.

package com.example.inputdialog;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity{
private DataHelper dbHelper;
private EditText et;
   protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.activity_main);
     et=(EditText)findViewById(R.id.txtedit);
     dbHelper=new DataHelper(this);
    
    
   }
  
   public void downloadImage(View view){
   BackTask bt=new BackTask();
   String imgURL=et.getText().toString();
   if(!imgURL.trim().equals("")){
   bt.execute(imgURL);
   }
  
   }
  
// AsynnTask to run download an image in background
   private class BackTask extends AsyncTask<String,Void,Bitmap>{
   TextView tv;
   protected void onPreExecute(){
     tv=(TextView)findViewById(R.id.txtview);
     tv.setText("Downloading the image. Please wait...");
   }
   protected Bitmap doInBackground(String...params){
   Bitmap bitmap=null;
   try {
   // Download the image
     URL url = new URL(params[0]);
     HttpURLConnection connection = (HttpURLConnection) url.openConnection();
     connection.setDoInput(true);
     connection.connect();
     InputStream is = connection.getInputStream();
     // Decode image to get smaller image to save memory
     final BitmapFactory.Options options = new BitmapFactory.Options();
     options.inJustDecodeBounds = false;
     options.inSampleSize=4;
     bitmap = BitmapFactory.decodeStream(is,null, options);
     is.close();
     }
     catch(IOException e){
     return null;
     }
   return bitmap;
   }
   protected void onPostExecute(Bitmap result){
   tv.setVisibility(TextView.GONE);
   // Insert bitmap to the database
   dbHelper.insertBitmap(result);
   ImageView imgView=(ImageView)findViewById(R.id.imgview);
   // Read the first image from database and show it in ImageView  
   imgView.setImageBitmap(dbHelper.getBitmap(1));
     }
   }
  
}


Before you run the example application, do not forget to declare INTERNET permission in AndroidManifest.xml file of your project.



Android-save-image-sqlite-database

Posted by: Dara | post date: 12-22-2014 | Subject: Android Apps Development

write programming tip




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.