alibi
alibi

Reputation: 11

how to save images in sqlite and display it?

I have a database , the database contents are the name , address , image ( varchar ) and the images folder . I 've parser ( using json ) and stored in a sqlite , whether the image can be downloaded to sqlite ? and I also wanted to present it in an application ? how to do it ? please let me know :(

Upvotes: 0

Views: 511

Answers (3)

user943716
user943716

Reputation:

// Create a table with BLOB datatype 
     String SQL_TABLE = "create table "
      + TABLE_MESSAGE + "(" + "id"
      + " integer primary key autoincrement, "
      + "name"  + " text not null, "
      + address     + " text not null, " 
      + image   + " BLOB);";


      to store image into this you have to convert it to bytes like so:

     public static byte[] makeByte(Bitmap bitmap) {

     if (bitmap == null) {
     return null;
     } else {
     byte[] b = null;
     try {
     ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
     bitmap.compress(CompressFormat.JPEG, 75, byteArrayOutputStream);
     b = byteArrayOutputStream.toByteArray();
     } catch (Exception e) {
     e.printStackTrace();
     }
     return b;
     }
     }

after the get byte then you can save into the database like you save or update any other field. then you can recreate the image using this function and add to ImageView

    public static Bitmap getBitmapFromByte(byte[] pByte){
    if (pByte == null) {
        return null;
    }
    Bitmap bmp = BitmapFactory.decodeByteArray(pByte, 0, pByte.length);

    return bmp;
    }

pass the above function the bytes you stored in database, this will return a bitmap that can be set on imageview exmaple Bitmap img = getBitmapFromByte(byteData);

Upvotes: 0

Jaroslav
Jaroslav

Reputation: 263

serialize them to internal storage and save the paths as ordinary string values. But if your images are dynamic (loaded from web sources) I would better save their links and use LruCache http://developer.android.com/training/displaying-bitmaps/cache-bitmap.html

Upvotes: 0

inverse12
inverse12

Reputation: 186

Putting image in sqlite is bad practice. You should store img as file and put the path to file with img to sqlite.

Upvotes: 1

Related Questions