如何将微调器值传递给 IBM api 中的目标语言?

How to pass spinner value to the target language in IBM api?

我有一个由 IBM 库中的语言组成的微调器。我希望用户 select 一种语言并将文本翻译成 selected 语言。我从 spinner 获得了值,但我不知道如何将值传递给目标语言。请帮忙

`enter code here`Spinner s = (Spinner) findViewById(R.id.spinner1);
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
            android.R.layout.simple_spinner_item, languages);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    s.setAdapter(adapter);
    text = s.getSelectedItem().toString(); // value from spinner



    new Hey().execute();
}


    class Hey extends AsyncTask<Void, Void, String> {
    String text;


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

        }


        @Override
        protected String doInBackground(Void... voids) {

            IamAuthenticator authenticator = new IamAuthenticator("nAh_Z_0X2AS1Vun2MI3UR3lYNRivFRkWaNsZyFwELMul"); //key
            LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
            languageTranslator.setServiceUrl("https://api.eu-gb.language-translator.watson.cloud.ibm.com/instances/83f66689-1c94-4a9b-b595-e2d776f10ded"); //url

            TranslateOptions translateOptions = new TranslateOptions.Builder()
                    .addText("Hello")
                    .source(Language.ENGLISH)
                    .target(Language.SPANISH) // need to get user to select the target language from the spinner option
                    .build();

            TranslationResult result = languageTranslator.translate(translateOptions) //translation happens
                    .execute().getResult();

            String som = result.toString();
            System.out.println(som);


            return som;
        }

首先,您需要了解如何将值作为参数传递给 AsyncTask。因此,在从微调器获取值后将其传递给 AsyncTask 参数。

您的代码将如下所示:

text = s.getSelectedItem().toString(); // value from spinner
new Hey().execute(text);

现在在 AsyncTask 中您将检索传递的参数:

 class Hey extends AsyncTask<Void, Void, String> {
    String text;

        @Override
        protected String doInBackground(Void... voids) {

       String language = (String) params[0]; //can use it further
      TranslateOptions translateOptions = new TranslateOptions.Builder()
                .addText("Hello")
                .source(Language.ENGLISH)
                .target(language) // Do check the input format for this and do required conversion 
                .build();
    }
}