ondrovic
ondrovic

Reputation: 1175

Image to database from drawable

I have search hi and low, read many different post and tutorials but yet I can't seem to figure out how to get my images to save in a database.

It seems that every time I attempt to put an image into the database it causes the database to not be created and then I get a force close. I would love some help.

Here is my code

 package com.ondrovic.boombozzpassport;

 import java.io.ByteArrayOutputStream;
 import java.io.IOException;

 import android.content.ContentValues;
 import android.content.Context;
 import android.database.sqlite.SQLiteDatabase;
 import android.database.sqlite.SQLiteOpenHelper;
 import android.graphics.Bitmap;
 import android.graphics.Bitmap.CompressFormat;
 import android.graphics.BitmapFactory;
 import android.provider.BaseColumns;
 import android.util.Log;

 public class Database extends SQLiteOpenHelper implements BaseColumns {
     private final static String DB_NAME = "boombozz.db";
     private final static int DB_VERSION = 1;
     static final String TABLE_BEERS = "beers";
     static final String COL_NAME = "name";
     static final String COL_BREWER = "brewer";
     static final String COL_ABV = "abv";
     static final String COL_RATE = "rating";
     static final String COL_BDESC = "breifdescription";
     static final String COL_FDESC = "fulldescription";
     static final String COL_TYPE = "type";
     static final String COL_PIC = "picture";

     private Context mContext;
     private Bitmap picture = null;

 public Database(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE beers (" + "_id INTEGER PRIMARY KEY, "
            + "name TEXT, " + "brewer TEXT, " + "abv REAL, "
            + "rating REAL, " + "breifdescription TEXT, "
            + "fulldescription TEXT, " + "type TEXT, " + "picture BLOB);");

    addBeer(db, "NAME 1", "BREWER 1", "TYPE 1", "BDESC 1", "FDESC 1", 0, 0, R.drawable.beer1);

}

private void addBeer(SQLiteDatabase db, String name, String brewer,
        String type, String bdesc, String fdesc, int abv, int rate, int image) {
    final ContentValues cv = new ContentValues();
    cv.put(COL_NAME, name);
    cv.put(COL_BREWER, brewer);
    cv.put(COL_TYPE, type);
    cv.put(COL_BDESC, bdesc);
    cv.put(COL_FDESC, fdesc);
    cv.put(COL_ABV, abv);
    cv.put(COL_RATE, rate);


    final Bitmap bitmap = BitmapFactory.decodeResource(
            mContext.getResources(), image);
    writeBitmap(cv, COL_PIC, bitmap);

    db.insert(TABLE_BEERS, null, cv);
}

static void writeBitmap(ContentValues cv, String name, Bitmap image) {
    if (image != null) {
        try {
            int size = image.getWidth() * image.getHeight() * 2;
            ByteArrayOutputStream out = new ByteArrayOutputStream(size);

            image.compress(CompressFormat.PNG, 100, out);
            out.flush();
            out.close();

            cv.put(name, out.toByteArray());

        } catch (IOException e) {

        }
    }
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    Log.w("onUpgrade", "Upgrading database from version: " + oldVersion
            + " to version: " + newVersion);
    db.execSQL("DROP TABLE IF EXISTS beers");
}
}

Upvotes: 0

Views: 1675

Answers (2)

unnamedhorse
unnamedhorse

Reputation: 1823

Are you downloading those images? If yes, save it to the SDCard/Phone Memory as suggested by Venkata Krishna. It's pretty simple to save your image into the disk.

First we create a method to check if we can read and write into the external storage disk.

/**
 * @return true if the external storage is mounted or read only.
 */
public static boolean isExternalStorageReadable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}

/**
 * @return true if the external storage is mounted and writable.
 */
public static boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    return Environment.MEDIA_MOUNTED.equals(state);
}

Then, another method that will check if we have enough space available in the external storage disk.

/**
 * @return the amount of free space on the external storage.
 */
public static long getAvailableExternalMemorySize() {
    File path = Environment.getExternalStorageDirectory();
    StatFs stat = new StatFs(path.getPath());
    long blockSize = stat.getBlockSize();
    long availableBlocks = stat.getAvailableBlocks();
    return availableBlocks * blockSize;
}

Now we create the method that will tell us if we can store the file in the sdcard.

/**
 * @return true if the external storage is available, writable, 
 * and contains enough free space.
 */
public static boolean isExternalStorageAvailable() {
    if (!isExternalStorageWritable()) return false;
    long availableSize = getAvailableExternalMemorySize();
    if (availableSize < REQUIRED_STORAGE_SPACE) {
        return false;
    }
    return true;
}

Where REQUIRED_STORAGE_SPACE is a constant with the amount of space that your app will use to store images and other stuff.

Now we'll create a method to store the image.

/**
 * @return the File from the given filename.
 */
public static File getImageFile(String filename) {
    if (!isExternalStorageReadable()) return null;
    // The images folder path.
    String imagesFolder = Environment.getExternalStorageDirectory().getPath()
                          + "Android/data/your.app.package/images/";
    // Creating the file.
    File file = new File(imagesFolder + filename);        
    return file;
}

/**
 * Write the contents of the HTTP entity to the external 
 * storage if available and writable.
 */
public static boolean storeImage(HttpEntity entity, String filename) throws IOException     {
    if (isExternalStorageAvailable()) {
        File file = getImageFile(filename);
        if (file == null) return false;
        // Write to file output stream.
        FileOutputStream os = new FileOutputStream(file);
        entity.writeTo(os);
        os.close();
        return true;
    }
    return false;
}

Put all of these methods into a class, let's say ImageHelper, check if you have permissions in your manifest file to write into the external storage and you are good to go.

Upvotes: 1

Venkata Krishna
Venkata Krishna

Reputation: 1603

save image in sdcard or phone memory and store that saved image path in database.whenever you want to access the image then take image path from database and using that path access image.

Upvotes: 0

Related Questions