Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Sample code to store and retrieve image from database using <code>SQLiteOpenHelper</code> class</p> <pre><code>package com.aliahmad.store_retrive_image; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class DataManager extends SQLiteOpenHelper { public final static String tab="image"; public final static String col1="iname"; public final static String col2="id"; public DataManager(Context context) { super(context, "MyData", null, 1); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("create table image (iname text,id blob)"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.w(DataManager.class.getName(), "Upgrading database from version "+oldVersion+" to"+newVersion+", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS "+tab); onCreate(db); } } </code></pre> <p>when store button clicked call this function</p> <pre><code>public void onStore(View v) { try { ByteArrayOutputStream baos=new ByteArrayOutputStream(); //image is object of Bitmap that you want to store image.compress(CompressFormat.PNG, 100, baos); byte[] data=baos.toByteArray(); SQLiteDatabase db=new DataManager(this).getWritableDatabase(); ContentValues cv=new ContentValues(); cv.put(DataManager.col1, et.getText().toString()); cv.put(DataManager.col2, data); db.insert(DataManager.tab, null, cv); } catch (Exception e) { Toast.makeText(this, "Errro - "+e,1 ).show(); } } </code></pre> <p>to retrieve the image call this function </p> <pre><code>public void onRet(View v) { SQLiteDatabase db=new DataManager(this).getReadableDatabase(); Cursor cr=db.query(DataManager.tab, new String[]{DataManager.col2}, DataManager.col1+"= ?", new String[]{str[which]}, null, null, null); if(cr.moveToFirst()) { byte [] b=cr.getBlob(4); ByteArrayInputStream imageStream = new ByteArrayInputStream(b); image= BitmapFactory.decodeStream(imageStream); iv.setImageBitmap(image); } else { Toast.makeText(this, "not found", 1).show(); } db.close(); } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload