Reputation: 15
Hi guys i am creating a web view app for college project
the problem is whenever the internet is not available web view shows web page not available
But what i want is to Either Display a Message or an Image saying You need to be connected to internet to use this app
So how can i Implement it
Upvotes: 0
Views: 967
Reputation: 3274
Implement your own WebViewClient
and treat the errors you receive:
private WebViewClient webViewClient = new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
}
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(yourContext,"Check your connection",Toast.LENGHT_LONG).show();
//check for the type of your error in errorCode and treat errors as you wish. You can even make the webview load something else(like an image you choose) when you encounter an error.
}
};
yourWebView.setWebViewClient(webViewClient);
Upvotes: 1
Reputation: 3181
Check whether Internet connection is there or not using this method
public class ConnectivityDetector {
private Context ctxt;
public ConnectivityDetector(Context context){
this.ctxt = context;
}
public boolean isConnectedToInternet(){
ConnectivityManager connectivityManager = (ConnectivityManager)ctxt.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null){
NetworkInfo[] infos = connectivityManager.getAllNetworkInfo();
if (infos != null)
for (int i = 0; i < infos.length; i++)
if (infos[i].getState() == NetworkInfo.State.CONNECTED){
return true;
}
}
return false;
}
}
Then, in the activity which uses webview, do this
ConnectivityDetector cd = new ConnectivityDetector(context);
Boolean isConnected = cd.isConnectedToInternet;
// this will return true if connected and false if not.
Now, in your xml, create a textview with intial visibility as gone.
Now, in the activity,
if (isConnectedToInternet){
//do nothing
} else {
webview.setVisibility(GONE);
txtview.setText("Please connect to Internet");
txtview.setVisibility(VISIBLE);
}
You can choose your own way of showing that internet connection is not available in the else part
Upvotes: 0