错误:java.lang.IllegalStateException:无法执行活动的方法

时间:2015-02-01 10:35:26

标签: android

我正在尝试在内容提供商中保存语音功能但发生此错误

    02-01 16:47:20.201: D/AndroidRuntime(11623): Shutting down VM
02-01 16:47:20.201: W/dalvikvm(11623): threadid=1: thread exiting with uncaught exception (group=0x41831da0)
02-01 16:47:20.211: E/AndroidRuntime(11623): FATAL EXCEPTION: main
02-01 16:47:20.211: E/AndroidRuntime(11623): Process: com.neu.val.activity, PID: 11623
02-01 16:47:20.211: E/AndroidRuntime(11623): java.lang.IllegalStateException: Could not execute method of the activity
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.view.View$1.onClick(View.java:3990)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.view.View.performClick(View.java:4658)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.view.View$PerformClick.run(View.java:19461)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.os.Handler.handleCallback(Handler.java:733)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.os.Handler.dispatchMessage(Handler.java:95)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.os.Looper.loop(Looper.java:146)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.app.ActivityThread.main(ActivityThread.java:5653)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at java.lang.reflect.Method.invokeNative(Native Method)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at java.lang.reflect.Method.invoke(Method.java:515)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at dalvik.system.NativeStart.main(Native Method)
02-01 16:47:20.211: E/AndroidRuntime(11623): Caused by: java.lang.reflect.InvocationTargetException
02-01 16:47:20.211: E/AndroidRuntime(11623):    at java.lang.reflect.Method.invokeNative(Native Method)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at java.lang.reflect.Method.invoke(Method.java:515)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.view.View$1.onClick(View.java:3985)
02-01 16:47:20.211: E/AndroidRuntime(11623):    ... 11 more
02-01 16:47:20.211: E/AndroidRuntime(11623): Caused by: java.lang.NullPointerException
02-01 16:47:20.211: E/AndroidRuntime(11623):    at android.content.ContentUris.parseId(ContentUris.java:85)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at com.neu.val.activity.CreateVoiceSample.insertFeature(CreateVoiceSample.java:181)
02-01 16:47:20.211: E/AndroidRuntime(11623):    at com.neu.val.activity.CreateVoiceSample.actionBt(CreateVoiceSample.java:77)
02-01 16:47:20.211: E/AndroidRuntime(11623):    ... 14 more

第181行出现错误,即此行

if (ContentUris.parseId(insert) != -1) 

我注意到变量“insert”为null但是我尝试过的提供程序的值不是null ..我猜'insert'变量是这里的主要eroor但我不知道如何解决它。请帮忙......

这是发生错误的类:

CreateVoiceSample.java

public class CreateVoiceSample extends ActionBarActivity {

    private Button btSpeak, btCancel, btStop, btSave;
    private WaveRecorder waveRecorder;
    private ProgressBar progressBar;
    private TextView timerText;
    private boolean stopped;
    private int MAX_DURATION = 5000, progressTime, seconds;
    private Timer timer;
    static final String TAG = "VAP";
    public String codebookString;
    private long userId;

    /** The recording output file. */
    private static File outputFile = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
            "recording.wav");

    /**
     * This is actually used to stop the record after the recording time is up
     * as well.
     */

    @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, false, true);
    }

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

    }

    public void actionBt(View v) {
        if (v.getId() == R.id.bSpeak) {
            startRecord();
        } else if (v.getId() == R.id.bStop) {
            stopRecord();
        } 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, true, 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,false,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);
        btStop.setEnabled(stopBt);
        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) {

        long modeId = ((VoiceApplication)getApplication()).getModeId();

        ContentValues cv = new ContentValues();
        cv.put(Feature.SUBJECT_ID, 1);
        cv.put(Feature.MODE_ID, 1);
        cv.put(Feature.REPRESENTATION, password);
        Log.i(TAG, ""+userId+""+modeId+""+password);
        Uri insert = getContentResolver().insert(Feature.CONTENT_URI, cv);
        Log.i(TAG, "Inserted voice features to URI: " + insert);

        if (ContentUris.parseId(insert) != -1) {
            finish();
        } else {
            Toast.makeText(this, "Could not save features!", Toast.LENGTH_LONG).show();
        }
    }

    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);

            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);
        }

    }
}

这是AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.neu.val.activity"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="9"
        android:targetSdkVersion="16" />

    <uses-permission android:name="android.permission.WRITE_SETTINGS" />
    <uses-permission android:name="android.permission.GET_TASKS" />
    <uses-permission android:name="android.permission.READ_LOGS" />
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_USER_DICTIONARY"/>

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" 
        android:name=".VoiceApplication">
        <activity
            android:name=".MainActivity"
            android:clearTaskOnLaunch="true"
            android:excludeFromRecents="true"
            android:label="@string/app_name"
            android:launchMode="singleTask" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".CreateVoiceSample"
            android:label="@string/app_name" >
            <intent-filter>
                <category android:name="android.intent.category.DEFAULT" />

                <action android:name="android.intent.action.INSERT" />

                <data android:mimeType="vnd.android.cursor.dir/vnd.hgb.feature" />
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.DEFAULT" />

                <category android:name="com.neu.val.activity.CREATEVOICESAMPLE" />
            </intent-filter>
        </activity>
        <activity
            android:name=".VoiceAuthenticator"
            android:label="@string/app_name" >
            <intent-filter >
                <action android:name="com.neu.val.intent.AUTH_METHOD" />
            </intent-filter>

            <intent-filter>
                <action android:name="com.neu.val.intent.DO_AUTH.voicerecognition"/>
            </intent-filter>
        </activity>

        <service android:name="com.neu.val.service.LockService" >
        </service>

        <receiver
            android:name="com.neu.val.service.BootStartUpReceiver"
            android:enabled="true"
            android:exported="false" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <provider
            android:name="com.neu.val.database.AuthDb"
            android:authorities="com.neu.val.database">
        </provider>
    </application>

</manifest>

1 个答案:

答案 0 :(得分:0)

我建议你在CedeBook cb = createCodebook(kmeans)的doInBackground方法中设置一个断点:

@Override
protected String doInBackground(String... params) {
  :
  :
  Codebook cb = createCodebook(kmeans);
  Gson gson = new Gson();
  String codebookJsonString = gson.toJson(cb, Codebook.class);
  return codebookJsonString;
}

看起来,codebookJsonString为null,因此在您的方法中返回此null值,并在Method onPostexecute中显示为结果:

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

所以你的活动成员codebookString为null。所以当它被访问时 在insertFeature(codeBookString)上将使用null。所以将发生java.lang.NullPointerException。

还有两点:

  1. 你声明了你的方法insertFeature(String password)。但是你传递了codeBookString,希望这是通缉。
  2. 第二件事是,您将密码记录为信息,请确保在部署应用时将其删除。

    Log.i(TAG,“”+ userId +“”+ modeId +“”+密码);

  3. 还要确保Feature.CONTENT_URI具有有效值。