几次成功运行后,进度对话框突然返回空指针异常

时间:2015-02-22 12:42:56

标签: android progressdialog

我正在开发一个应用程序,用户输入他/她的声音,应用程序将计算其功能。所以我放置了一个进度对话框,通知用户应用程序正在计算其功能。首先,应用程序运行完美,然后在第三次运行时,进度对话框返回空指针异常。我不知道如何解决。这是logcat:

02-22 20:35:11.776: D/AndroidRuntime(24137): Shutting down VM
02-22 20:35:11.776: W/dalvikvm(24137): threadid=1: thread exiting with uncaught exception (group=0x4186bda0)
02-22 20:35:11.786: E/AndroidRuntime(24137): FATAL EXCEPTION: main
02-22 20:35:11.786: E/AndroidRuntime(24137): Process: com.neu.val.activity, PID: 24137
02-22 20:35:11.786: E/AndroidRuntime(24137): java.lang.NullPointerException
02-22 20:35:11.786: E/AndroidRuntime(24137):    at android.app.ProgressDialog.setMessage(ProgressDialog.java:325)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at com.neu.val.activity.CreateVoiceSample$MfccTask.onProgressUpdate(CreateVoiceSample.java:341)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:648)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at android.os.Handler.dispatchMessage(Handler.java:102)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at android.os.Looper.loop(Looper.java:146)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at android.app.ActivityThread.main(ActivityThread.java:5653)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at java.lang.reflect.Method.invokeNative(Native Method)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at java.lang.reflect.Method.invoke(Method.java:515)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
02-22 20:35:11.786: E/AndroidRuntime(24137):    at dalvik.system.NativeStart.main(Native Method)

这是班级:

public class CreateVoiceSample extends ActionBarActivity {

    private Button btSpeak, btCance, btSave;
    private WaveRecorder waveRecorder;
    private ProgressBar progressBar;
    private TextView timerText;
    private boolean stopped;
    private int MAX_DURATION = 2500, progressTime, seconds;
    private Timer timer;
    static final String TAG = "VAP";
    public String codebookString;
    private long userId;
    private Uri insertFeatures;
    private AppDB appDB = new AppDB(this);
    /** The recording output file. */
    private static File outputFile = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
            "recording.wav");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.recordvoice);
        userId = getIntent().getLongExtra(Extras.EXTRA_USER_ID, 1);
        initializeVar();
        enableButtons(true, false, true);
    }

    public void initializeVar() {
        btSpeak = (Button) findViewById(R.id.bSpeak);
        btSave = (Button) findViewById(R.id.bSave);
            btCancel = (Button) findViewById(R.id.bCancel);
        progressBar = (ProgressBar) findViewById(R.id.progressBar1);
        timerText = (TextView) findViewById(R.id.textView1);
        stopped = true;
        progressBar.setMax(MAX_DURATION);
        startProgress();

    }

    public void actionBt(View v) {
        if (v.getId() == R.id.bSpeak) {
            startRecord();
        } else if (v.getId() == R.id.bCancel) {
            finish();
        } else if (v.getId() == R.id.bSave) {
            insertFeature(codebookString);
        }
    }

    private void startRecord() {
        // TODO Auto-generated method stub
        enableButtons(false, false, false);
        seconds = 1000;
        progressTime = 0;
        progressBar.setProgress(0);
        timerText.setText("00:00:00");

        if (outputFile.exists())
            outputFile.delete();
        waveRecorder = new WaveRecorder(8000);
        waveRecorder.setOutputFile(outputFile.getAbsolutePath());
        stopped = false;
        try {
            waveRecorder.prepare();
            waveRecorder.start();
            Toast.makeText(getApplicationContext(), "Recording started ... ",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopRecord() {
        stopped = true;
        waveRecorder.stop();
        waveRecorder.release();
        waveRecorder.reset();
        timer.cancel();
        Toast.makeText(getApplicationContext(), "Recording stopped..", Toast.LENGTH_SHORT).show();
        calculateMfccs();
        startProgress();
    }
    public void startProgress() { 
        enableButtons(true,true,true);
        final Handler handler = new Handler();

        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            progress();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                        }
                    }
                });
            }
        };
        timer = new Timer();
        timer.schedule(timerTask, 1, 1000);
    }

    public void enableButtons(boolean startBt, boolean stopBt, boolean saveBt,
            boolean cancelBt) {
        btSpeak.setEnabled(startBt);
            btSave.setEnabled(saveBt);
        btCancel.setEnabled(cancelBt);
    }

    public void progress() {
        if (!stopped) // call ui only when the progress is not stopped
        {
            if (progressTime < MAX_DURATION) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            int secondsText = seconds / 1000;
                            progressTime = progressBar.getProgress() + 1000;
                            progressBar.setProgress(progressTime);
                            timerText.setText("00:00:0" + secondsText);
                            seconds += 1000;
                        } catch (Exception e) {
                        }
                    }
                });
            } else {
                stopRecord();
            }
        }
    }

    private void calculateMfccs() {
        new MfccTask(this).execute(outputFile.getAbsolutePath());
    }
    private void insertFeature(String password) {
        enableButtons(true,false,true);     
        long modeId = ((VoiceApplication)getApplication()).getModeId();
        ContentValues cv = new ContentValues();
        cv.put(Feature.SUBJECT_ID, userId);
        cv.put(Feature.MODE_ID, modeId);
        cv.put(Feature.REPRESENTATION, password);
        insertFeatures = this.getContentResolver().insert(Feature.CONTENT_URI, cv);
        appDB.onClose();
        finish();
        Intent changePassIntent = new Intent(this,MainActivity.class);
        changePassIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
        this.startActivity(changePassIntent);
    }

    class MfccTask extends AsyncTask<String, Object, String> {

        private ProgressDialog progressDialog;
        private final Activity parentActivity;

        public MfccTask(Activity parentActivity) {
            this.parentActivity = parentActivity;
        }

        @Override
        protected String doInBackground(String... params) {
            String filename = params[0];
            WavReader wavReader = new WavReader(filename);

            Log.i(TAG, "Starting to read from file " + filename);
            double[] samples = readSamples(wavReader);

            Log.i(TAG, "Starting to calculate MFCC");
            double[][] mfcc = calculateMfcc(samples);

            FeatureVector pl = createFeatureVector(mfcc);

            KMeans kmeans = doClustering(pl);

            Codebook cb = createCodebook(kmeans);

            Gson gson = new Gson();
            String codebookJsonString = gson.toJson(cb, Codebook.class);
            Log.i(TAG, codebookJsonString);
            return codebookJsonString;
        }

        private Codebook createCodebook(KMeans kmeans) {
            int numberClusters = kmeans.getNumberClusters();
            Matrix[] centers = new Matrix[numberClusters];
            for (int i = 0; i < numberClusters; i++) {
                centers[i] = kmeans.getCluster(i).getCenter();
            }
            Codebook cb = new Codebook();
            cb.setLength(numberClusters);
            cb.setCentroids(centers);
            return cb;
        }

        private KMeans doClustering(FeatureVector pl) {
            long start;
            KMeans kmeans = new KMeans(Constants.CLUSTER_COUNT, pl,
                    Constants.CLUSTER_MAX_ITERATIONS);
            Log.i(TAG, "Prepared k means clustering");
            start = System.currentTimeMillis();
            progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            kmeans.run();
            Log.i(TAG,
                    "Clustering finished, total time = "
                            + (System.currentTimeMillis() - start) + "ms");
            return kmeans;
        }

        private FeatureVector createFeatureVector(double[][] mfcc) {
            int vectorSize = mfcc[0].length;
            int vectorCount = mfcc.length;
            Log.i(TAG, "Creating pointlist with dimension=" + vectorSize
                    + ", count=" + vectorCount);
            FeatureVector pl = new FeatureVector(vectorSize, vectorCount);
            for (int i = 0; i < vectorCount; i++) {
                pl.add(mfcc[i]);
            }
            Log.d(TAG, "Added all MFCC vectors to pointlist");
            return pl;
        }

        private short createSample(byte[] buffer) {
            short sample = 0;
            // hardcoded two bytes here
            short b1 = buffer[0];
            short b2 = buffer[1];
            b2 <<= 8;
            sample = (short) (b1 | b2);
            return sample;
        }

        private double[][] calculateMfcc(double[] samples) {
            MFCC mfccCalculator = new MFCC(Constants.SAMPLERATE,
                    Constants.WINDOWSIZE, Constants.COEFFICIENTS, false,
                    Constants.MINFREQ + 1, Constants.MAXFREQ, Constants.FILTERS);

            int hopSize = Constants.WINDOWSIZE / 2;
            int mfccCount = (samples.length / hopSize) - 1;
            double[][] mfcc = new double[mfccCount][Constants.COEFFICIENTS];
            long start = System.currentTimeMillis();
            for (int i = 0, pos = 0; pos < samples.length - hopSize; i++, pos += hopSize) {
                mfcc[i] = mfccCalculator.processWindow(samples, pos);
                if (i % 20 == 0) {
                    publishProgress("Calculating features...", i, mfccCount);
                }
            }
            publishProgress("Calculating features...", mfccCount, mfccCount);

            Log.i(TAG, "Calculated " + mfcc.length + " vectors of MFCCs in "
                    + (System.currentTimeMillis() - start) + "ms");
            return mfcc;
        }

        private double[] readSamples(WavReader wavReader) {
            int sampleSize = wavReader.getFrameSize();
            int sampleCount = wavReader.getPayloadLength() / sampleSize;
            int windowCount = (int) Math.floor(sampleCount
                    / Constants.WINDOWSIZE);
            byte[] buffer = new byte[sampleSize];
            double[] samples = new double[windowCount * Constants.WINDOWSIZE];

            try {
                for (int i = 0; i < samples.length; i++) {
                    wavReader.read(buffer, 0, sampleSize);
                    samples[i] = createSample(buffer);

                    if (i % 1000 == 0) {
                        publishProgress("Reading samples...", i, samples.length);
                    }
                }
            } catch (IOException e) {
                Log.e(TAG, "Exception in reading samples", e);
            }
            return samples;
        }

        @Override
        protected void onPostExecute(String result) {
            codebookString = result; 
            progressDialog.dismiss();   
        }

        @Override
        protected void onPreExecute() {
            progressDialog = new ProgressDialog(parentActivity);
            progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progressDialog.setTitle("Working...");
            progressDialog.setMessage("Working...");
            progressDialog.setProgress(0);
            progressDialog.setMax(10000);
            progressDialog.show();
            progressDialog.setCancelable(false);
            progressDialog.setCanceledOnTouchOutside(false);
        }

        @Override
        protected void onProgressUpdate(Object... values) {
            String msg = (String) values[0];
            Integer current = (Integer) values[1];
            Integer max = (Integer) values[2];

            progressDialog.setMessage(msg);
            progressDialog.setProgress(current);
            progressDialog.setMax(max);
        }

    }
}

,这是发生错误的行(341行):

progressDialog.setMessage(msg);

1 个答案:

答案 0 :(得分:0)

我认为问题出在actionBt,其中函数startRecord()被调用,而行 progressBar.setProgress(0); ,如果progressBar尚未初始化,则为will raise.its不是在不同的行中多次初始化全局变量的好方法。