Android:java.lang.RuntimeException:无法实例化活动 ComponentInfo:java.lang.NullPointerException

Posted

技术标签:

【中文标题】Android:java.lang.RuntimeException:无法实例化活动 ComponentInfo:java.lang.NullPointerException【英文标题】:Android : java.lang.RuntimeException: Unable to instantiate activity ComponentInfo: java.lang.NullPointerException 【发布时间】:2012-05-16 13:32:45 【问题描述】:

我正在尝试录制音频,之后应该立即播放录音。我要去哪里错了。请帮帮我。我没有得到。显示空指针异常...

这里是代码

import android.app.Activity;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.AudioRecord;
import android.media.AudioTrack;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;

public class Audio_testActivity extends Activity 
private String LOG_TAG = null;

/* variables which are required to generate and manage the UI of the App */
// private RecordButton mRecordButton = null;
private Button recordBtn, stopBtn, playBtn;

/*
 * variables which are required for the actual functioning of the recording
 * and playing
 */
private AudioRecord recorder = null;
private AudioTrack player = null;
private AudioManager audioManager = null;
private int recorderBufSize, recordingSampleRate;
private int trackBufSize;
private short[] audioData;
private boolean isRecording = false, isPlaying = false;
private Thread startRecThread;

private AudioRecord.OnRecordPositionUpdateListener posUpdateListener;

/**
 * constructor method for initializing the variables
 */
public Audio_testActivity() 
    super();
    LOG_TAG = "Constructor";
    recorderBufSize = recordingSampleRate = trackBufSize = 0;

    // init function will initialize all the necessary variables ...
    init();

    if (recorder != null && player != null) 
        Log.e(LOG_TAG, "recorder and player initialized");
        audioData = new short[recorderBufSize / 2]; // since we r reading
                                                    // shorts

     else 
        Log.e(LOG_TAG, "Problem inside init function ");
    
    posUpdateListener = new AudioRecord.OnRecordPositionUpdateListener() 
        int numShortsRead = 0;

        @Override
        public void onPeriodicNotification(AudioRecord rec) 
            // TODO Auto-generated method stub
            // String LOG_TAG = Thread.currentThread().getName();
            // Log.e(LOG_TAG, "inside position listener");
            audioData = new short[recorderBufSize / 2]; // divide by 2 since
                                                        // now we are
                                                        // reading shorts
            numShortsRead = rec.read(audioData, 0, audioData.length);
            player.write(audioData, 0, numShortsRead);

        

        @Override
        public void onMarkerReached(AudioRecord recorder) 
            // TODO Auto-generated method stub
            Log.e(LOG_TAG, "Marker Reached");
        
    ;
    // listener will be called every time 160 frames are reached
    recorder.setPositionNotificationPeriod(160);
    recorder.setRecordPositionUpdateListener(posUpdateListener);

    Log.e(LOG_TAG, "inside constructor");


private void init() 
    LOG_TAG = "initFunc";
    // int[] mSampleRates = new int[]  8000, 11025, 22050, 44100 ;
    short audioFormat = AudioFormat.ENCODING_PCM_16BIT;
    // for (int rate : mSampleRates) 
    this.recordingSampleRate = AudioTrack
            .getNativeOutputSampleRate(AudioManager.STREAM_MUSIC);
    try 
        // Log.d(LOG_TAG, "Attempting rate " + rate + "Hz, bits: " +
        // audioFormat);
        int bufrSize = AudioRecord.getMinBufferSize(
                this.recordingSampleRate, AudioFormat.CHANNEL_IN_MONO,
                audioFormat);

        // lets find out the minimum required size for AudioTrack
        int audioTrackBufSize = AudioTrack.getMinBufferSize(
                this.recordingSampleRate, AudioFormat.CHANNEL_OUT_MONO,
                audioFormat);

        if (bufrSize != AudioRecord.ERROR_BAD_VALUE
                && bufrSize != AudioRecord.ERROR) 
            // check if we can instantiate and have a success
            if (audioTrackBufSize >= bufrSize) 
                this.recorderBufSize = audioTrackBufSize;
             else 
                this.recorderBufSize = bufrSize;
            

            AudioRecord rec = new AudioRecord(
                    MediaRecorder.Audiosource.DEFAULT,
                    this.recordingSampleRate, AudioFormat.CHANNEL_IN_MONO,
                    audioFormat, this.recorderBufSize);

            if (rec != null
                    && rec.getState() == AudioRecord.STATE_INITIALIZED) 

                // storing variables for future use . . .
                // this.recordingSampleRate = rate;
                // this.recorderBufSize = bufrSize;

                Log.e(LOG_TAG,
                        "Returning..(rate:channelConfig:audioFormat:recorderBufSize)"
                                + this.recordingSampleRate + ":"
                                + AudioFormat.CHANNEL_IN_MONO + ":"
                                + audioFormat + ":" + this.recorderBufSize);

                // Now create an instance of the AudioTrack
                // int audioTrackBufSize = AudioTrack.getMinBufferSize(rate,
                // AudioFormat.CHANNEL_OUT_MONO, audioFormat);

                Log.e(LOG_TAG, "Audio Record / Track / Final buf size :"
                        + bufrSize + "/ " + audioTrackBufSize + "/ "
                        + this.recorderBufSize);

                this.player = new AudioTrack(AudioManager.STREAM_MUSIC,
                        this.recordingSampleRate,
                        AudioFormat.CHANNEL_OUT_MONO, audioFormat,
                        this.recorderBufSize, AudioTrack.MODE_STREAM);

                this.recorder = rec;
                this.player.stop();
                this.player.flush();
                this.player.setPlaybackRate(this.recordingSampleRate);
                return;
            
        
     catch (IllegalArgumentException e) 
        Log.d(LOG_TAG,
                this.recordingSampleRate + "Exception, keep trying.", e);
     catch (Exception e) 
        Log.e(LOG_TAG, this.recordingSampleRate + "Some Exception!!", e);
    
    // for loop for channel config ended here. . . .
    // for loop for audioFormat ended here. . .
    // // for loop for sampleRate
    return;


private void startPlaying() 
    LOG_TAG = "startPlaying";

    Log.e(LOG_TAG, "start Playing");


private void stopPlaying() 
    LOG_TAG = "stopPlaying";

    Log.e(LOG_TAG, "stop Playing");


private void startRecording() 
    LOG_TAG = "startRecording";

    /* start a separate recording thread from here . . . */
    startRecThread = new Thread() 
        @Override
        public void run() 
            // TODO Auto-generated method stub
            android.os.Process
                    .setThreadPriority(android.os.Process.THREAD_PRIORITY_URGENT_AUDIO);
            // String LOG_TAG = Thread.currentThread().getName();
            if (recorder.getRecordingState() != AudioRecord.RECORDSTATE_RECORDING) 
                recorder.startRecording();
            
            // Log.e(LOG_TAG, "running" +recorder.getRecordingState());
            while (recorder.getRecordingState() == AudioRecord.RECORDSTATE_RECORDING) 
                recorder.read(audioData, 0, audioData.length);
                try 

                    Thread.sleep(1000); // sleep for 2s
                 catch (InterruptedException e) 
                    // TODO Auto-generated catch block
                    Log.e("run Method", "recorder thread is interrupted");
                    e.printStackTrace();
                
            
        
    ;
    setVolumeControlStream(AudioManager.STREAM_MUSIC);
    audioManager.setSpeakerphoneOn(false);
    player.flush();
    player.play();
    startRecThread.start();

    Log.e(LOG_TAG, "start Recording");


private void stopRecording() 
    LOG_TAG = "stopRecording";
    recorder.stop();

    if (startRecThread != null && startRecThread.isAlive()) 
        startRecThread.destroy();
        startRecThread = null;
    

    player.stop();
    player.flush();
    Log.e(LOG_TAG, "stop Recording");


private void stop() 
    if (isRecording) 
        isRecording = false;
        stopRecording();
    
    if (isPlaying) 
        isPlaying = false;
        stopPlaying();
    
    recordBtn.setEnabled(true);
    playBtn.setEnabled(true);


@Override
public void onCreate(Bundle icicle) 
    super.onCreate(icicle);
    LOG_TAG = "onCreate";
    // Log.e(LOG_TAG, "Create Called");
    // getting the audio service
    audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    LinearLayout ll = new LinearLayout(this);

    // creating Buttons one by one . . . .
    // button to start the recording process
    recordBtn = new Button(this);
    recordBtn.setText("Record");
    recordBtn.setOnClickListener(new OnClickListener() 
        public void onClick(View v) 
            // TODO Auto-generated method stub
            recordBtn.setEnabled(false);
            playBtn.setEnabled(false);
            isRecording = true;
            startRecording();
        
    );
    // single button to stop recording and playing as applicable
    stopBtn = new Button(this);
    stopBtn.setText("Stop");
    stopBtn.setOnClickListener(new OnClickListener() 

        public void onClick(View v) 
            // TODO Auto-generated method stub
            stop();
        
    );
    // button to play the recorded sound
    playBtn = new Button(this);
    playBtn.setText("Play");
    playBtn.setOnClickListener(new OnClickListener() 

        public void onClick(View v) 
            // TODO Auto-generated method stub
            // reverse the isPlaying
            isPlaying = true;
            recordBtn.setEnabled(false);
            playBtn.setEnabled(false);
            startPlaying();
        
    );

    ll.addView(recordBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    ll.addView(playBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    ll.addView(stopBtn, new LinearLayout.LayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.WRAP_CONTENT, 1));

    setContentView(ll);


@Override
protected void onDestroy() 
    // Clean up code . ..
    super.onDestroy();
    if (recorder != null)
        recorder.release();
    if (startRecThread != null && startRecThread.isAlive())
        startRecThread.destroy();
    if (recorder != null)
        recorder.release();
    if (player != null)
        player.release();
    startRecThread = null;
    recorder = null;
    player = null;
    recordBtn = null;
    stopBtn = null;
    playBtn = null;
    audioData = null;
    System.gc();



这是错误的LOGCAT文件.....

05-17 09:53:01.402: E/AndroidRuntime(367): FATAL EXCEPTION: main
05-17 09:53:01.402: E/AndroidRuntime(367): java.lang.NullPointerException
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity.startRecording(Audio_testActivity.java:232)
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity.access$9(Audio_testActivity.java:194)
05-17 09:53:01.402: E/AndroidRuntime(367):  at audio.xxx.com.Audio_testActivity$3.onClick(Audio_testActivity.java:291)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.view.View.performClick(View.java:2485)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.view.View$PerformClick.run(View.java:9080)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Handler.handleCallback(Handler.java:587)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Handler.dispatchMessage(Handler.java:92)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.os.Looper.loop(Looper.java:123)
05-17 09:53:01.402: E/AndroidRuntime(367):  at android.app.ActivityThread.main(ActivityThread.java:3683)
05-17 09:53:01.402: E/AndroidRuntime(367):  at java.lang.reflect.Method.invokeNative(Native Method)
05-17 09:53:01.402: E/AndroidRuntime(367):  at java.lang.reflect.Method.invoke(Method.java:507)
05-17 09:53:01.402: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-17 09:53:01.402: E/AndroidRuntime(367):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-17 09:53:01.402: E/AndroidRuntime(367):  at dalvik.system.NativeStart.main(Native Method)

让我知道我错在哪里..请帮助我.!!!!!!!!!

【问题讨论】:

Audio_testActivity.java 中的第 81 行? 请让我们知道 Audio_testActivity.java 中的第 81 号,因为您的文件中缺少导入语句,因此我们无法获取。 @DheereshSingh -- 使用 IMPORT 更新 .. 请让我知道解决方案。谢谢 谢谢 rahul,但我的意思是,当您遇到错误时,请让我们知道您的 IDE 中 Audio_testActivity.java 中的第 81 行... 在“初始化函数内部出现问题”错误之前,您是否在日志中收到此语句? 【参考方案1】:

如果您从代码中得到“初始化函数内部的问题”

if (recorder != null && player != null) 
        Log.e(LOG_TAG, "recorder and player initialized");
        audioData = new short[recorderBufSize / 2]; // since we r reading
                                                    // shorts

     else 
        Log.e(LOG_TAG, "Problem inside init function ");
    

recorder 可能为空。请检查一下。

【讨论】:

这个日志“初始化函数内部出现问题”来了? 不,它没有出现在 INIT() 中。我在 startrecording 函数中添加了 81 行代码。现在开始录制功能出错。 对不起,你为什么这样做“我在 startrecording 函数中添加了 81 行代码。现在 startrecording 函数出错。” ?我们只想知道第 81 行代码。 似乎您最好在尝试调用其任何方法之前检查 recorder 是否为非空。如果为 null,则需要对其进行初始化或酌情放弃当前操作。 @ChrisStratton 我试过了.. 录音机不为空.. 请你帮帮我.. 谢谢

以上是关于Android:java.lang.RuntimeException:无法实例化活动 ComponentInfo:java.lang.NullPointerException的主要内容,如果未能解决你的问题,请参考以下文章

浅析Java.lang.Runtime类

java中的命令执行汇总

java.lang.Runtime.exec() Payload

使用java.lang.Runtime.getRuntime无法在matlab中调用多个python脚本实例

System.gc()和Runtime.getRuntime().gc()区别

Java基础7Java重要的class类清单