如何在数据库中插入和获取图像

时间:2017-01-04 06:19:22

标签: android android-studio

这是我的代码,插入图像文件时出错。

 SQLiteDatabase.openOrCreateDatabase("AddDetail", null);
    db1.execSQL("CREATE TABLE IF NOT EXISTS profile(name TEXT,photo BLOB); ");

    Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.file);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG,100,stream);

    byte imageInByte[]=stream.toByteArray();
    db1.execSQL("INSERT INTO profile VALUES('Ramesh',"+imageInByte+");");
    Cursor s= db1.rawQuery("Select * from profile",null);
    while(s.moveToNext()){
        jtv.setText(s.getString(0));
        byte[] image1= s.getBlob(1);
        Bitmap bmp= BitmapFactory.decodeByteArray(image1,0,image1.length);
        jim.setImageBitmap(bmp);
        }

1 个答案:

答案 0 :(得分:0)

我在这里解决了,错误在我的查询中。

jtv=(TextView)findViewById(R.id.tv1);
    jim=(ImageView)findViewById(R.id.im);
    db1=openOrCreateDatabase("ImgAdd",MODE_PRIVATE,null);
    jb1=(Button)findViewById(R.id.b1);

    db1.execSQL("CREATE TABLE IF NOT EXISTS profile(name TEXT,photo BLOB);");

    Bitmap image= BitmapFactory.decodeResource(getResources(),R.drawable.test);
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG,100,stream);
    imageInByte=stream.toByteArray();

    jb1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            try {
                db1.execSQL("INSERT INTO profile VALUES('Ramesh','" + imageInByte + "')");
                Log.d("Image : ", " Value Inserted");
         Cursor s= db1.rawQuery("Select * from profile",null);
            if(s.moveToNext()){
                jtv.setText(s.getString(0));
                byte[] image1= s.getBlob(1);
                Bitmap bmp= BitmapFactory.decodeByteArray(image1,1,image1.length);
                jim.setImageBitmap(bmp);
            }
            }
            catch(Exception e)
            {
                Log.d("Errrrrrr",e.toString());
            }
        }
    });