Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Null pointer Exception on file- URI?

In my app a capture button is there to capture an image using device camera,so I have used a method captureImage() on the click event of that button.When I click the button a null pointer exception is thrown.I could not understand how this happens Can anyone help? Thanks in advance!

capture button on on Create () method

photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            /*
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);*/
            captureImage();
        }
    });

captureImage() method

private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_REQUEST);
}

Null pointer exception on this method

  public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

/**
 * returning image / video
 */
private static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.d(TAG, "Oops! Failed create "
                    + Config.IMAGE_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Create a media file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");
    } else {
        return null;
    }

    return mediaFile;
}

Logcat

 java.lang.NullPointerException: file
        at android.net.Uri.fromFile(Uri.java:447)
        at com.riafy.user.imagegallerydemo.MainActivity.getOutputMediaFileUri(MainActivity.java:235)
        at com.riafy.user.imagegallerydemo.MainActivity.captureImage(MainActivity.java:97)
        at com.riafy.user.imagegallerydemo.MainActivity.access$100(MainActivity.java:29)
        at com.riafy.user.imagegallerydemo.MainActivity$2.onClick(MainActivity.java:68)
        at android.view.View.performClick(View.java:4761)
        at android.view.View$PerformClick.run(View.java:19767)
        at android.os.Handler.handleCallback(Handler.java:739)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        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:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
like image 444
Jack Avatar asked Jul 10 '15 06:07

Jack


People also ask

How do I fix null pointer exceptions?

In Java, the java. lang. NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.

What causes a NullPointerException?

What Causes NullPointerException. The NullPointerException occurs due to a situation in application code where an uninitialized object is attempted to be accessed or modified. Essentially, this means the object reference does not point anywhere and has a null value.

Can NullPointerException be caught?

Programmers typically catch NullPointerException under three circumstances: The program contains a null pointer dereference. Catching the resulting exception was easier than fixing the underlying problem. The program explicitly throws a NullPointerException to signal an error condition.

What is a NullPointerException error?

NullPointerException is a RuntimeException . In Java, a special null value can be assigned to an object reference. NullPointerException is thrown when an application attempts to use an object reference that has the null value. These include: Calling an instance method on the object referred by a null reference.


3 Answers

getOutputMediaFile(type) returns null.

 public Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
}

You are returning here:

// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
    if (!mediaStorageDir.mkdirs()) {
        Log.d(TAG, "Oops! Failed create "
                + Config.IMAGE_DIRECTORY_NAME + " directory");
        return null;
    }
}

Have you added the following permission

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

to your manifest?

like image 117
barq Avatar answered Oct 13 '22 02:10

barq


My solution was simple.

Realised the error. Android Manifest had put a maxSDKVersion to 18 on the permission to write to storage. After removing that, it was working perfectly.

like image 26
Houston Austin Avatar answered Oct 13 '22 01:10

Houston Austin


File mediaStorageDir = new File(
            Environment
                  .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            Config.IMAGE_DIRECTORY_NAME);

I directly copied to code from Android getting started page. My problem was I was running it on emulator. Therefore I think the code above that I used could not assess my file system.

like image 34
Steven Wong Avatar answered Oct 13 '22 03:10

Steven Wong