I have tried Google Translate and Microsoft Translator. Both give the error:
[microsoft-translator-api] Error retrieving translation : null
Caused by: android.os.NetworkOnMainThreadException
I've set everything up according to references and tutorials. The only difference is that instead of calling Translate.execute() on click of a button, I'm trying to have it call as the JSON string data starts coming in.
Here's what I have:
In My Data Model Class
public String getName() throws Exception {
String trans = Translate.execute(prod_name, Language.ENGLISH, Language.fromString(Locale.getDefault().getLanguage()));
return trans;
}
I've also tried this:
In My Data Model Class
public String getName(){
return prod_name;
}
Along with this:
Main Activity
JsonArrayRequest request = new JsonArrayRequest(FEAT_URL,
new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString()); try {
for(int i=0;i<response.length();i++){
String pid=response.getJSONObject(i).getString("pid");
String name=response.getJSONObject(i).getString("prod_name");
String img = response.getJSONObject(i).getString("prod_pic");
String lang = Locale.getDefault().getLanguage();
Log.d("Response: ", name);
String trans = Translate.execute(name, Language.SPANISH, Language.fromString(lang));
fdata.add(new FeaturedModel(pid, trans, img));
}
} catch (Exception e) {
e.printStackTrace();
} featAdapt=new FeaturedAdapter(MainActivity.this, fdata);
pageView.setAdapter(featAdapt);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d(TAG, "Error: " + error.getMessage());
}
});
VolleyController.getInstance().addToRequestQueue(request, TAG);
I have seen other SO questions regarding Translate API's on Android but all of them referred to clicking a view to get the translation. I haven't found anything that gives an example of translating the JSON string response from a Volley request. Any ideas? What would be the proper way to do this without overloading the main thread?
PER COMMENTS BELOW I've added this AsyncTask class to my MainActivity:
class TranslateAsync extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... inTxt) {
try {
String lang = Locale.getDefault().getLanguage();
translatedText = Translate.execute(inTxt, Language.fromString(lang));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Translate Error", e.toString());
}
return null;
}
@Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
}
}
And now getting an error that it can't resolve method setText(String[]) on this line in my adapter class:
holder.ftitle.setText(feature.get(position).getName());
Looking at both the Google and Microsoft Translator API's, they require String[]