Неустранимое исключение AsyncTask # 1 android Watson переводчик - PullRequest
0 голосов
/ 26 марта 2020

Я продолжаю получать следующее исключение, когда нажимаю на кнопку перевода в моем приложении: я убедился, что мой ключ watson APi указан правильно.

Я использую watson Translator Api только для перевода указанных c фразы из моей базы данных ... Все методы базы данных работают нормально. Я просто вижу ошибку в задаче перевода.

E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
    Process: com.example.translatorapp1, PID: 18199
    java.lang.RuntimeException: An error occurred while executing doInBackground()
        at android.os.AsyncTask$4.done(AsyncTask.java:399)
        at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
        at java.util.concurrent.FutureTask.run(FutureTask.java:271)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
     Caused by: java.lang.RuntimeException: Error while fetching access token from token service: 
        at com.ibm.cloud.sdk.core.security.TokenRequestBasedAuthenticator.getToken(TokenRequestBasedAuthenticator.java:252)
        at com.ibm.cloud.sdk.core.security.TokenRequestBasedAuthenticator.authenticate(TokenRequestBasedAuthenticator.java:194)
        at com.ibm.cloud.sdk.core.service.BaseService.setAuthentication(BaseService.java:260)
        at com.ibm.cloud.sdk.core.service.BaseService.createCall(BaseService.java:198)
        at com.ibm.cloud.sdk.core.service.BaseService.createServiceCall(BaseService.java:236)
        at com.ibm.watson.language_translator.v3.LanguageTranslator.translate(LanguageTranslator.java:152)
        at com.example.translatorapp1.PhraseTranslator$TranslationTask.doInBackground(PhraseTranslator.java:132)
        at com.example.translatorapp1.PhraseTranslator$TranslationTask.doInBackground(PhraseTranslator.java:123)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289) 
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167) 
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641) 
        at java.lang.Thread.run(Thread.java:919) 
     Caused by: java.net.SocketException: socket failed: EPERM (Operation not permitted)
        at java.net.Socket.createImpl(Socket.java:492)
        at java.net.Socket.getImpl(Socket.java:552)
        at java.net.Socket.setSoTimeout(Socket.java:1180)
        at okhttp3.internal.connection.RealConnection.connectSocket(RealConnection.java:244)
        at okhttp3.internal.connection.RealConnection.connect(RealConnection.java:166)
        at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:257)
        at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:135)
        at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:114)
        at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:126)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
        at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
        at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:254)
        at okhttp3.RealCall.execute(RealCall.java:92)
        at com.ibm.cloud.sdk.core.security.TokenRequestBasedAuthenticator$2.run(TokenRequestBasedAuthenticator.java:307)
        at java.lang.Thread.run(Thread.java:919) 

Это мой TranslatorClass

public class PhraseTranslator extends AppCompatActivity {
    private LanguageTranslator translationService;

    DatabaseConn langDb;

    TextView displayTrans;
    Spinner  languagesSpinner;
    ListView phrasesLv;
    Button   translateBtn;

    ArrayList<String> p;
    ArrayList<String> spinnerLang;

    ArrayAdapter<String> adapter;
    ArrayAdapter<String> spinnerAdapter;

    String selectedPhrase;

    private String selectedTargetLanguage = "es";

    //private StreamPlayer player = new StreamPlayer();

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

        displayTrans       = findViewById(R.id.displayTransTextView);
        languagesSpinner   = findViewById(R.id.possibleLangspinner);
        phrasesLv          = findViewById(R.id.displayWordsListView);
        translateBtn       = findViewById(R.id.translateBtn);



        //database connection.
        langDb = new DatabaseConn(this);

        //allow only one choice at a time
        phrasesLv.setChoiceMode(CHOICE_MODE_SINGLE);

        p           = new ArrayList<>();
        spinnerLang = new ArrayList<>();


        adapter         = new ArrayAdapter<String>(PhraseTranslator.this, android.R.layout.simple_list_item_single_choice, p);
        spinnerAdapter  = new ArrayAdapter<String>(PhraseTranslator.this, android.R.layout.simple_spinner_item, spinnerLang);

        //retrives subscribed languages and adds them to array.
        getSubscribedLang(spinnerLang);

        translateBtn.setEnabled(false);

        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        //adds subscribed languages to the spinner
        translationService = initLanguageTranslatorService();

        langDb.display(p);

        Collections.sort(p);


        phrasesLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectedPhrase = phrasesLv.getItemAtPosition(position).toString();
                translateBtn.setEnabled(true);

            }
        });

        phrasesLv.setAdapter(adapter);
        languagesSpinner.setAdapter(spinnerAdapter);
        //when translate Button is pressed
        translateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new TranslationTask().execute(selectedPhrase);


            }
        });



    }

    private LanguageTranslator initLanguageTranslatorService() {
        Authenticator authenticator
                = new IamAuthenticator(getString(R.string.visual_recognition_iam_apikey));
        LanguageTranslator service = new LanguageTranslator("2018-05-01", authenticator);
        service.setServiceUrl(getString(R.string.visual_recognition_url));
        return service;
    }

    private class TranslationTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            TranslateOptions translateOptions = new TranslateOptions.Builder()
                    .addText(params[0])
                    .source(Language.ENGLISH)
                    .target(Language.SPANISH)
                    .build();
            TranslationResult result = translationService.translate(translateOptions).execute().getResult();
            String firstTranslation = result.getTranslations().get(0).getTranslation();
            return firstTranslation;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            displayTrans.setText(s);
        }
    }
//retrives the subscribed languages from the database

    public void getSubscribedLang(ArrayList<String> a){
        langDb.rertrivesubscriptions(a);


    }


}

Это мой макет Деятельность

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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=".PhraseTranslator">

    <ListView
        android:id="@+id/displayWordsListView"
        android:layout_width="406dp"
        android:layout_height="424dp"
        android:layout_marginStart="2dp"
        android:layout_marginEnd="3dp"
        android:layout_marginBottom="48dp"
        app:layout_constraintBottom_toTopOf="@+id/translateBtn"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent" />

    <Spinner
        android:id="@+id/possibleLangspinner"
        android:layout_width="313dp"
        android:layout_height="33dp"
        android:layout_marginStart="49dp"
        android:layout_marginTop="120dp"
        android:layout_marginEnd="49dp"
        android:layout_marginBottom="26dp"
        app:layout_constraintBottom_toTopOf="@+id/displayWordsListView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/translateBtn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="32dp"
        android:text="@string/translate"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

    <TextView
        android:id="@+id/displayTransTextView"
        android:layout_width="219dp"
        android:layout_height="60dp"
        android:layout_marginStart="96dp"
        android:layout_marginTop="30dp"
        android:layout_marginEnd="96dp"
        android:layout_marginBottom="30dp"
        android:textAlignment="center"
        android:textSize="18sp"
        app:layout_constraintBottom_toTopOf="@+id/possibleLangspinner"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

Ответы [ 2 ]

0 голосов
/ 27 марта 2020

Произошла ошибка Неправильно с моей android Studio версии, которая вызвала эту ошибку.

0 голосов
/ 26 марта 2020

Быстрая проверка показывает, что вы обращаетесь к Visual Recognition как для аутентификации, так и для URL службы. Не уверен, что здесь проблема, но ключи и URL-адреса API определяются сервисом c, если вы не делитесь информацией между сервисами.

Проверьте подробности в Справочнике по API , если вы еще этого не сделали

...