Search code examples
androidcameraandroid-contentresolver

Latest Change not in ContentObserver


When my ContentObserver is called because of a freshly taken photo, that freshest photo is nowhere to be found in a query.

I am registering my ContentObserver like this:

        getContentResolver()
                .registerContentObserver(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        false,
                        imageObserver
                );

Yet, the following callback can only query for the last image before that, not the newly taken image itself:

@Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);

            Cursor cursor = getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null, "date_added DESC");
            String filePath = null;
            if(cursor.moveToFirst()){
                filePath = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
            }
            cursor.close();
        }

What can i do to retrieve the real latest picture in the callback?


Solution

  • I figured it out:

    the second parameter has to be true:

    getContentResolver()
                    .registerContentObserver(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            true,
                            imageObserver
                    );
    

    That allows you to do the following:

    cursor = getContentResolver().query(uri, null, null, null, null);
    

    Just don't forget to keep track of what ID you have already processed, since one photo may trigger multiple events...