相机崩溃[重复]

Posted

技术标签:

【中文标题】相机崩溃[重复]【英文标题】:Camera Crashing [duplicate] 【发布时间】:2018-10-12 15:10:54 【问题描述】:

我正在尝试按照 Google 文档使用相机拍照。它工作正常并将图像存储在适当的文件夹中。但是,一旦拍摄照片,相机中会出现两个选项:重试和确定。当我单击确定时,应用程序崩溃。错误在下面注释。有没有人有任何想法。谢谢

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

日志信息:

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 ResultInfowho=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'

【问题讨论】:

Android Camera Crashing你需要分享问题Crash-Log 添加摄像头访问权限***.com/a/43760891/4336740 Android Studio 中的崩溃日志在哪里? 【参考方案1】:
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.tauheed.cameraapplication, PID: 5507

java.lang.RuntimeException: 传递结果失败 ResultInfowho=null, request=1, result=-1, data=null 到活动 com.example.tauheed.cameraapplication/com.example.tauheed.cameraapplication.MainActivity: java.lang.NullPointerException: 尝试调用虚方法

'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'

因为protected void onActivityResult(int requestCode, int resultCode, Intent data) 中的data 对象为空,所以检查您发送的内容非常好。从那里开始有问题。

因此,当您调用 startActivityForResult() 时,请记住,您还需要传递 Intent,在您的情况下为:takePictureIntent。您最终需要得到类似:startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO,takePictureIntent);inside 的 public void dispatchTakePictureIntent(View view) 方法,以便也传递 Intent

希望对你有帮助:)

【讨论】:

非常感谢您的回答。我将有问题的代码放在 try/catch 中,现在它按预期工作。谢谢! 不客气!如果你愿意,你可以接受正确的答案作为贡献:) 完成,再次感谢 :)

以上是关于相机崩溃[重复]的主要内容,如果未能解决你的问题,请参考以下文章

拍照使应用程序崩溃[重复]

相机随机崩溃

检索照片时相机崩溃

为自定义相机转动闪光灯时前置相机崩溃?

ios10相机等崩溃-b

相机崩溃时的返回按钮