muhammad sappe
muhammad sappe

Reputation: 33

how to return value inside of class in java

i'm a beginner in java, i try to make my 1st simple app that is allowing the user to interact with the app using voice but i have a problem on returning the result of speechRecognition. i have the following class:

class listener implements RecognitionListener{
   ....
   public void onResults(Bundle arg0){
      ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
          String result = matches.get(0);
   }
}

in this case i wanna get the value of

result 

how can i get the value of it?

Upvotes: 1

Views: 82

Answers (2)

fweigl
fweigl

Reputation: 22018

Keep a class member and save your result in it:

class listener implements RecognitionListener{

String result; 

   public void onResults(Bundle arg0){
      ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
          result = matches.get(0);
   }
}

or just call another method of your class from within the onResult method:

class listener implements RecognitionListener{

String result; 

   public void onResults(Bundle arg0){
      ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
          doSomethingWithResult(matches.get(0));
   }
}

Upvotes: 1

Neilos
Neilos

Reputation: 2746

class Listener implements RecognitionListener {

   ....

   public String onResults(Bundle arg0) {
      ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
      return matches.get(0);
   }

}

the above method definition works like so:

<access modifier> <return type> <method name>(<argument type> <argument name>)

Then the method can return a type of <argument type>

If the return type must be void then you can do something like this:

class Listener implements RecognitionListener {

    private String match = null;

    ....

    public void onResults(Bundle arg0) {
       ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
       this.match = matches.get(0);
    }

    /**
     * Get the match
     * can return null if onResults not called or matches.get(0) == null
     */
    public String getMatch() {
        return match;
    }

}

Upvotes: 1

Related Questions