Yandex

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 2

public class TranslatorBackgroundTask extends AsyncTask<String, Void, String> {

//Declare Context
Context ctx;
String resultString;
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}

@Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];

String jsonString;

try {
//Set up the translation call URL
String yandexKey =
"trnsl.1.1.20171226T121459Z.08a8183263f03572.8c5cff0151c8ebcd9370fe18f8fd51b474f9b3
bc";
String yandexUrl =
"https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);

//Set Http Conncection, Input Stream, and Buffered Reader


HttpURLConnection httpJsonConnection = (HttpURLConnection)
yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(inputStream));

//Set string builder and insert retrieved JSON result into it


StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}

//Close and disconnect


bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();

//Making result human readable


resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")
+1);
resultString =
resultString.substring(0,resultString.indexOf("\""));

// TranslationCls translationCls=new TranslationCls();


//translationCls.result=resultString;
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim();

} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

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

@Override
protected void onPostExecute(String result) {
translated.setText(resultString);
}

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

You might also like