Проблемы API перевода Google на Android - PullRequest
0 голосов
/ 20 февраля 2020

Я пытаюсь использовать Google Translation API, но получаю не нулевую ошибку указателя, это ошибка:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.speakingtranslator.GoogleTranslateActivity.translte(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
at com.example.speakingtranslator.MainActivity.translated(MainActivity.java:332)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:310)
at com.example.speakingtranslator.MainActivity$EnglishToTagalog.onPostExecute(MainActivity.java:271)

Вот код

public void translated() {
        String translatetotagalog = editText.getText().toString();
        Log.v("raw text",translatetotagalog);
        String text = translator.translte(translatetotagalog, "en", "yo");
        Log.v("translated text", text);
        editTranslate.setText(text);

    }


 Here is the translte
    String translte(String text, String from, String to) {
            StringBuilder result = new StringBuilder();
            try {
                String encodedText = URLEncoder.encode(text, "UTF-8");
                String urlStr = "https://www.googleapis.com/language/translate/v2?key="+ key +"&q=" + encodedText + "&target=" + to + "&source=" + from;

                URL url = new URL(urlStr);

                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                InputStream stream;
                if (conn.getResponseCode() == 200) //success
                {
                    stream = conn.getInputStream();
                } else
                    stream = conn.getErrorStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                JsonParser parser = new JsonParser();

                JsonElement element = parser.parse(result.toString());

                if (element.isJsonObject()) {
                    JsonObject obj = element.getAsJsonObject();
                    if (obj.get("error") == null) {
                        String translatedText = obj.get("data").getAsJsonObject().
                                get("translations").getAsJsonArray().
                                get(0).getAsJsonObject().
                                get("translatedText").getAsString();
                        return translatedText;

                    }
                }

                if (conn.getResponseCode() != 200) {
                    System.err.println(result);
                }

            } catch (IOException | JsonSyntaxException ex) {
                System.err.println(ex.getMessage());
            }

            return null;
        }

Завершено MainActivity. java

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.google.android.material.bottomnavigation.BottomNavigationView;


import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    GoogleTranslateActivity translator;
    private TextToSpeech textToSpeech;
    private Button btn, button2, trans;
    String soundName;
    MediaPlayer mp = null;

    String text2speak;
    private boolean connected;
    private static final String API_KEY = "API_KEY";

    private EditText editText, editTranslate;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        btn = findViewById(R.id.material_icon_button);
        button2 = findViewById(R.id.material_icon_yoruba);
        trans = findViewById(R.id.material_icon_translate);

        checkPermission();

        editText = findViewById(R.id.editText);

        editTranslate = findViewById(R.id.editTranslate);

        final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
        final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
                Locale.getDefault());

        textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    int ttsLang = textToSpeech.setLanguage(Locale.US);

                    if (ttsLang == TextToSpeech.LANG_MISSING_DATA
                            || ttsLang == TextToSpeech.LANG_NOT_SUPPORTED) {
                        Log.e("TTS", "The Language is not supported!");
                    } else {
                        Log.i("TTS", "Language Supported.");
                    }
                    Log.i("TTS", "Initialization success.");
                } else {
                    Toast.makeText(getApplicationContext(), "TTS Initialization failed!", Toast.LENGTH_SHORT).show();
                }
            }
        });

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                String data = editText.getText().toString();

                Log.i("TTS", "button clicked: " + data);
                int speechStatus = textToSpeech.speak(data, TextToSpeech.QUEUE_FLUSH, null);

                if (speechStatus == TextToSpeech.ERROR) {
                    Log.e("TTS", "Error in converting Text to Speech!");
                }
            }

        });

        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                soundName = editTranslate.getText().toString();
                soundName = soundName.replaceAll("\\s+", "_").toLowerCase();

                SoundManager(soundName);

                Toast.makeText(getApplicationContext(), soundName, Toast.LENGTH_LONG).show();
            }

        });

        trans.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                text2speak = editText.getText().toString();
                new EnglishToTagalog().execute();

            }

        });


        mSpeechRecognizer.setRecognitionListener(new RecognitionListener() {
            @Override
            public void onReadyForSpeech(Bundle bundle) {

            }

            @Override
            public void onBeginningOfSpeech() {

            }

            @Override
            public void onRmsChanged(float v) {

            }

            @Override
            public void onBufferReceived(byte[] bytes) {

            }

            @Override
            public void onEndOfSpeech() {

            }

            @Override
            public void onError(int i) {

            }

            @Override
            public void onResults(Bundle bundle) {
                //getting all the matches
                ArrayList<String> matches = bundle
                        .getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);

                //displaying the first match
                if (matches != null)
                    editText.setText(matches.get(0));
            }

            @Override
            public void onPartialResults(Bundle bundle) {

            }

            @Override
            public void onEvent(int i, Bundle bundle) {

            }
        });

        findViewById(R.id.material_icon_mic).setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_UP:
                        mSpeechRecognizer.stopListening();
                        editText.setHint("You will see input here");
                        break;

                    case MotionEvent.ACTION_DOWN:
                        mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
                        editText.setText("");
                        editText.setHint("Listening...");
                        break;
                }
                return false;
            }
        });

        //Initialize and Assign Variable
        BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation);

        //Set Home Selected
        bottomNavigationView.setSelectedItemId(R.id.home);

        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {

                switch (menuItem.getItemId()){
                    case R.id.messages:
                        startActivity(new Intent(getApplicationContext(),Messages.class));
                        overridePendingTransition(0,0);
                        return true;
                    case R.id.home:
                        return true;
                    case R.id.info:
                        startActivity(new Intent(getApplicationContext(),Info.class));
                        overridePendingTransition(0,0);
                        return true;
                }
                return false;
            }
        });
    }

    private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
        private ProgressDialog progress = null;

        protected void onError(Exception ex) {
            Toast.makeText(getApplicationContext(),ex.toString(), Toast.LENGTH_LONG).show();
        }

        @Override
        protected Void doInBackground(Void... params) {

            try {
               translator = new GoogleTranslateActivity(API_KEY);

                Thread.sleep(15000);

            } catch (Exception e) {
                // TODO Auto-generated catch block
               e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected void onPreExecute() {
            // start the progress dialog
            progress = ProgressDialog.show(MainActivity.this, null,
                    "Translating...");
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setIndeterminate(true);
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(Void result) {
            translated();
            progress.dismiss();

            super.onPostExecute(result);
        }

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

    }

    public void translated() {

        String translatetotagalog = editText.getText().toString();
        Toast.makeText(getApplicationContext(), translatetotagalog, Toast.LENGTH_LONG).show();
        Log.v("raw text",translatetotagalog);
        String text = translator.translte(translatetotagalog, "en", "yo");
        //translatabletext = (TextView) findViewById(R.id.translatabletext);
        Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        Log.v("translated text", text);
        editTranslate.setText(text);

    }
    protected void SoundManager(String sn){
        if (mp != null){
            mp.reset();
            mp.release();
        }

        switch (sn){
            case "e_kaaro":
                mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaaro);
                break;
            case "e_kaasan":
                mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaasan);
                break;
            case "e_kaale":
                mp = MediaPlayer.create(getApplicationContext(), R.raw.e_kaale);
                break;
            case "bawo_ni_o_se_n_se":
                mp = MediaPlayer.create(getApplicationContext(), R.raw.bawo_ni_o_se_n_se);
                break;
            case "mo_nife_re":
                mp = MediaPlayer.create(getApplicationContext(), R.raw.mo_nife_re);
                break;
            default:
                mp = MediaPlayer.create(getApplicationContext(), R.raw.crowd);
        }
        //Toast.makeText(getApplicationContext(), "clicked " + sn, Toast.LENGTH_LONG).show();
        mp.start();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (textToSpeech != null) {
            textToSpeech.stop();
            textToSpeech.shutdown();
        }
    }

    private void checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                        Uri.parse("package:" + getPackageName()));
                startActivity(intent);
                finish();
            }
        }
    }


    public boolean checkInternetConnection() {

        //Check internet connection:
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        //Means that we are connected to a network (mobile or wi-fi)
        connected = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
                connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED;

        return connected;
    }
}
...