Search code examples
javaandroidbitmapjpeg

Loading a JPEG image in Lollipop (5.1.1)


I would like to load a JPEG image as a Bitmap object on an Android App. I am using Android 5.1.1 API 22. I am currently using the following code to load the bitmap, where jpg is the file of the image that I have previously taken:

File root = Environment.getExternalStorageDirectory();
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = 1;
Bitmap bMap = BitmapFactory.decodeFile(jpg.getAbsolutePath(),bmOptions);

And I am attempting to perform image processing on the Bitmap extracted above:

int width = bMap.getWidth();
int height = bMap.getHeight();

I have the following permissions set in my manifest file:

<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE"
    android:maxSdkVersion="18" />

In the logcat I get the following output:

java.lang.IllegalStateException: Could not execute method for android:onClick
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:389)
    at android.view.View.performClick(View.java:5254)
    at android.view.View$PerformClick.run(View.java:21173)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:145)
    at android.app.ActivityThread.main(ActivityThread.java:6838)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
 Caused by: java.lang.reflect.InvocationTargetException
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:384)
    at android.view.View.performClick(View.java:5254) 
    at android.view.View$PerformClick.run(View.java:21173) 
    at android.os.Handler.handleCallback(Handler.java:739) 
    at android.os.Handler.dispatchMessage(Handler.java:95) 
    at android.os.Looper.loop(Looper.java:145) 
    at android.app.ActivityThread.main(ActivityThread.java:6838) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at java.lang.reflect.Method.invoke(Method.java:372) 
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.graphics.Bitmap.getWidth()' on a null object reference

So essentially it's saying that the Bitmap is null (last line in the logcat).

Has anyone else had this problem on android 5.1.1; API 22? Or does anybody have a different way of doing this? Any help would be appreciated! Thanks :)


Solution

  • If you are selecting bitmap image from gallery, It is possible that the path you are getting is not proper. Add a new XML file called file_paths.xml

    <?xml version="1.0" encoding="utf-8"?>
    <paths xmlns:android="http://schemas.android.com/apk/res/android">
     <external-path name="my_images"
        path="." />
    </paths>
    

    add this inside tag in AndroidManifest

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="${applicationId}.provider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths">
            </meta-data>
        </provider>
    

    And this in Activity:

    public String getPathFromURI(Uri contentUri) {
        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
                String res = "";
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
                if (cursor.moveToFirst()) {
                    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                    res = cursor.getString(column_index);
                }
                cursor.close();
                return res;
            } else {
                String res = "";
                String wholeID = null;
                wholeID = DocumentsContract.getDocumentId(contentUri);
                String id = wholeID.split(":")[1];
    
                String[] column = {MediaStore.Images.Media.DATA};
                String sel = MediaStore.Images.Media._ID + "=?";
    
                Cursor cursor = getActivity().getContentResolver().
                        query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                                column, sel, new String[]{id}, null);
    
                int columnIndex = cursor.getColumnIndex(column[0]);
    
                if (cursor.moveToFirst()) {
                    res = cursor.getString(columnIndex);
                }
                cursor.close();
                return res;
            }
        } catch (Exception e) {
            Cursor cursor = null;
            try {
                String[] proj = {MediaStore.Images.Media.DATA};
                cursor = getContext().getContentResolver().query(contentUri, proj, null, null, null);
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } catch (Exception ex) {
                return null;
            } finally {
                if (cursor != null) {
                    cursor.close();
                }
            }
        }
    }