Android,Java只从字符串数组中获取最后一个字

时间:2014-11-05 10:39:14

标签: java android arrays contains

我已经构建了一个使用语音识别的java应用程序,我创建了一个像这样的字符串数组:

String[] greetings = {"hello", "hi", "yow"};

现在问题是应用程序只检测数组的最后一个字" yow"而不是"你好"或"嗨"

for (String strings: greetings) 

                 { if (mostLikelyThingHeard.contains(strings)) {
                            tts.speak("Hey nice to see you!",
                                    TextToSpeech.QUEUE_FLUSH, null);

所以我真的不知道我做错了什么,也许mostLikelyThingHeard需要一个' for'循环呢?

完整代码:

package nl.giovanniterlingen.pws;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity implements OnInitListener {
    private static final String TAG = "PWS";

    private TextView result;

    private TextToSpeech tts;

    private Button speak;

    private int SPEECH_REQUEST_CODE = 1234;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        speak = (Button) findViewById(R.id.bt_speak);
        speak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendRecognizeIntent();
            }
        });

        speak.setEnabled(false);
        result = (TextView) findViewById(R.id.tv_result);

        tts = new TextToSpeech(this, this);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            speak.setEnabled(true);
        } else {
            // failed to init
            finish();
        }

    }

    private void sendRecognizeIntent() {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Aan het luisteren...");
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 100);
        startActivityForResult(intent, SPEECH_REQUEST_CODE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == SPEECH_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                ArrayList<String> matches = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                if (matches.size() == 0) {
                    tts.speak("Ik heb niks gehoord, probeer het nog eens",
                            TextToSpeech.QUEUE_FLUSH, null);
                } else {
                    String mostLikelyThingHeard = matches.get(0);
                    result.setText("Dit heeft u gezegd: "
                            + mostLikelyThingHeard + ".");
                    String doei = "doei";
                    String[] greetings = { "hello", "hi", "yow" };

                    for (String strings : greetings) {

                        if (mostLikelyThingHeard.contains(strings)) {
                            tts.speak("Hey nice to see you!",
                                    TextToSpeech.QUEUE_FLUSH, null);

                        } else if (mostLikelyThingHeard.equals(doei)) {
                            tts.speak("Okay tot de volgende keer!",
                                    TextToSpeech.QUEUE_FLUSH, null);
                        } else {
                            tts.speak("Ik begrijp niet wat je bedoeld met "
                                    + mostLikelyThingHeard
                                    + " probeer het anders te verwoorden.",
                                    TextToSpeech.QUEUE_FLUSH, null);
                        }
                    }
                }
            } else {
                Log.d(TAG, "result NOT ok");
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (tts != null) {
            tts.shutdown();
        }
        super.onDestroy();
    }
}

2 个答案:

答案 0 :(得分:1)

你可以把所有的单词都放在一个字符串中(不是数组字符串)。我知道这不是最好的解决方案所以我给你提供了一个简单的例子,其中你写的任何引擎都会说话。 / p>

MainActivity.java
package com.authorwjf.talk2me;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    protected static final int REQUEST_OK = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        findViewById(R.id.button1).setOnClickListener(this);
    }


}
//The on click handler is responsible for firing off the voice intent. 

@Override
public void onClick(View v) {
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
         i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
             try {
             startActivityForResult(i, REQUEST_OK);
         } catch (Exception e) {
                Toast.makeText(this, "Error initializing speech to text engine.", Toast.LENGTH_LONG).show();
         }
}

//When the intent calls back, we display the transcribed text.

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==REQUEST_OK  && resultCode==RESULT_OK) {
                ArrayList<String> thingsYouSaid = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                ((TextView)findViewById(R.id.text1)).setText(thingsYouSaid.get(0));
        }
    }

//activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="132dp"
        android:text="..." ></TextView>

    <ImageButton
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text1"
        android:layout_centerHorizontal="true"
        android:layout_margin="10dp"
        android:layout_marginTop="37dp"
        android:src="@android:drawable/ic_btn_speak_now" ></ImageButton>

</RelativeLayout>

答案 1 :(得分:0)

我看到的唯一问题是你正在检查&#34; doei&#34;在里面...除此之外,它应该工作正常。此外,考虑确保所听到的事情是在您预期的情况下。 此外,您应该跟踪在for中找到或不找到单词的事实。

String doei = "doei";
String[] greetings = { "hallo", "hi", "yow" };
mostLikelyThingHeard = mostLikelyThingHeard.toLowerCase();
boolean found = false;

for (String strings : greetings) {
    if (mostLikelyThingHeard.contains(strings)) {
        tts.speak("Hey nice to see you!",
            TextToSpeech.QUEUE_FLUSH, null);
        found = true;
        break;
    }
} 
if (!found) { 
    if (mostLikelyThingHeard.equals(doei)) {
        tts.speak("Okay tot de volgende keer!", TextToSpeech.QUEUE_FLUSH, null);
    } else {
        tts.speak("Ik begrijp niet wat je bedoeld met "
          + mostLikelyThingHeard
          + " probeer het anders te verwoorden.",
          TextToSpeech.QUEUE_FLUSH, null);
    }
}