Search code examples
sqliteandroid-sqliteandroid-imageviewandroid-image

Android - Storing a Camera image file path into SQLite db.


I have been trying to understand how the SQLite DB works in android. i made a simple app that uses the camera to take a photo and display it to the screen... what id like to do is also store a description of the photo too--and the best way i know how to do that is with a db. But I'm having trouble understanding how to store the image.

the image from the camera is kind of large, so i don't really want store it in the DB as a blob. I have been doing some digging on storing the file path as a text field in the database--and i think the SQL is right to store the path. this is from my DBAdapter class:

    private static final String DATABASE_CREATE_SQL = 
        "create table " + DATABASE_TABLE 
        + " (" + KEY_ROWID + " integer primary key autoincrement, "
        + KEY_USERNAME + " text, "
        + KEY_DATE + " text, "
        + KEY_PHOTO_DESCRIPTION + " text, "
        + KEY_IMAGE_PATH + " text"
        + ");";

insert method:

    public long insertRow(String username, String date, String photoDesc, String imagePath) {
    ContentValues initialValues = new ContentValues();
    initialValues.put(KEY_USERNAME, username);
    initialValues.put(KEY_DATE, date);
    initialValues.put(KEY_PHOTO_DESCRIPTION, photoDesc);
    initialValues.put(KEY_IMAGE_PATH, imagePath);

    // Insert it into the database.
    return db.insert(DATABASE_TABLE, null, initialValues);
}

then in my MainActivity--the onActivityResult() for receiving the image from the camera:

private void receiveImage(int resultCode) {
    if(resultCode == Activity.RESULT_OK) {
        getContentResolver().notifyChange(imageUri, null);
        ContentResolver contentResolver = getContentResolver();
        try {
            imageBitmap = MediaStore.Images.Media.getBitmap(contentResolver, imageUri);
        } catch(Exception e) {
            Toast.makeText(TakePhotoActivity.this, "failed to load", Toast.LENGTH_LONG).show();
            Log.e(LOG_TAG, e.toString());
        }
    }
}

this is how i am adding the row to the database:

public void onClick_AddRecord(View v) {
    long newId = myDb.insertRow("User", "00/00/0000",
            "image description", imageUri);
    populateListViewFromDB();
}

now the issue-- if i create an activity to view all the information stored in a row, how do i access the image and assign it to an ImageView?


Solution

  • Please check if it helps:

    1. Write a method which will return all rows from the images table into a cursor.
    2. Create a Cursor adapter and bind it to the list view.
    3. Use ImageView.setImageURI() to bind image URI with imageView.