SQLiteOpenHelper
使用类从数据库中存储和检索图像的示例代码
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);
}
}
单击存储按钮时调用此函数
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();
}
}
检索图像调用此函数
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();
}