I am creating an app in android studio Using webview and i want something like this. " if the url is unable to load and show something like the screenshot then my app will show a toast saying Incorrect URL ." and if the url loaded properly the toast will show correct URL .
How can i do this.
MainActivity.Java
public class MainActivity extends AppCompatActivity {
WebView mWebv;
ProgressBar spinner;
private String main_url = "http://my.wifi/";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
spinner = findViewById(R.id.webview_spinner);
mWebv = findViewById(R.id.web_view);
WebSettings settings = mWebv.getSettings();
settings.setJavaScriptEnabled(true);
mWebv.setWebViewClient(new WebViewClient(){
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
spinner.setVisibility(View.VISIBLE);
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
spinner.setVisibility(View.GONE);
}
});
mWebv.getSettings().setJavaScriptEnabled(true);
mWebv.loadUrl(main_url);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebv.canGoBack()) {
mWebv.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Simply override this method into your setWebViewClient
mWebv.setWebViewClient(new WebViewClient(){
...
@SuppressWarnings("deprecation")
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// do some stuff
}
@TargetApi(android.os.Build.VERSION_CODES.M)
@Override
public void onReceivedError(WebView inView, WebResourceRequest inReq,WebResourceError inError)
{
// do some stuff
onReceivedError(inView, inError.getErrorCode(), inError.getDescription().toString(), inReq.getUrl().toString());
}
});
Thank's to @newton_cr7 for edit proposition
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.