Search code examples
javaandroidspeech-recognitiontext-to-speechoverriding

Consolidating Two "OnActivityResult" Methods


If any of you have seen me around, you know I'm incredibly basic in Java. Most of my knowledge is self taught from various sources: In this case the code is mainly taken and modified from online tutorials. I'm trying to create this very simple ai that allows you to 1) Use speech recognition 2) Talk back. The issue is, both of my codes use an OnActivityResult method: And I can't find out how to combine them and keep it working. The code for both works perfectly, but they can't both work at the same time because of the methods with the same name. Here's the two methods, and the method that the first calls.

Any idea how I can get both methods to work at once?

  package com.prometheus.coding.supremisai;

import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.common.api.GoogleApiClient;

import java.util.ArrayList;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class Main extends AppCompatActivity {
    /**
     * Whether or not the system UI should be auto-hidden after
     * {@link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
     */
    protected static final int RESULT_SPEECH = 1;

    private final int CHECK_CODE = 0x1;
    private final int LONG_DURATION = 5000;
    private final int SHORT_DURATION = 1200;

    private Speaker speaker;


    private static final boolean AUTO_HIDE = true;

    /**
     * If {@link #AUTO_HIDE} is set, the number of milliseconds to wait after
     * user interaction before hiding the system UI.
     */
    private static final int AUTO_HIDE_DELAY_MILLIS = 3000;

    /**
     * Some older devices needs a small delay between UI widget updates
     * and a change of the status and navigation bar.
     */
    private static final int UI_ANIMATION_DELAY = 300;

    private View mContentView;
    private View mControlsView;
    private boolean mVisible;
    /**
     * ATTENTION: This was auto-generated to implement the App Indexing API.
     * See https://g.co/AppIndexing/AndroidStudio for more information.
     */
    private GoogleApiClient client;
    private int requestCode;
    private int resultCode;
    private Intent data;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        checkTTS();
        ImageButton btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
        btnSpeak.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);

                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");

                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });

        mVisible = true;
        mControlsView = findViewById(R.id.fullscreen_content_controls);
        mContentView = findViewById(R.id.fullscreen_content);


        // Set up the user interaction to manually show or hide the system UI.
        mContentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                toggle();
            }
        });

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.
        findViewById(R.id.btnSay).setOnTouchListener(mDelayHideTouchListener);
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        speaker = new Speaker(this);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case RESULT_SPEECH: {
                if (resultCode == RESULT_OK && null != data) {

                    ArrayList<String> text = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                    final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
                    final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
                    final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);

                    final RelativeLayout emailLayout = (RelativeLayout) findViewById(R.id.emailInterface);

                    String strInput; // Gets textbox string
                    strInput = text.get(0);

//Commands:
                    if (strInput.contains("open browser")) {
                        Intent intent1 = new Intent(this, Browser.class);
                        startActivity(intent1);
                    } else if (strInput.contains("send email")) {
                        homeLayout.setVisibility(View.GONE);
                        emailLayout.setVisibility(View.VISIBLE);
                    }

                    if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
                        Output.setText("Hello");

                    } else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
                        Output.setText("I'm sorry to dissapoint you");
                    } else if (strInput.contains("goodbye") || strInput.contains("bye")) {
                        Output.setText("Farewell");
                    } else if (strInput.contains("shut up")) {
                        Output.setText(("Anything for you"));
                    } else if (strInput.contains("do you like doctor who")) {
                        Output.setText("I'll take joy in it if you do");
                    } else if (strInput.contains("what is the answer to life the universe and everything")) {
                        Output.setText("42");
                    } else if (strInput.contains("tell me something nice")) {
                        Output.setText("You look nice today");
                        Output.setTextSize(5);
                        Output.append("...says the AI with no eyes");
                        Output.setTextSize(16);
                    } else if (strInput.contains("will you marry me")) {
                        Output.setText("I'm sorry but I don't have the capacity for marriage");
                    } else if (strInput.contains("where can I hide a body")) {
                        Output.setText(("That isn't my area of expertise"));
                    } else if (strInput.contains("weather is nice")) {
                        Output.setText(("If you say so"));
                    } else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
                        Output.setText(("Please try to be a little more intelligent"));
                    } else if (strInput.contains("what is your name")) {
                        Output.setText(("Ignis"));
                    } else if (strInput.contains("who created you")) {
                        Output.setText(("Prometheus created me"));
                    } else if (strInput.contains("who is prometheus")) {
                        Output.setText(("Prometheus is the one who created Ignis"));
                    } else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
                        Output.setText(("Whatever I need do for you"));
                    } else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
                        Output.setText(("Neither"));
                    } else if (strInput.contains("who are you") || strInput.contains("what are you")) {
                        Output.setText(("I am myself"));
                    } else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
                        Output.setText("I'm sorry to hear that");
                    } else if (strInput.contains("good morning")) {
                        Output.setText(("Good morning to you too"));
                    } else if (strInput.contains("good night")) {
                        Output.setText(("Good night"));
                    } else if (strInput.contains("how are you")) {
                        Output.setText(("I'm existing and functioning well, and you?"));
                    } else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
                        Output.setText(("Frankly I don't have an opinion on the matter"));
                    } else if (strInput.contains("what is the meaning of life")) {
                        Output.setText(("To live while you can I would guess"));
                    }
                   String toSpeak = Output.getText().toString();
                    speaker.speak(toSpeak);
                }
                break;
            }

        }
    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100);
    }

    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private void checkTTS(){
        Intent check = new Intent();
        check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        startActivityForResult(check, CHECK_CODE);
    }



    private final View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent motionEvent) {
            if (AUTO_HIDE) {
                delayedHide(AUTO_HIDE_DELAY_MILLIS);
            }
            return false;
        }
    };


    private void toggle() {
        if (mVisible) {
            hide();
        } else {
            show();
        }
    }

    private void hide() {
        // Hide UI first
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }
        mControlsView.setVisibility(View.GONE);
        mVisible = false;

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable);
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {
            // Delayed removal of status and navigation bar

            // Note that some of these constants are new as of API 16 (Jelly Bean)
            // and API 19 (KitKat). It is safe to use them, as they are inlined
            // at compile-time and do nothing on earlier devices.
            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };

    @SuppressLint("InlinedApi")
    private void show() {
        // Show the system bar
        mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mVisible = true;

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable);
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY);
    }

    private final Runnable mShowPart2Runnable = new Runnable() {
        @Override
        public void run() {
            // Delayed display of UI elements
            ActionBar actionBar = getSupportActionBar();
            if (actionBar != null) {
                actionBar.show();
            }
            mControlsView.setVisibility(View.VISIBLE);
        }
    };

    private final Handler mHideHandler = new Handler();
    private final Runnable mHideRunnable = new Runnable() {
        @Override
        public void run() {
            hide();
        }
    };

    /**
     * Schedules a call to hide() in [delay] milliseconds, canceling any
     * previously scheduled calls.
     */
    private void delayedHide(int delayMillis) {
        mHideHandler.removeCallbacks(mHideRunnable);
        mHideHandler.postDelayed(mHideRunnable, delayMillis);
    }



    public void evaluateInput(View v) {
        final EditText Input = (EditText) findViewById(R.id.txtInput); //Lets textbox be referenced
        final TextView Output = (TextView) findViewById(R.id.lblOutput); //Lets label be referenced
        final RelativeLayout homeLayout = (RelativeLayout) findViewById(R.id.homeInterface);

        final RelativeLayout emailLayout = (RelativeLayout) findViewById(R.id.emailInterface);

        String strInput; // Gets textbox string
        strInput = Input.getText().toString();
        strInput = strInput.toLowerCase();
        String toSpeak = Output.getText().toString();
//Commands:
        if (strInput.contains("open browser")) {
            Intent intent1 = new Intent(this, Browser.class);
            startActivity(intent1);
        } else if (strInput.contains("send email")) {
            homeLayout.setVisibility(View.GONE);
            emailLayout.setVisibility(View.VISIBLE);
        }

        if ((strInput.contains("hello")) || (strInput.contains(" hi "))) {
            Output.setText("Hello");
            toSpeak = Output.getText().toString();
        } else if ((strInput.contains("you") && strInput.contains("are")) && (strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb") || strInput.contains("you're") && strInput.contains("idiot") || strInput.contains("stupid") || strInput.contains("retard") || strInput.contains("dumb"))) {
            Output.setText("I'm sorry to dissapoint you");
        } else if (strInput.contains("goodbye") || strInput.contains("bye")) {
            Output.setText("Farewell");
        } else if (strInput.contains("shut up")) {
            Output.setText(("Anything for you"));
        } else if (strInput.contains("do you like doctor who")) {
            Output.setText("I'll take joy in it if you do");
        } else if (strInput.contains("what is the answer to life the universe and everything")) {
            Output.setText("42");
        } else if (strInput.contains("tell me something nice")) {
            Output.setText("You look nice today");
            Output.setTextSize(5);
            Output.append("...says the AI with no eyes");
            Output.setTextSize(16);
        } else if (strInput.contains("will you marry me")) {
            Output.setText("I'm sorry but I don't have the capacity for marriage");
        } else if (strInput.contains("where can I hide a body")) {
            Output.setText(("That isn't my area of expertise"));
        } else if (strInput.contains("weather is nice")) {
            Output.setText(("If you say so"));
        } else if (strInput.contains("bitch") || strInput.contains("fuck") || strInput.contains("shit") || strInput.contains("damn") || strInput.contains("ass")) {
            Output.setText(("Please try to be a little more intelligent"));
        } else if (strInput.contains("what is your name")) {
            Output.setText(("Ignis"));
        } else if (strInput.contains("who created you")) {
            Output.setText(("Prometheus created me"));
        } else if (strInput.contains("who is prometheus")) {
            Output.setText(("Prometheus is the one who created Ignis"));
        } else if (strInput.contains("whats up") || strInput.contains("what's up") || strInput.contains("wassup")) {
            Output.setText(("Whatever I need do for you"));
        } else if (strInput.contains("are you a boy or a girl") || strInput.contains("are you a girl or a boy")) {
            Output.setText(("Neither"));
        } else if (strInput.contains("who are you") || strInput.contains("what are you")) {
            Output.setText(("I am myself"));
        } else if (strInput.contains("i'm hungry") || strInput.contains("i am hungry")) {
            Output.setText("I'm sorry to hear that");
        } else if (strInput.contains("good morning")) {
            Output.setText(("Good morning to you too"));
        } else if (strInput.contains("good night")) {
            Output.setText(("Good night"));
        } else if (strInput.contains("how are you")) {
            Output.setText(("I'm existing and functioning well, and you?"));
        } else if (strInput.contains("do you like") || strInput.contains("what do you think about")) {
            Output.setText(("Frankly I don't have an opinion on the matter"));
        } else if (strInput.contains("what is the meaning of life")) {
            Output.setText(("To live while you can I would guess"));
        }
        toSpeak = Output.getText().toString();
       speaker.speak(toSpeak);


    }




}

Solution

  • The requestCode in the method onActivityResult acts as a key here. You have to define different requestCodes for different activities.

    Activity 1

    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
    try {
        startActivityForResult(intent, 1);
    } catch (ActivityNotFoundException a) {
        Toast t = Toast.makeText(getApplicationContext(), "Opps! Your device doesn't support Speech to Text",Toast.LENGTH_SHORT);
        t.show();
    } 
    

    Activity 2

    Intent check = new Intent();
    check.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
    startActivityForResult(check, 2); 
    

    onActivityResult

    public void onActivityResult(int requestCode, int resultCode, Intent data){
      super.onActivityResult(requestCode, resultCode, data);
      switch (requestCode){
      case (1): 
           //Code for Speech Recognition  
        break;
    
      case (2):
           //Code for Speech Synthesis (Text to Speech)
        break;
    }
    

    Notice that I have used two different numbers here -

    startActivityForResult(intent, 1);

    startActivityForResult(check, 2);

    These 1 and 2 are the requestCodes. The noActivityResult method then switches accordingly. I have tailored this your code. Just replace the Intent declarations. And then edit onActivityResult by adding separate codes for different activities.