即使您已将其转换为字节,我也无法将我的图像插入到sqlite数据库中。我做错什么了吗?

时间:2018-01-12 08:03:38

标签: android sqlite

我的OnActiviy结果无论什么时候被调用,它都会一直工作到我的图像视图的设置背景,它总是会显示"出现问题"每当我要把它放在我的sqlite中时,我真的无法找到它不工作的原因T_T

public void onActivityResult(int requestcode,int resultcode,Intent intent)
{
    dbHbeforePIC = new DBHbeforePIC(this);

    super.onActivityResult(requestcode, resultcode, intent);
    if(resultcode==RESULT_OK)
    {
        if(requestcode==1)
        {
            Bitmap photo = (Bitmap)intent.getExtras().get("data");
            Drawable drawable=new BitmapDrawable(photo);
            imgBefore.setBackground(drawable);
            byte[] img = DbBitmapUtility.getBytes(photo);
            boolean insertData = dbHbeforePIC.addBeforeImage("test", img);
            if (insertData == true) {
                Toast.makeText(MyProfile.this, "Data successfully inserted", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MyProfile.this, "Something went wrong", Toast.LENGTH_LONG).show();
            }
        }

这是我的DbBitmapUtility类

public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
    return stream.toByteArray();
}

// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}

我的数据库类

public class DBHbeforePIC extends SQLiteOpenHelper {

public static final String DATABASE_NAME = "beforepic.db";
public static final String TABLE_NAME = "beforepic_data";
public static final String COL1 = "ID";
public static final String COL2 = "ImageName";
public static final String COL3 = "ImageItself";

public DBHbeforePIC(Context context) {
    super(context, DATABASE_NAME, null, 1);
}

@Override
public void onCreate(SQLiteDatabase db) {
    String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
            " ImageName TEXT, ImageItself BLOB )";
    db.execSQL(createTable);
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
    onCreate(db);
}

public boolean addBeforeImage( String name, byte[] image) throws SQLiteException {
    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues cv = new  ContentValues();
    cv.put(COL2,    name);
    cv.put(COL3,   image);
    long result = db.insert(DATABASE_NAME, null, cv );
    if (result == -1) {
        return false;
    } else {
        return true;
    }
}

}

1 个答案:

答案 0 :(得分:1)

您正在尝试使用数据库名称代替表名

更改此行

long result = db.insert(DATABASE_NAME, null, cv );

到下面

 long result = db.insert(TABLE_NAME, null, cv );