So I have a Webview and a JavascriptInterface attached to it, how can I show/hide a dialog when a method in the interface is triggered and a request is made to another URL?
I have a game in JavaScript user plays it and when the game is over the score is sent to the interface and if the score is greater than 200 I want to send a request to another server and wanna show/hide dialog during it's processing.
I get this exception: CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
GameActivity.java
Handler mHandler = new Handler(Looper.getMainLooper()); // initialized in onCreate()
private void setWebview(int level) {
WebView webView = findViewById(R.id.webView);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new WebViewJavaScriptInterface(this, mHandler), "app");
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.loadUrl(Helper.GAME_URL + level);
}
private class WebViewJavaScriptInterface {
private Context context;
private Handler mHandler;
WebViewJavaScriptInterface(Context context, Handler mHandler) {
this.context = context;
this.mHandler = mHandler;
}
@JavascriptInterface
public void tellScore(int score) {
if (score >= 200) {
showProgressDialog(); // No error here
RequestBody roundBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("uid", getUid())
.build();
Request roundRequest = new Request.Builder()
.cacheControl(CacheControl.FORCE_NETWORK)
.url(Helper.POST_URL)
.post(roundBody)
.build();
client.newCall(roundRequest).enqueue(new Callback() {
@Override
public void onFailure(@NonNull Call call, @NonNull IOException e) {
e.printStackTrace();
showSnackbarAndFinish();
}
@Override
public void onResponse(@NonNull Call call, @NonNull final Response roundResponse) {
mHandler.post(new Runnable() {
@Override
public void run() {
if (roundResponse.code() == 200) {
String jsonData = "";
try {
jsonData = roundResponse.body().string();
} catch (IOException e) {
e.printStackTrace();
}
try {
final JSONObject jObject = new JSONObject(jsonData);
if (jObject.getBoolean("error")) {
try {
hideProgressDialog(); // <-- error here
} catch (JSONException e) {
e.printStackTrace();
}
} else {
try {
scoreGuide.setText("Score 200 points to earn " + (Integer.parseInt(jObject.getJSONObject("message").getString("current_level")) / 10d));
hideProgressDialog(); // <-- error here
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
showSnackbarAndFinish();
}
}
});
}
});
}
}
}