Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 错误:java.lang.IllegalStateException:无法执行活动的方法_Android - Fatal编程技术网

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

Android 错误:java.lang.IllegalStateException:无法执行活动的方法,android,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): FAT

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

    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”变量是这里的主要变量,但我不知道如何解决它。请帮忙

这是发生错误的类:

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

    }
}
public类CreateVoiceSample扩展了ActionBarActivity{
专用按钮btSpeak、btCancel、btStop、btSave;
专用录波器;
私人ProgressBar ProgressBar;
私有文本查看时间文本;
私有布尔停止;
私有整数最大持续时间=5000,进行时间,秒;
私人定时器;
静态最终字符串标记=“VAP”;
公共字符串codebookString;
私有长用户ID;
/**录制输出文件*/
私有静态文件outputFile=新文件(
环境
.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC),
“recording.wav”);
/**
*这实际上用于在录制时间结束后停止录制
*还有。
*/
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.recordvoice);
userId=getIntent().getLongExtra(Extras.EXTRA\u USER\u ID,-1);
initializeVar();
启用按钮(真、假、假、真);
}
public void initializeVar(){
btSpeak=(按钮)findViewById(R.id.bSpeak);
btSave=(按钮)findviewbyd(R.id.bSave);
btStop=(按钮)findViewById(R.id.bStop);
btCancel=(按钮)findviewbyd(R.id.bccancel);
progressBar=(progressBar)findViewById(R.id.progressBar1);
timerText=(TextView)findViewById(R.id.textView1);
停止=真;
progressBar.setMax(最大持续时间);
progressBar.setProgress(0);
startProgress();
}
公共无效行动BT(视图五){
if(v.getId()==R.id.bSpeak){
startRecord();
}else if(v.getId()==R.id.bStop){
停止记录();
}else if(v.getId()==R.id.b取消){
完成();
}else if(v.getId()==R.id.bSave){
insertFeature(codebookString);
}
}
私有无效startRecord(){
//TODO自动生成的方法存根
启用按钮(假、真、假、假);
秒=1000;
progressTime=0;
progressBar.setProgress(0);
timerText.setText(“00:00:00”);
if(outputFile.exists())
outputFile.delete();
录波器=新的录波器(8000);
setOutputFile(outputFile.getAbsolutePath());
停止=错误;
试一试{
波形记录器;
waveRecorder.start();
Toast.makeText(getApplicationContext(),“录制已开始…”,
吐司。长度(短)。show();
}捕获(例外e){
e、 printStackTrace();
}
}
公开作废停止记录(){
停止=真;
波记录器。停止();
波形记录器。释放();
waveRecorder.reset();
timer.cancel();
Toast.makeText(getApplicationContext(),“录制已停止…”,Toast.LENGTH\u SHORT.show();
计算emfccs();
startProgress();
}
public void startProgress(){
启用按钮(真、假、真、真);
最终处理程序=新处理程序();
TimerTask TimerTask=新TimerTask(){
@凌驾
公开募捐{
handler.post(新的Runnable(){
@凌驾
公开募捐{
试一试{
进步();
}捕获(例外e){
//TODO自动生成的捕捉块
}
}
});
}
};
定时器=新定时器();
时间表(timerTask,11000);
}
公共无效启用按钮(布尔开始按钮、布尔停止按钮、布尔保存按钮、,
布尔值(Bt){
btSpeak.setEnabled(startBt);
btStop.setEnabled(stopBt);
btSave.setEnabled(saveBt);
btCancel.setEnabled(cancelBt);
}
公共工程进展(){
if(!stopped)//仅当进度未停止时调用ui
{
if(进度时间<最大持续时间){
runOnUiThread(新的Runnable(){
@凌驾
公开募捐{
试一试{
int secondsText=秒/1000;
progressTime=progressBar.getProgress()+1000;
progressBar.setProgress(progressTime);
timerText.setText(“00:00:0”+秒文本);
秒+=1000;
}捕获(例外e){
}
}
});
}否则{
停止记录();
}
}
}
私有无效计算emfccs(){
新建MfccTask(this).execute(outputFile.getAbsolutePath());
}
私有void insertFeature(字符串密码){
长modeId=((VoiceApplication)getApplication()).getModeId();
ContentValues cv=新的ContentValues();
cv.put(Feature.SUBJECT_ID,1);
cv.put(特征模式识别号1);
cv.put(特征、表示、密码);
Log.i(标记“+userId+”+modeId+”+password);
Uri insert=getContentResolver().insert(Feature.CONTENT\u Uri,cv);
Log.i(标签,“将语音特征插入URI:+插入”);
if(ContentUris.parseId)(
<?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>
@Override
protected String doInBackground(String... params) {
  :
  :
  Codebook cb = createCodebook(kmeans);
  Gson gson = new Gson();
  String codebookJsonString = gson.toJson(cb, Codebook.class);
  return codebookJsonString;
}
@Override
protected void onPostExecute(String result){
  codebookString = result; 
  progressDialog.dismiss();   
}