4

Dears How I can Android Save Image And Get Image From Sqlite Database I'm Using Android Studio ?

2
  • Convert Image into Base 64 String and then store it into database and do vice versa when fetching the image. See this for Base 64 APIs in android. Commented Mar 10, 2016 at 13:32
  • If you want to store binary file into sqlite, save it as blob type. Maybe this link can help you: stackoverflow.com/questions/7331310/… Commented Mar 10, 2016 at 13:42

2 Answers 2

3

Might be too late. but useful for future readers..

import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


import java.util.HashMap;

 /**
  * Created by Noorul on 23-05-2016.
 */

@SuppressWarnings("ALL")
public class DBSplash extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "SplashDB.db";
public static final String SPLASH_TABLE_NAME = "splash_db";

private HashMap hp;

public DBSplash(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(
            "create table " + SPLASH_TABLE_NAME + "( name TEXT, image BLOB)"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS contacts");
    onCreate(db);
}

public boolean insertImage(String name, Bitmap img) {
    Bitmap storedBitmap = null;
    String sql = "INSERT INTO " + SPLASH_TABLE_NAME + " (name,image) VALUES(?,?)";
    SQLiteDatabase db = this.getWritableDatabase();
    SQLiteStatement insertStmt = db.compileStatement(sql);

    byte[] imgByte = getBitmapAsByteArray(img);
    try {
        storedBitmap = getImage(name);
    } catch (Exception e) {
        AppLog.exception(e);
    }
    if (storedBitmap == null) {
        insertStmt.bindString(1, name);
        insertStmt.bindBlob(2, imgByte);
        insertStmt.executeInsert();
        db.close();
    }
    return true;
}


public int numberOfRows() {
    SQLiteDatabase db = this.getReadableDatabase();
    int numRows = (int) DatabaseUtils.queryNumEntries(db, SPLASH_TABLE_NAME);
    return numRows;
}


public Bitmap getImage(String name) {
    String qu = "SELECT * FROM " + SPLASH_TABLE_NAME;
    Cursor cur = null;
    SQLiteDatabase db = this.getReadableDatabase();

    try {
        cur = db.rawQuery(qu, new String[]{});
    } catch (Exception e) {
        AppLog.exception(e);
    }
    if (cur != null) {
        if (cur.moveToFirst()) {
            int index = cur.getColumnIndexOrThrow("image");
            byte[] imgByte = cur.getBlob(index);
            cur.close();
            return BitmapFactory.decodeByteArray(imgByte, 0, imgByte.length);
        }
        if (cur != null && !cur.isClosed()) {
            cur.close();
        }
    }

    return null;
}
   public byte[] getBitmapAsByteArray(Bitmap bitmap) {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG, 0, outputStream);
    return outputStream.toByteArray();
}
}

Use this code. But storing images in databases is not not best practices.change the image size if you need unblurred image. IMages are blob type with high memory . mobile is smaller device . so storing many images in sqlite db means, it will be ugly. so use @thuongle method

Sign up to request clarification or add additional context in comments.

Comments

0

You can check this tutorial for implementing Sqlite in Android. http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

Instead working with Contact for example, you can implement this way

public class Image{
    String imagePath; //it is your absolute image file path
}

And your DatabaseHandler can be implemented like below

public class DatabaseHandler extends SQLiteOpenHelper {

    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

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

    // Contacts table name
    private static final String TABLE_IMAGE = "images";

    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_IMAGE_PATH = "name";

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

    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String sqlQuery = "CREATE TABLE " + TABLE_IMAGE + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_IMAGE_PATH + " TEXT)";
        db.execSQL(sqlQuery);
    }

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

        // Create tables again
        onCreate(db);
    }

    // Adding new image
    public void addImage(Image image) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(KEY_IMAGE_PATH, image.imagePath); // Image path

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


    // Getting single image
    public Image getImage(int id) {
        SQLiteDatabase db = this.getReadableDatabase();

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

        Image image = new Image(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1));
        // return image
        return image;
    }
}

2 Comments

I think he wants to store whole image object into database, not image path.
Thank you @ᖷAЯAƸ. I thought he was asking for a sqlite tutorial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.