有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Android上的java Google翻译API问题

我正在尝试使用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;
        }

完成主要活动。爪哇

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

import 安卓x.annotation.NonNull;
import 安卓x.appcompat.app.AppCompatActivity;
import 安卓x.core.content.ContextCompat;

import com.google.安卓.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;
    }
}

共 (0) 个答案