将图像添加到SQLite数据库表

时间:2016-04-06 22:21:23

标签: android sqlite android-sqlite

我是Android和Java的相对新手。我在向SQLite数据库表添加图像时遇到了一些麻烦。以下是我的表格设计:

private static final String CREATE_GALLERY_TABLE = "CREATE TABLE "
    + GALLERY_TABLE + "("
    + ID + " INTEGER PRIMARY KEY,"
    + IMAGE + " BLOB,"
    + TITLE + " TEXT,"
    + CAPTION + " TEXT" + ")";

这是我向image表添加titlecaptiongallery的方法:

public boolean createGallery(byte[] image, String title, String caption) throws SQLiteException {
 SQLiteDatabase db = this.getWritableDatabase();
 ContentValues values = new ContentValues();

 values.put(IMAGE, image);
 values.put(TITLE, title);
 values.put(CAPTION, caption);

 long result = db.insert(GALLERY_TABLE, null, values);

 if (result == -1)
  return false;
 else
  return true;
}

在我的活动中,我有以下方法:

//user selects image from gallery
public void selectImage() {
 selectButton.setOnClickListener(
  new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(galleryIntent, RESULT_LOAD_IMAGE);
   }
  }
 );
}

//This method is called when user selected image from gallery
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
 super.onActivityResult(requestCode, resultCode, data);
 if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
  Uri selectedImage = data.getData();
  viewImage.setImageURI(selectedImage);
 }
}
public void uploadImage() {
 uploadButton.setOnClickListener(
  new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    Bitmap image = ((BitmapDrawable) viewImage.getDrawable()).getBitmap();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    image.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
    String encodedImage = Base64.encodeToString(byteArrayOutputStream.toByteArray(), Base64.DEFAULT);

    boolean isInserted = myDb.createGallery(
     encodedImage.getBytes(),
     addTitle.getText().toString(),
     addCaption.getText().toString()
    );

    if (isInserted == true) {

     Toast.makeText(gallery.this, "Image uploaded successfully added", Toast.LENGTH_SHORT).show();
    } else
     Toast.makeText(gallery.this, "Image upload has failed", Toast.LENGTH_SHORT).show();

   }
  }
 );
}

我可以从图库中选择一个图像,当我选择了ImageView名为viewImage时,我会成功显示我选择的图像。我也能够成功插入数据库,插入标题和标题,但图像列是空白的。知道我哪里出错了吗?任何帮助将不胜感激。

0 个答案:

没有答案