0

在我使用单个按钮的主要活动中,单击以下活动启动以使用 android 中的默认相机应用程序拍摄图像,然后录制声音。

但是,每当我单击主要活动中的按钮时,我都会收到此错误:

java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.naviiid.soundshot/com.naviiid.soundshot.MicroFilm}:
java.lang.NullPointerException

相机应用程序启动有一点,但在此之前我的应用程序已经停止!这是代码(对不起,代码有点长):

package com.naviiid.soundshot;

import java.io.File
import java.util.Calendar;
import android.R.drawable;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.Toast;

public class MicroFilm extends Activity {

    private static final int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;
    private Uri imageUri;
    public static final int MEDIA_TYPE_IMAGE = 1;
    public static final int MEDIA_TYPE_VIDEO = 2;
    private static File mediaStorageDir;
    private ImageView image;
    private ImageView record;
    private ImageView save;
    private ImageView capture;
    private boolean visibleButtons = true;
    private MediaRecorder soundRecorder;
    private String mediaFilePath;
    private static Calendar cal;
    boolean recording = false;

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

        String mediaState = Environment.getExternalStorageState();
        if (!mediaState.equals(Environment.MEDIA_MOUNTED)){
            Toast.makeText(MicroFilm.this, "Media unmounted! \n Mount media firts..", Toast.LENGTH_LONG).show();
            Log.d("StorageState", "Media Unmounted");
            finish();
        }

        mediaStorageDir = new File(Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM)
                .getAbsolutePath()
                + "/MicroFilm");

        takePicture(); // this method will capture image from camera intent and
                        // returns to main activity if user cancels

        // View things
        image = (ImageView) findViewById(R.id.imageViewPicture);
        record = (ImageView) findViewById(R.id.imageViewMic);
        save = (ImageView) findViewById(R.id.imageViewSave);
        capture = (ImageView) findViewById(R.id.imageViewCapture);

        setBackgroundImage(); // shows taken picture
        captureSound(); // prepares for recording, recording starts with imageButton click

    }

    private void captureSound() {
        // prepare things to record
        soundRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        soundRecorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        soundRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        File soundFile = getNewSoundFile();
        soundRecorder.setOutputFile(soundFile.getAbsolutePath());
        try{
            soundRecorder.prepare();
        }catch (Exception e) {
            Log.d("SoundRecorder", "unable to prepare");
            Toast.makeText(MicroFilm.this, "Mic in use", Toast.LENGTH_SHORT).show();
            return;
        }

        //listeners
        soundRecorderListeners();

    }

    private void soundRecorderListeners() {

        record.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (recording){
                    soundRecorder.stop();
                    soundRecorder.release();
                    recording = false;
                    record.setBackgroundResource(drawable.ic_btn_speak_now);
                }else{
                    soundRecorder.start();
                    recording = true;
                    record.setBackgroundResource(drawable.presence_audio_busy);
                }
            }
        });
    }

    private File getNewSoundFile() {
        // Create a media file name
        String timeStamp;
        cal = Calendar.getInstance();
        timeStamp = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + 1
                + cal.get(Calendar.DAY_OF_MONTH) + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE)
                + cal.get(Calendar.SECOND);
        mediaFilePath = mediaStorageDir.getAbsolutePath() + "/AUD_" + timeStamp
                + ".amr";
        return new File(mediaFilePath);
    }

    private void setBackgroundImage() {
        // shows taken picture in background
        image.setImageDrawable(Drawable.createFromPath(imageUri.getPath()));
        image.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (visibleButtons) {
                    record.setVisibility(View.INVISIBLE);
                    save.setVisibility(View.INVISIBLE);
                    capture.setVisibility(View.INVISIBLE);
                    visibleButtons = false;
                } else {
                    record.setVisibility(View.VISIBLE);
                    save.setVisibility(View.VISIBLE);
                    capture.setVisibility(View.VISIBLE);
                    visibleButtons = true;
                }
            }
        });
    }

    private void takePicture() {
        Intent camera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        imageUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE); // create a file to
        // save the image
        camera.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); // set the image file
        // name

        // start the image captugetOutputMediaFileUrire Intent
        startActivityForResult(camera, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);

    }

    /** Create a file Uri for saving an image or video */
    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
        // using Environment.getExternalStorageState() before doing this.


        // 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()) {
                Log.d("MicroFilm", "failed to create directory");
                return null;
            }
        }

        // Create a media file name
        String timeStamp;
        cal = Calendar.getInstance();
        timeStamp = "" + cal.get(Calendar.YEAR) + cal.get(Calendar.MONTH) + 1
                + cal.get(Calendar.DAY_OF_MONTH) + "_"
                + cal.get(Calendar.HOUR_OF_DAY) + cal.get(Calendar.MINUTE)
                + cal.get(Calendar.SECOND);
        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;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // Image captured and saved to fileUri specified in the Intent
                Toast.makeText(MicroFilm.this, "Image saved", Toast.LENGTH_LONG).show();
            } else if (resultCode == RESULT_CANCELED) {
                finish();
            } else {
                // Image capture failed, advise user
            }
        }
    }

}

感谢您的帮助 :)

4

3 回答 3

0

我建议您为所有实例变量分配一些初始值。

当您在调用方法时将空对象作为引用传递时,会发生 NULLPOINTEREXCEPTION。

这很可能是因为您没有初始化这些变量。

例如,

private Uri imageUri;

类似于

private Uri imageUri = new Uri();

(这只是一个示例,可能不是为您的预期用途正确初始化 Uri 类)

于 2013-04-12T21:40:27.223 回答
0

只写 soundRecorder=new MediaRecorder soundRecorder();之后 setContentView(R.layout.activity_micro_film);

于 2013-11-20T06:20:42.970 回答
0

我认为你NullPointerException的方法被抛出了captureSound()

soundRecorder在开始调用此对象的方法之前,您必须为变量初始化一个值。

于 2013-04-12T21:42:40.817 回答