我正在尝试从用户的语音中获取数据并将其存储到字符串中,然后将该文本设置为文本视图。但我的申请正在被关闭。请提供正确的代码。 这是我的代码:
package com.example.voicerecognization;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class VoiceRecognization extends Activity {
private static final int REQUEST_CODE = 1234;
private ListView resultList;
Button speakButton;
TextView tv;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_voice_recognization);
speakButton = (Button) findViewById(R.id.button1);
resultList = (ListView) findViewById(R.id.listView1);
tv = (TextView) findViewById(R.id.textView1);
// Disable button if no recognition service is present
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() == 0) {
speakButton.setEnabled(false);
Toast.makeText(getApplicationContext(), "Recognizer Not Found",
1000).show();
}
speakButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startVoiceRecognitionActivity();
}
});
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Rakshak Voice Recognition...");
startActivityForResult(intent, REQUEST_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String[] str = data
.getStringArrayExtra(RecognizerIntent.EXTRA_RESULTS);
tv.setText(str[0]);
/*
* ArrayList<String> matches = data.getStringArrayListExtra(
* RecognizerIntent.EXTRA_RESULTS); resultList.setAdapter(new
* ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
* matches));
*/
}
super.onActivityResult(requestCode, resultCode, data);
}
}
答案 0 :(得分:0)
您的崩溃可能是因为您将ArrayList作为String数组进行投射 - 对data.getStringArrayExtra(RecognizerIntent.EXTRA_RESULTS)
的调用应该是data.getStringArrayListExtra(...)
,就像您在注释代码中那样,然后您可以使用{{1获取第一个元素的方法如下:get(int index)
。
虽然您可能需要先检查以确保列表中包含元素。