I'm a relative newcomer to Android and Java. I am having some trouble adding an image to my SQLite database table. Below is my table design:
private static final String CREATE_GALLERY_TABLE = "CREATE TABLE "
+ GALLERY_TABLE + "("
+ ID + " INTEGER PRIMARY KEY,"
+ IMAGE + " BLOB,"
+ TITLE + " TEXT,"
+ CAPTION + " TEXT" + ")";
This is my method to add an image, title and caption to the gallery table:
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;
}
Within my activity I have the following methods:
//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();
}
}
);
}
I am able to select an image from the gallery and when selected I have an ImageView named viewImage which successfully shows the image I selected. I am also able to successfully insert to the database, the title and caption are inserted but the image column is blank. Any idea where I may have gone wrong? Any help would be appreciated.
Aucun commentaire:
Enregistrer un commentaire