-2

I am trying to follow along with Google Documentation to take a picture with the camera. It works fine and stores the image in the appropriate folder. However once the picture is taken, two option Appear in the camera: Retry and Ok. When I click OK the app crashes. The error is commented below. Has anyone any ideas. Thanks

package com.example.tauheed.cameraapplication;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.EventLogTags;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity {
    static final int REQUEST_IMAGE_CAPTURE = 1;
    private static final String LOGTAG = "MainActivity"; //Use this to Filter Out Log Details
    Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn1 =  findViewById(R.id.myButton);
    }
    //Start Camera from Button TO Intent
    public void StartCamera(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        Log.i(LOGTAG, "test output");
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
    //Show Camera image in Image View //onActivityResult returns a result from activity
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode,resultCode,data);

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            //Crash App Here when I press ok
            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");

            ImageView mImageView;
            mImageView = (ImageView) findViewById(R.id.imgV);
            mImageView.setImageBitmap(imageBitmap);
        }
    }
    //C:\Users\tauheed\AndroidStudioProjects\CameraApplication\app\src\main\java\com\example\tauheed\cameraapplication
    //Path to store Picture
    String mCurrentPhotoPath;

   //Create file to hold the picture named JPEG PLUS THE TIME STAMP OF PHOTO
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);

        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    //Send the picture back through the intent
    static final int REQUEST_TAKE_PHOTO = 1;

    public void dispatchTakePictureIntent(View view) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
                ex.printStackTrace();
                Toast.makeText(this,"Error",Toast.LENGTH_SHORT).show();
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                Log.i(LOGTAG, "photo uri: "+photoURI);
                Log.i(LOGTAG, "photo file: "+photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    private void galleryAddPic() {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

    private void setPic() {
        // Get the dimensions of the View
        ImageView mImageView;
        mImageView = (ImageView) findViewById(R.id.imgV);
        int targetW = mImageView.getWidth();
        int targetH = mImageView.getHeight();

        // Get the dimensions of the bitmap
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        bmOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        int photoW = bmOptions.outWidth;
        int photoH = bmOptions.outHeight;

        // Determine how much to scale down the image
        int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

        // Decode the image file into a Bitmap sized to fill the View
        bmOptions.inJustDecodeBounds = false;
        bmOptions.inSampleSize = scaleFactor;
        bmOptions.inPurgeable = true;

        Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
        mImageView.setImageBitmap(bitmap);
    }
  }
}

Log information:

05/02 10:06:28: Launching app
$ adb install-multiple -r -t -p com.example.tauheed.cameraapplication C:\Users\tauheed\AndroidStudioProjects\CameraApplication\app\build\intermediates\split-apk\debug\slices\slice_4.apk C:\Users\tauheed\AndroidStudioProjects\CameraApplication\app\build\intermediates\instant-run-apk\debug\app-debug.apk 
Split APKs installed
$ adb shell am start -n "com.example.tauheed.cameraapplication/com.example.tauheed.cameraapplication.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER -D
Waiting for application to come online: com.example.tauheed.cameraapplication | com.example.tauheed.cameraapplication.test
Waiting for application to come online: com.example.tauheed.cameraapplication | com.example.tauheed.cameraapplication.test
Waiting for application to come online: com.example.tauheed.cameraapplication | com.example.tauheed.cameraapplication.test
Waiting for application to come online: com.example.tauheed.cameraapplication | com.example.tauheed.cameraapplication.test
Connecting to com.example.tauheed.cameraapplication
Connected to the target VM, address: 'localhost:8604', transport: 'socket'
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/art: Debugger is active
I/System.out: Debugger has connected
              waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: waiting for debugger to settle...
I/System.out: debugger has settled (1479)
W/System: ClassLoader referenced unknown path: /data/app/com.example.tauheed.cameraapplication-1/lib/arm64
I/InstantRun: starting instant run server: is main process
W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
D/TextView: setTypeface with style : 0
D/TextView: setTypeface with style : 0
D/TextView: setTypeface with style : 0
D/ViewRootImpl@648e444[MainActivity]: ThreadedRenderer.create() translucent=false
D/InputTransport: Input channel constructed: fd=70
D/ViewRootImpl@648e444[MainActivity]: setView = DecorView@c1a9e62[MainActivity] touchMode=true
D/ViewRootImpl@648e444[MainActivity]: dispatchAttachedToWindow
D/ViewRootImpl@648e444[MainActivity]: Relayout returned: oldFrame=[0,0][0,0] newFrame=[0,0][1440,2560] result=0x27 surface={isValid=true 523090896384} surfaceGenerationChanged=true
D/ViewRootImpl@648e444[MainActivity]: mHardwareRenderer.initialize() mSurface={isValid=true 523090896384} hwInitialized=true
D/libEGL: loaded /vendor/lib64/egl/libGLES_mali.so
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
D/mali_winsys: EGLint new_window_surface(egl_winsys_display*, void*, EGLSurface, EGLConfig, egl_winsys_surface**, egl_color_buffer_format*, EGLBoolean) returns 0x3000,  [1440x2560]-format:1
W/art: Before Android 4.1, method int android.support.v7.widget.DropDownListView.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
D/ViewRootImpl@648e444[MainActivity]: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
                                      MSG_WINDOW_FOCUS_CHANGED 1
D/ViewRootImpl@648e444[MainActivity]: mHardwareRenderer.initializeIfNeeded()#2 mSurface={isValid=true 523090896384}
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@355b62f nm : com.example.tauheed.cameraapplication ic=null
I/InputMethodManager: [IMM] startInputInner - mService.startInputOrWindowGainedFocus
D/InputTransport: Input channel constructed: fd=81
V/InputMethodManager: Starting input: tba=android.view.inputmethod.EditorInfo@5b143c nm : com.example.tauheed.cameraapplication ic=null
D/ViewRootImpl@648e444[MainActivity]: ViewPostImeInputStage processPointer 0
W/System: ClassLoader referenced unknown path: /system/framework/QPerformance.jar
E/BoostFramework: BoostFramework() : Exception_1 = java.lang.ClassNotFoundException: Didn't find class "com.qualcomm.qti.Performance" on path: DexPathList[[],nativeLibraryDirectories=[/system/lib64, /vendor/lib64]]
V/BoostFramework: BoostFramework() : mPerf = null
D/ViewRootImpl@648e444[MainActivity]: ViewPostImeInputStage processPointer 1
I/MainActivity: photo uri: content://com.example.android.fileprovider/test_folder/JPEG_20180502_100721_1084476579.jpg
I/MainActivity: photo file: /storage/emulated/0/Android/data/com.example.tauheed.cameraapplication/files/Pictures/JPEG_20180502_100721_1084476579.jpg
D/ViewRootImpl@648e444[MainActivity]: MSG_WINDOW_FOCUS_CHANGED 0
D/OpenGLRenderer: endAllActiveAnimators on 0x79b998c400 (RippleDrawable) with handle 0x79a843a180
D/ViewRootImpl@648e444[MainActivity]: mHardwareRenderer.destroy()#1
D/ViewRootImpl@648e444[MainActivity]: Relayout returned: oldFrame=[0,0][1440,2560] newFrame=[0,0][1440,2560] result=0x5 surface={isValid=false 0} surfaceGenerationChanged=true
D/InputTransport: Input channel destroyed: fd=81
D/ViewRootImpl@648e444[MainActivity]: mHardwareRenderer.destroy()#1
D/ViewRootImpl@648e444[MainActivity]: Relayout returned: oldFrame=[0,0][1440,2560] newFrame=[0,0][1440,2560] result=0x1 surface={isValid=false 0} surfaceGenerationChanged=false
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.tauheed.cameraapplication, PID: 5507
                  java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.tauheed.cameraapplication/com.example.tauheed.cameraapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4472)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
                      at android.app.ActivityThread.-wrap22(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6682)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                      at com.example.tauheed.cameraapplication.MainActivity.onActivityResult(MainActivity.java:47)
                      at android.app.Activity.dispatchActivityResult(Activity.java:7256)
                      at android.app.ActivityThread.deliverResults(ActivityThread.java:4468)
                      at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515) 
                      at android.app.ActivityThread.-wrap22(ActivityThread.java) 
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) 
                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                      at android.os.Looper.loop(Looper.java:154) 
                      at android.app.ActivityThread.main(ActivityThread.java:6682) 
                      at java.lang.reflect.Method.invoke(Native Method) 
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
Disconnected from the target VM, address: 'localhost:8604', transport: 'socket'
GhostCat
  • 137,827
  • 25
  • 176
  • 248
shellac85
  • 15
  • 8

1 Answers1

0
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.tauheed.cameraapplication, PID: 5507

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.tauheed.cameraapplication/com.example.tauheed.cameraapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method

'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                          at android.app.ActivityThread.deliverResults(ActivityThread.java:4472)
                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
                          at android.app.ActivityThread.-wrap22(ActivityThread.java)
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
                          at android.os.Handler.dispatchMessage(Handler.java:102)
                          at android.os.Looper.loop(Looper.java:154)
                          at android.app.ActivityThread.main(ActivityThread.java:6682)
                          at java.lang.reflect.Method.invoke(Native Method)
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
                       Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
                          at com.example.tauheed.cameraapplication.MainActivity.onActivityResult(MainActivity.java:47)
                          at android.app.Activity.dispatchActivityResult(Activity.java:7256)
                          at android.app.ActivityThread.deliverResults(ActivityThread.java:4468)
                          at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515) 
                          at android.app.ActivityThread.-wrap22(ActivityThread.java) 
                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687) 
                          at android.os.Handler.dispatchMessage(Handler.java:102) 
                          at android.os.Looper.loop(Looper.java:154) 
                          at android.app.ActivityThread.main(ActivityThread.java:6682) 
                          at java.lang.reflect.Method.invoke(Native Method) 
                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520) 
                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410) 
    Disconnected from the target VM, address: 'localhost:8604', transport: 'socket'

Check really good what are you sending since your data object in protected void onActivityResult(int requestCode, int resultCode, Intent data) is null. From there is the problem starting.

So when you call the startActivityForResult() keep in mind that you need to pass also the Intent in your case that will be: takePictureIntent. You need to end up with something like: startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO,takePictureIntent);inside of your public void dispatchTakePictureIntent(View view){} method in order to pass the Intent as well.

Hope that helps :)