How to warn the user with Toast that the OkHttp request returned something other than 200?

I use OkHttp and everything works fine, however I wanted to take into account the case when the DNS resolution is off, the server is off, slow or just returns something other than HTTP Status Code 200. I tried to use Toast, but I can’t, as it is done in another thread (?). How to overcome this obstacle and give the user a better experience? Here is my code:

private void getBinary(String text) throws Exception { OkHttpClient client = new OkHttpClient(); String body = URLEncoder.encode(text, "utf-8"); // Encrypt MCrypt mcrypt = new MCrypt(); String encrypted = MCrypt.bytesToHex(mcrypt.encrypt(body)); Request request = new Request.Builder() .url("http://mysite/my_api.php") .post(RequestBody.create(MediaType.parse("text/plain"), encrypted)) .addHeader("User-Agent", System.getProperty("http.agent")) .build(); client.newCall(request).enqueue(new Callback() { @Override public void onResponse(Response response) throws IOException, RuntimeException { if (response.code() != 200){ Toast.makeText(getSherlockActivity(), "Fail", Toast.LENGTH_LONG).show(); return; } saveResponseToFile(response); } @Override public void onFailure(Request arg0, IOException arg1) { Toast.makeText(getSherlockActivity(), "Bigger fail", Toast.LENGTH_LONG).show(); } }); } 

Here's the accident:

 FATAL EXCEPTION: OkHttp Dispatcher java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() 
+8
android android-toast
source share
1 answer

The toast should be displayed in the main thread. You can use the new Handler(Looper.getMainLooper()) to create a main thread handler from any background thread, and then use it to publish a toast to the main thread.

Such code will work for your:

 public static void backgroundThreadShortToast(final Context context, final String msg) { if (context != null && msg != null) { new Handler(Looper.getMainLooper()).post(new Runnable() { @Override public void run() { Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } }); } } 
+12
source

All Articles