Android Studio - 语音搜索 - 说出数字 2 和 4 时崩溃
Android Studio - Voice search - Crashing on saying number 2 and 4
我有一个 activity 具有语音功能。这让你说 4 个词,这些词被添加到一个数组中。我只想要第二个也是最后一个词。
我正在将第二个单词转换为字符串,将最后一个单词转换为 int(最后一个单词始终是 1-5 之间的数字)。
只要我不说 2 或 4,代码就可以正常工作。只要我说这两个数字,应用程序就会崩溃。
我该如何解决这个问题?
我试着考虑插入一个 if 语句。例如 - 如果字符串包含 word for, four 那么它 = 4。(粗略的代码)。
我已经post编辑了下面的代码和堆栈跟踪。
public class Report extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startVoiceInput();
}
});
final String carreg = mVoiceInputTv.getText().toString();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "e.g- Report fpg563 rating 3");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
break;
}
}
if(mVoiceInputTv.getText().toString().contains("report")) {
input();
}
}
public void input() {
String test = mVoiceInputTv.getText().toString();
String[] ms = test.split(" ");
List<String> selectedWords = new ArrayList<>();
for (int i = 0; i < ms.length; i++) {
selectedWords.add(ms[i]);
final String carreg = ms[1];
final String newrating = ms[3];
final int rating = Integer.parseInt(newrating);
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Report.this, Report.class);
Report.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
builder.setMessage("Reporting Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Report_request registerRequest = new Report_request(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Report.this);
queue.add(registerRequest);
}
}
}
堆栈跟踪:
10-25 17:45:41.449 32501-32501/com.example.naveen.loginregister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.naveen.loginregister, PID: 32501
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 }(has extras) }} to activity {com.example.naveen.loginregister/com.example.naveen.loginregister.Report}: java.lang.NumberFormatException: For input string: "for"
at android.app.ActivityThread.deliverResults(ActivityThread.java:4472)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NumberFormatException: For input string: "for"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.naveen.loginregister.Report.input(Report.java:103)
at com.example.naveen.loginregister.Report.onActivityResult(Report.java:85)
at android.app.Activity.dispatchActivityResult(Activity.java:7256)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4468)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
这个反对票是怎么回事?我问一个诚实的问题。当然语法可能不好。但我仍在学习英语。在我 post 提问之前你想让我去上英语课吗?
这一定会发生,因为 2 也是单词 "to" 或 "too",除非您捕捉到这些情况,否则不会将其转换为 int。同样,正如您指出的那样, 4 可能被转换为单词 "for" ,除非您特别注意这种情况,否则它不会再次转换为 int 。
我认为您走在正确的轨道上,抓住了语音转文本将给您一个听起来像数字但不是数字的单词的情况。
但是如果您希望您的代码不崩溃,您需要为任何可能的输入做好准备。因此,如果抛出异常,您应该捕获异常,然后做正确的事情。
try {
final int rating = Integer.parseInt(newrating);
} catch ( NumberFormatException e ) {
//uhoh couldn't get the number
//prompt the user to try again or
//do something else that makes sense
}
我有一个 activity 具有语音功能。这让你说 4 个词,这些词被添加到一个数组中。我只想要第二个也是最后一个词。
我正在将第二个单词转换为字符串,将最后一个单词转换为 int(最后一个单词始终是 1-5 之间的数字)。
只要我不说 2 或 4,代码就可以正常工作。只要我说这两个数字,应用程序就会崩溃。
我该如何解决这个问题?
我试着考虑插入一个 if 语句。例如 - 如果字符串包含 word for, four 那么它 = 4。(粗略的代码)。
我已经post编辑了下面的代码和堆栈跟踪。
public class Report extends AppCompatActivity {
private static final int REQ_CODE_SPEECH_INPUT = 100;
private TextView mVoiceInputTv;
private ImageButton mSpeakBtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.report);
mVoiceInputTv = (TextView) findViewById(R.id.voiceInput);
mSpeakBtn = (ImageButton) findViewById(R.id.btnSpeak);
mSpeakBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startVoiceInput();
}
});
final String carreg = mVoiceInputTv.getText().toString();
}
private void startVoiceInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "e.g- Report fpg563 rating 3");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
mVoiceInputTv.setText(result.get(0));
}
break;
}
}
if(mVoiceInputTv.getText().toString().contains("report")) {
input();
}
}
public void input() {
String test = mVoiceInputTv.getText().toString();
String[] ms = test.split(" ");
List<String> selectedWords = new ArrayList<>();
for (int i = 0; i < ms.length; i++) {
selectedWords.add(ms[i]);
final String carreg = ms[1];
final String newrating = ms[3];
final int rating = Integer.parseInt(newrating);
Response.Listener<String> responseListener = new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(Report.this, Report.class);
Report.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(Report.this);
builder.setMessage("Reporting Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
Report_request registerRequest = new Report_request(carreg, rating, responseListener);
RequestQueue queue = Volley.newRequestQueue(Report.this);
queue.add(registerRequest);
}
}
}
堆栈跟踪:
10-25 17:45:41.449 32501-32501/com.example.naveen.loginregister E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.naveen.loginregister, PID: 32501
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { launchParam=MultiScreenLaunchParams { mDisplayId=0 mFlags=0 }(has extras) }} to activity {com.example.naveen.loginregister/com.example.naveen.loginregister.Report}: java.lang.NumberFormatException: For input string: "for"
at android.app.ActivityThread.deliverResults(ActivityThread.java:4472)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
Caused by: java.lang.NumberFormatException: For input string: "for"
at java.lang.Integer.parseInt(Integer.java:521)
at java.lang.Integer.parseInt(Integer.java:556)
at com.example.naveen.loginregister.Report.input(Report.java:103)
at com.example.naveen.loginregister.Report.onActivityResult(Report.java:85)
at android.app.Activity.dispatchActivityResult(Activity.java:7256)
at android.app.ActivityThread.deliverResults(ActivityThread.java:4468)
at android.app.ActivityThread.handleSendResult(ActivityThread.java:4515)
at android.app.ActivityThread.-wrap22(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1687)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
这个反对票是怎么回事?我问一个诚实的问题。当然语法可能不好。但我仍在学习英语。在我 post 提问之前你想让我去上英语课吗?
这一定会发生,因为 2 也是单词 "to" 或 "too",除非您捕捉到这些情况,否则不会将其转换为 int。同样,正如您指出的那样, 4 可能被转换为单词 "for" ,除非您特别注意这种情况,否则它不会再次转换为 int 。
我认为您走在正确的轨道上,抓住了语音转文本将给您一个听起来像数字但不是数字的单词的情况。
但是如果您希望您的代码不崩溃,您需要为任何可能的输入做好准备。因此,如果抛出异常,您应该捕获异常,然后做正确的事情。
try {
final int rating = Integer.parseInt(newrating);
} catch ( NumberFormatException e ) {
//uhoh couldn't get the number
//prompt the user to try again or
//do something else that makes sense
}