0

So I get a null pointer exception when trying to recieve image from SQLite database.

Saving image:

    public void insertImage(byte[] imageBytes) {
        ContentValues cv = new ContentValues();
        cv.put(IMAGE, imageBytes);
        mDb.insert(IMAGES_TABLE, null, cv);
    }

Here's my code for recieving the image in the helper class:

    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;
    }

And here's how I try to set the image to ImageView in my activity:

    byte[] image = mImage.retreiveImageFromDB();
    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
    profileImage.setImageBitmap(bitmap);

What am I doing wrong?

MikeT
  • 51,415
  • 16
  • 49
  • 68
DaxHR
  • 683
  • 1
  • 11
  • 30

1 Answers1

0

What am I doing wrong?

You are likely not checking for null being returned from the retreiveImageFromDB method.

Instead of :-

    byte[] image = mImage.retreiveImageFromDB();
    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
    profileImage.setImageBitmap(bitmap);

You should have something along the lines of :-

    byte[] image = mImage.retreiveImageFromDB();
    if (image != null) {
        Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
        profileImage.setImageBitmap(bitmap);
    } else {
        // Hanlde null here e.g.
        Toast.makeText(this,"Ooops image is null!!!",Toast.LENGTH_SHORT).show();
    }

You may then ask Why is the Cursor empty!

As the query should return at least 1 row if any exist (i.e the restrictions are only uniqueness of the images (blobs) and the number of rows being returned as 1) then there is a likelihood that you may have issues beyond the scope of what is ascertainable from the code given.

You could perhaps change the insertImage method to return the ID of the inserted row, and check this whenever the method is called e.g.

public long insertImage(byte[] imageBytes) { // <<<< changed signature
    ContentValues cv = new ContentValues();
    cv.put(IMAGE, imageBytes);
    return mDb.insert(IMAGES_TABLE, null, cv); // added return
}

Then use something like :-

    if (insertImage(your_image) > 0) {
        Log.d("IMAGEINSERT","Image inserted OK.");
    } else {
        Log.d("IMAGEINSERT","Image was not inserted!!!");
    }

Instead of

    insertImage(your_image);

You could perhaps utilise the utilities provided at this link, these will allow you to inspect the database and tables.

Community
  • 1
  • 1
MikeT
  • 51,415
  • 16
  • 49
  • 68