Issue
I am trying to make a translater app and all code is working fine but at the last part my app is crashed while fetching the result from asynctask into mainactivity,what I'm doing wrong here
enter code here
MainActivity.java
b.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View p1)
{
// TODO: Implement this method
texttotranslate = et.getText().toString();
Log.d("text:", "" + texttotranslate);
OkhttpHandler myTask = new OkhttpHandler(new AsyncResponse(){
@Override
public void processFinish(String output)
{
// TODO: Implement this method
Log.d("Response from asynctask", (String) output);
t.setText((String)output);
}
});
myTask.execute(texttotranslate, lang_pair);
}
});
I already created an interface AsyncResponse and added a method processFinish(String output) into it
enter code here
OkHttpHandler.java
public class OkhttpHandler extends AsyncTask<String,Void,String>
{
String res;
String transres;
String finalres;
public AsyncResponse delegate;
public OkhttpHandler(AsyncResponse delegate)
{
this.delegate = delegate;
}
@Override
protected String doInBackground(String[] values)
{
// TODO: Implement this method
OkHttpClient client = new OkHttpClient();
String texttotranslate = values[0];
String lang_pair = values[1];
String key = "my-key";
String url = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + key
+ "&text=" + texttotranslate + "&lang=" + lang_pair;
Request request = new Request.Builder().url(url).build();
try
{
Response response = client.newCall(request).execute();
res = response.body().string();
}
catch (IOException e)
{
e.printStackTrace();
}
if (res != null)
{
try
{
JSONObject jsonobj = new JSONObject(res);
transres = jsonobj.getString("text");
String f = transres.replace("[", "");
String s = f.replace("]", "");
finalres = s.replace("\"", "");
Log.d("final result", "" + finalres);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return finalres;
}
@Override
protected void onPostExecute(String result)
{
// TODO: Implement this method
super.onPostExecute(result);
delegate.processFinish(result);
Log.d("result:", "" + result);
}
}
My app is crashed while launching and there is no any error showing in my logcat.
Solution
I had accidentally deleted okio library from libs folder that's why my app was crashing, so now it's solved. So if anyone using okhttp library then add okio library too.
Answered By - shubham kumbhar
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.