从前置摄像头捕获图片时的java.lang.IllegalStateException - Android

时间:2014-08-14 09:56:41

标签: android

我的应用程序因消息而崩溃 java.lang.IllegalStateException: Could not execute method of the activity E/AndroidRuntime(6043):at android.view.View$1.onClick(View.java:3823)

这是我的 CameraController类

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.PictureCallback;
import android.os.Environment;
import android.util.Log;
import android.view.SurfaceView;


    public class CameraController {

        private Context context;

        private boolean hasCamera;

        private Camera camera;
        private int cameraId;

        public CameraController(Context c){
            context = c;

            if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
                cameraId = getFrontCameraId();

                if(cameraId != -1){
                    hasCamera = true;
                }else{
                    hasCamera = false;
                }
            }else{
                hasCamera = false;
            }
        }

        public boolean hasCamera(){
            return hasCamera;
        }

        public void getCameraInstance(){
            camera = null;

            if(hasCamera){
                try{
                    camera = Camera.open(cameraId);
                    prepareCamera();
                }
                catch(Exception e){
                    hasCamera = false;
                }
            }
        }

        public void takePicture(){
            if(hasCamera){
                camera.takePicture(null,null,mPicture);
            }
        }

        public void releaseCamera(){
            if(camera != null){
                camera.stopPreview();
                camera.release();
                camera = null;
            }
        }

        private int getFrontCameraId(){
            int camId = -1;
            int numberOfCameras = Camera.getNumberOfCameras();
            CameraInfo ci = new CameraInfo();

            for(int i = 0;i < numberOfCameras;i++){
                Camera.getCameraInfo(i,ci);
                if(ci.facing == CameraInfo.CAMERA_FACING_FRONT){
                    camId = i;
                }
            }

            return camId;
        }

        private void prepareCamera(){
            SurfaceView view = new SurfaceView(context);

            try{
                camera.setPreviewDisplay(view.getHolder());
            }catch(IOException e){
                throw new RuntimeException(e);
            }

            camera.startPreview();

            Camera.Parameters params = camera.getParameters();
            params.setJpegQuality(100);

            camera.setParameters(params);  
        }

        private PictureCallback mPicture = new PictureCallback(){
            @Override
            public void onPictureTaken(byte[] data, Camera camera){
                File pictureFile = getOutputMediaFile();

                if(pictureFile == null){
                    Log.d("TEST", "Error creating media file, check storage permissions");
                    return;
                }

                try{
                    Log.d("TEST","File created");
                    FileOutputStream fos = new FileOutputStream(pictureFile);
                    fos.write(data);
                    fos.close();
                }catch(FileNotFoundException e){
                    Log.d("TEST","File not found: "+e.getMessage());
                } catch (IOException e){
                    Log.d("TEST","Error accessing file: "+e.getMessage());
                }
            }
        };

        private File getOutputMediaFile(){
            // To be safe, you should check that the SDCard is mounted
            // using Environment.getExternalStorageState() before doing this.

            File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),"MyCameraApp");

            // 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()){
                    return null;
                }
            }

            // Create a media file name
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

            File mediaFile;
            mediaFile = new   File(mediaStorageDir.getPath()+File.separator+"IMG_"+timeStamp+".jpg");

            return mediaFile;
        }
    }

MainActivity

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void Onclick(View view)
    {

        CameraController click = new CameraController(MainActivity.this);
        click.takePicture();


    }

}

main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.cameraapi.postcamera.MainActivity" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="35dp"
        android:onClick="Onclick" 
        android:text="Make Photo"/>

</RelativeLayout>

LogCat

08-14 12:10:15.813: E/AndroidRuntime(7432): FATAL EXCEPTION: main
08-14 12:10:15.813: E/AndroidRuntime(7432): Process: com.cameraapi.postcamera, PID: 7432
08-14 12:10:15.813: E/AndroidRuntime(7432): java.lang.IllegalStateException: Could not execute method of the activity
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.view.View$1.onClick(View.java:3823)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.view.View.performClick(View.java:4438)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.view.View$PerformClick.run(View.java:18422)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.os.Handler.handleCallback(Handler.java:733)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.os.Handler.dispatchMessage(Handler.java:95)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.os.Looper.loop(Looper.java:136)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.app.ActivityThread.main(ActivityThread.java:5034)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at java.lang.reflect.Method.invoke(Method.java:515)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at dalvik.system.NativeStart.main(Native Method)
08-14 12:10:15.813: E/AndroidRuntime(7432): Caused by: java.lang.reflect.InvocationTargetException
08-14 12:10:15.813: E/AndroidRuntime(7432):     at java.lang.reflect.Method.invokeNative(Native Method)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at java.lang.reflect.Method.invoke(Method.java:515)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at android.view.View$1.onClick(View.java:3818)
08-14 12:10:15.813: E/AndroidRuntime(7432):     ... 11 more
08-14 12:10:15.813: E/AndroidRuntime(7432): Caused by: java.lang.NullPointerException
08-14 12:10:15.813: E/AndroidRuntime(7432):     at com.cameraapi.postcamera.CameraController.takePicture(CameraController.java:64)
08-14 12:10:15.813: E/AndroidRuntime(7432):     at com.cameraapi.postcamera.MainActivity.Onclick(MainActivity.java:41)
08-14 12:10:15.813: E/AndroidRuntime(7432):     ... 14 more

一切看起来都很好但仍然发生崩溃而无法弄明白为什么? 任何人都可以帮助我解决这个问题。

1 个答案:

答案 0 :(得分:0)

takePicture()中的NPE。您的camera为空。您尚未调用方法getCameraInstance(),而是在camera对象上CameraController初始化takePicture()