商店&a​​mp;将图像检索到SQLite数据库中

时间:2015-01-18 18:19:53

标签: android database image sqlite blob

我要将一个位于可绘制文件夹中的图像存储到SQlite数据库中,之后只需检索它。我稍后会修改这个概念,但我在ImageView中什么都没有。

以下是代码:

public class DBHelper extends SQLiteOpenHelper {

    protected static final String DATABASE_NAME = "kamuskerul2";
    private static final int DB_VERSION = 1;
    private final Context myContext;

    public DBHelper(Context context) {
        super(context, DATABASE_NAME, null, DB_VERSION);
        this.myContext = context;
    }

    public void onCreate(SQLiteDatabase sqlitedatabase) {

        sqlitedatabase.execSQL("CREATE TABLE tableimage (image BLOB);");
        Bitmap mybitmap = BitmapFactory.decodeResource(myContext.getResources(), R.drawable.me);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        mybitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
        byte[] img = bos.toByteArray();

        ContentValues myContentValues = new ContentValues();
        myContentValues.put("imag", img);

        sqlitedatabase.execSQL("INSERT INTO tableimage (image) VALUES('"+myContentValues+"');");


    }// END of onCreate().


    public void onUpgrade(SQLiteDatabase sqlitedatabase, int i, int j) { 
        if (i >= j) {
            return;
        } else {
            sqlitedatabase.execSQL("DROP DATABASE IF EXISTS kamuskerul2;");
            onCreate(sqlitedatabase);
            return;
        }
     }
  }

另一个类(检索图像并显示它)。

private DBHelper dbhelper = new DBHelper(this);
private SQLiteDatabase db;  
ImageView myTestedImageView;
byte[] imgimg;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.MainActivity);

    db = dbhelper.getReadableDatabase();

    // ImageView
    myTestedImageView = (ImageView)findViewById(R.id.myTestedImageViewXML);

}// end onCreate



public void onClick(View v) {
    String image_name = "myContentValues";
    Cursor cursor_image = db.rawQuery("SELECT * FROM tableimage " + "WHERE image='" + image_name + "';", null);

    if (cursor_image.getCount() != 0) {

            cursor_image.moveToFirst();
            do {
                imgimg =   cursor_image.getBlob(cursor_image.getColumnIndex("image"));
            } while (cursor_image.moveToNext());

            Bitmap b1 = BitmapFactory.decodeByteArray(imgimg, 0, imgimg.length);
            myTestedImageView.setImageBitmap(b1);

}

当我运行应用程序时,没有任何显示,数据库为空。 希望你能得到我的想法并帮助我克服这个问题。

1 个答案:

答案 0 :(得分:0)

最好将图像克隆到应用程序的外部存储器,而不是将图像的字节保存在数据库中。您可以在数据库中保存路径或仅保存图像的名称。

有关文件存储选项的Android文档:http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

将图像作为blob保存在SQLite数据库中是我的观点,即使您将图像转换为字节也是如此。