如何将图像插入SQLite数据库

时间:2017-10-25 09:09:04

标签: java android android-sqlite

我正在尝试将图片插入SQLite数据库,但我收到了null点异常,但检查了没有任何null object。我尝试了我的水平最好,但我仍然找不到问题帮助我。我尝试过的代码如下所示。谢谢堆栈溢出,请帮帮我,

MainActivity.class

public class MainActivity extends AppCompatActivity {
ImageView imageView;
Button button;
Bitmap bitmap;
Context context;

LocalDatabase localDatabase;
public static final int PICK_IMAGE = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    imageView=(ImageView)findViewById(R.id.imageid);
    localDatabase=new LocalDatabase(this);
    button=(Button)findViewById(R.id.btnid);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if (requestCode == PICK_IMAGE) {
        Uri uri=data.getData();
        imageView.setImageURI(uri);
        InputStream iStream = null;
        try {
            iStream = getContentResolver().openInputStream(uri);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        try {
            byte[] inputData = getBytes(iStream);
            saveimage(inputData);
        } catch (IOException e) {
            e.printStackTrace();
        }


    }
}
public byte[] getBytes(InputStream inputStream) throws IOException {
    ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
    int bufferSize = 1024;
    byte[] buffer = new byte[bufferSize];

    int len = 0;
    while ((len = inputStream.read(buffer)) != -1) {
        byteBuffer.write(buffer, 0, len);
    }
    return byteBuffer.toByteArray();
}
boolean saveimage(byte[] bytes)
{
    localDatabase.insertImage(bytes);
    return true;
}
}

LocalDataBase.class

public class LocalDatabase extends SQLiteOpenHelper {
public static final String IMAGE_ID = "id";
public static final String IMAGE = "image";
LocalDatabase localDatabase;


private SQLiteDatabase mDb;

private static final String DATABASE_NAME = "Images.db";
private static final int DATABASE_VERSION = 1;

private static final String IMAGES_TABLE = "ImagesTable";

private static final String CREATE_IMAGES_TABLE =
        "CREATE TABLE " + IMAGES_TABLE + " (" +
                IMAGE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + IMAGE + " BLOB NOT NULL );";

public LocalDatabase(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}


@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
    mDb.execSQL(CREATE_IMAGES_TABLE);

}

@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
    sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + CREATE_IMAGES_TABLE);
    onCreate(sqLiteDatabase);
}

// Insert the image to the Sqlite DB
public void insertImage(byte[] imageBytes) {
     mDb=localDatabase.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(IMAGE, imageBytes);
    mDb.insert(IMAGES_TABLE, null, cv);
    localDatabase.close();
}

// Get the image from SQLite DB
// We will just get the last image we just saved for convenience...
public byte[] retreiveImageFromDB() {
    Cursor cur = mDb.query(true, IMAGES_TABLE, new String[]{IMAGE,},
            null, null, null, null,
            IMAGE_ID + " DESC", "1");
    if (cur.moveToFirst()) {
        byte[] blob = cur.getBlob(cur.getColumnIndex(IMAGE));
        cur.close();
        return blob;
    }
    cur.close();
    return null;
}
}

1 个答案:

答案 0 :(得分:0)

public static byte[] getBytes(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 0, stream);
    return stream.toByteArray();
}

然后将bytearray插入到列类型为blob

的数据库中