如何在IBMapi中将微调器值传递给目标语言



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

`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();
}
}

相关内容

  • 没有找到相关文章

最新更新