0

In my activity, I want to take voice input when we click imageView and convert into text and display it in textfield and after we press button it converts it into french(currently it is fixed) and display it in textfield2. I am using yandex translator.

My error:: When I click button for the first time nothing happens in textfield2 but in log, it display the correct translation.After my 2nd click,it changes the textfield2. But i want to show the translation after 1st click only.Why it is taking 2 click for working while my output is coming correct after 2nd click??

here is my XML file:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/textView"
        tools:layout_editor_absoluteX="131dp"
        tools:layout_editor_absoluteY="202dp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_width="267dp"
        android:layout_height="244dp"
        app:srcCompat="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:text="Text to be Translated" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:text="Translated Text"
        android:textSize="30sp"
        />

</RelativeLayout>

Here is my MainActivty:

package com.example.translator;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    final static int REQUEST_CODE_SPEECH=1000;
    ImageView listen;
    TextView ans,mresult;
    Context context=this;
    Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listen=findViewById(R.id.imageView);
        ans=findViewById(R.id.textView);
        mresult=findViewById(R.id.textView2);
        b=findViewById(R.id.button);
        listen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speak();
            }
        });
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String textToBeTranslated = ans.getText().toString();

                String languagePair = "en-fr"; //English to French ("<source_language>-<target_language>")
                //Executing the translation function
                Translate(textToBeTranslated,languagePair);
            }
        });
    }

    void Translate(String textToBeTranslated,String languagePair){
        TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);

        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB) {
            translatorBackgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,textToBeTranslated,languagePair);
        } else {
            translatorBackgroundTask.execute(textToBeTranslated,languagePair);
        }
        Log.d("Translation Result:", translatorBackgroundTask.t); // Logs the result in Android Monitor
         mresult.setText(translatorBackgroundTask.t);
    }
    void speak(){
        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, "hi say something!!!");
        try{
            startActivityForResult(intent,REQUEST_CODE_SPEECH);
        }
        catch(Exception e) {
            Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
        case REQUEST_CODE_SPEECH:{
          if(resultCode==RESULT_OK && data!=null) {
              ArrayList<String>result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
              ans.setText(result.get(0));
          }
          break;
        }
    }
    }
}

Here is my API File:

package com.example.translator;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
    //Declare Context
    Context ctx;
    public static String t="";
    //Set Context
    TranslatorBackgroundTask(Context ctx){
        this.ctx = ctx;
    }

    @Override
    public String doInBackground(String... params) {
        //String variables
        String textToBeTranslated = params[0];
        String languagePair = params[1];

        String jsonString;

        try {
            //Set up the translation call URL
            String yandexKey = "MY-API-KEY";
            String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
                    + "&text=" + textToBeTranslated + "&lang=" + languagePair;
            URL yandexTranslateURL = new URL(yandexUrl);

            //Set Http Conncection, Input Stream, and Buffered Reader
            HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
            InputStream inputStream = httpJsonConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //Set string builder and insert retrieved JSON result into it
            StringBuilder jsonStringBuilder = new StringBuilder();
            while ((jsonString = bufferedReader.readLine()) != null) {
                jsonStringBuilder.append(jsonString + "\n");
            }

            //Close and disconnect
            bufferedReader.close();
            inputStream.close();
            httpJsonConnection.disconnect();

            //Making result human readable
            String resultString = jsonStringBuilder.toString().trim();
            //Getting the characters between [ and ]
            resultString = resultString.substring(resultString.indexOf('[')+1);
            resultString = resultString.substring(0,resultString.indexOf("]"));
            //Getting the characters between " and "
            resultString = resultString.substring(resultString.indexOf("\"")+1);
            resultString = resultString.substring(0,resultString.indexOf("\""));

            Log.d("Translation Result:", resultString);
            t=resultString;
            return jsonStringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();

    }

    @Override
    protected void onPostExecute(String result) {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

1 Answers1

0

I think it's this line:

mresult.setText(TranslatorBackgroundTask.t);

Shouldn't it be:

mresult.setText(translatorBackgroundTask.t);
Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106