android - 当我在不同的设备中尝试时,应用程序内的相机强制关闭数据为空

标签 android android-intent nullpointerexception android-camera android-sdcard

我有一个 apk 应用程序,可以通过按钮拍照和拍摄视频。

这是我的 Activity

package com.example.testcamera;

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

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;

public class AndroidCameraTestsActivity extends Activity 
{
    private static final String TAG = AndroidCameraTestsActivity.class.getSimpleName(); 

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private static final int CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE = 200;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;

    private Uri fileUri;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    /** 
     * https://developer.android.com/guide/topics/media/camera.html 
     * **/
    public void onCaptureImage(View v) 
    {
        // give the image a name so we can store it in the phone's default location
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.TITLE, "IMG_" + timeStamp + ".jpg");

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

        //fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to save the image (this doesn't work at all for images)
        fileUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); // store content values
        intent.putExtra( MediaStore.EXTRA_OUTPUT,  fileUri);

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

    /** 
     * https://developer.android.com/guide/topics/media/camera.html 
     * **/
    public void onCaptureVideo(View v) 
    {
         //create new Intent
        Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

        //fileUri = getOutputMediaFileUri(MEDIA_TYPE_VIDEO);  // create a file to save the video in specific folder (this works for video only)
        //intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);  // set the image file name

        intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high

        // start the Video Capture Intent
        startActivityForResult(intent, CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) 
    {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Originally I was going to iterate through the list of images and grab last added to the MediaStore.
                // But this is not necessary if we store the Uri in the image
                /*
                String[] projection = {MediaStore.Images.ImageColumns._ID};
                String sort = MediaStore.Images.ImageColumns._ID + " DESC";

                Cursor cursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null, sort);

                try{
                    cursor.moveToFirst();
                    Long id = cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns._ID));
                    fileUri = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, String.valueOf(id));
                } finally{
                    cursor.close();
                }
                */

                if(fileUri != null) {
                    Log.d(TAG, "Image saved to:\n" + fileUri);
                    Log.d(TAG, "Image path:\n" + fileUri.getPath());
                    Log.d(TAG, "Image name:\n" + getName(fileUri)); // use uri.getLastPathSegment() if store in folder
                }

            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the image capture
            } else {
                // Image capture failed, advise user
            }
        }

        if (requestCode == CAPTURE_VIDEO_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {

                // Video captured and saved to fileUri specified in the Intent
                fileUri = (Uri) data.getData();

                if(fileUri != null) {
                    Log.d(TAG, "Video saved to:\n" + fileUri);
                    Log.d(TAG, "Video path:\n" + fileUri.getPath());
                    Log.d(TAG, "Video name:\n" + getName(fileUri)); // use uri.getLastPathSegment() if store in folder
                }

            } else if (resultCode == RESULT_CANCELED) {
                // User cancelled the video capture
            } else {
                // Video capture failed, advise user
            }
        }
    }

    /** Create a file Uri for saving an image or video to specific folder
     * https://developer.android.com/guide/topics/media/camera.html#saving-media
     * */
    private static Uri getOutputMediaFileUri(int type)
    {
          return Uri.fromFile(getOutputMediaFile(type));
    }

    /** Create a File for saving an image or video */
    private static File getOutputMediaFile(int type)
    {
        // To be safe, you should check that the SDCard is mounted

        if(Environment.getExternalStorageState() != null) {
            // this works for Android 2.2 and above
            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "AndroidCameraTestsFolder");

            // This location works best if you want the created images to be shared
            // between applications and persist after your app has been uninstalled.

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

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

            return mediaFile;
        }

        return null;
    }

    // grab the name of the media from the Uri
    protected String getName(Uri uri) 
    {
        String filename = null;

        try {
            String[] projection = { MediaStore.Images.Media.DISPLAY_NAME };
            Cursor cursor = managedQuery(uri, projection, null, null, null);

            if(cursor != null && cursor.moveToFirst()){
                int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
                filename = cursor.getString(column_index);
            } else {
                filename = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Error getting file name: " + e.getMessage());
        }

        return filename;
    }
}

我有第一台设备运行该应用程序,并且有 2 个按钮,拍照拍摄视频

当我在此应用程序中单击拍摄视频时,它运行良好,但当我从按钮中单击拍摄照片时,该应用程序总是“强制关闭”。

这是我的错误日志

11-19 14:43:27.085: ERROR/AndroidRuntime(6903): FATAL EXCEPTION: main
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): java.lang.NullPointerException
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera.initializeFirstTime(Came ra.java:328)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera.access$1100(Camera.java: 95)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.camera.Camera$MainHandler.handleMessag e(Camera.java:282)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.os.Handler.dispatchMessage(Handler.java:99 )
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.os.Looper.loop(Looper.java:130)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at android.app.ActivityThread.main(ActivityThread.jav a:3683)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at java.lang.reflect.Method.invokeNative(Native Method)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at java.lang.reflect.Method.invoke(Method.java:507)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.internal.os.ZygoteInit$MethodAndArgsCa ller.run(ZygoteInit.java:839)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:597)
11-19 14:43:27.085: ERROR/AndroidRuntime(6903): at dalvik.system.NativeStart.main(Native Method)
11-19 14:43:27.093: WARN/ActivityManager(1308): Force finishing activity com.android.camera/.Camera
11-19 14:43:27.109: WARN/ActivityManager(1308): Force finishing activity makemachine.android.examples/.PhotoCaptureExample

logcat capture

编辑:这是我使用单个应用程序按钮的不同 Activity

package com.example.maincamera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class OpenCameraDemo extends Activity {

    private static final int CAMERA_PIC_REQUEST = 2500;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button b = (Button)findViewById(R.id.Button01);
        b.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                 Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                 startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
            }
        });
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_PIC_REQUEST) {
              Bitmap image = (Bitmap) data.getExtras().get("data");
              ImageView imageview = (ImageView) findViewById(R.id.ImageView01);
              imageview.setImageBitmap(image);
        }
    }
}

这个应用程序仍然错误,我已经尝试了很多应用程序。在 google 中搜索。错误仍然与我的 logcat 错误相同

当我尝试在其他设备上运行它时,这个应用程序运行良好。

如何解决这个问题,以便我可以在我的第一台设备上运行并拍照?

BR。

亚历克斯

最佳答案

崩溃发生在设备的相机应用程序内部,而不是您自己的应用程序。不幸的是,由于该设备上的相机应用程序可能是 AOSP 中实际应用程序的高度定制变体,因此尚不完全清楚故障是什么,但 here is a link to the source file在发生异常的 AOSP 2.3.7 源代码树中。行号与任何感兴趣的内容都不完全匹配,这告诉我您的特定设备上的应用程序至少已经过一些自定义。

initializeFirstTime() 方法中发生异常、调用方法的任何对象都可能是问题的根源,但这些都与 Intent 您的请求传入的参数,因此您可以采取很多措施来使其正常运行,这是值得怀疑的。

因此,您可能会更幸运地在自己的应用程序中自行实现捕获功能。该设备上的 Android API 可能比其 bundle 的系统应用程序更稳定。 Here is an example了解如何创建自己的相机预览和捕获 Activity 。

关于android - 当我在不同的设备中尝试时,应用程序内的相机强制关闭数据为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505662/

相关文章:

android - 从位图中获取图像并将其放入字符串中

java - 什么是NullPointerException,我该如何解决?

android - 生成失败,并显示以下错误:错误:任务执行失败

android - 避免Android中图库保存相机拍摄的照片

android - 在 Android 上使用 Chrome 打开 android-app 方案

java - Android SDK public void 获取错误

java ftp 空指针异常

Java ConcurrentHashMap 不是线程安全的..wth?

android - Xamarin.窗体 : Apk size is too large

android - Sinch SDK - 不接收旧消息