user7817213
user7817213

Reputation:

webview not connected to the internet page

How can i make it so that when a user of my app is not connected to the internet they receive a error message asking them to connect to the internet?

My main activity code:

public class MainActivity extends AppCompatActivity {

private WebView mywebView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mywebView = (WebView) findViewById(R.id.webView);
    WebSettings webSettings = mywebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mywebView.loadUrl("http://holidayhomes.ca/");
    mywebView.setWebViewClient(new WebViewClient());
    mywebView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
}

@Override
public void onBackPressed() {
    if(mywebView.canGoBack())
        mywebView.goBack();
    super.onBackPressed();

}

}

Upvotes: 0

Views: 107

Answers (4)

Hitesh Dhamshaniya
Hitesh Dhamshaniya

Reputation: 2182

Please check your android manifest file whether you have added internet permission or not. Please you didn't provide internet permission web view can't load webpage even you can't call any internet related operation. you can add permission by adding below tag in android manifest file.

<uses-permission android:name="android.permission.INTERNET" />

Upvotes: 0

sravs
sravs

Reputation: 330

Override onPageStart method of WebviewClient and check for internet connection and show error msg.

webview.setWebViewClient(new WebViewClient() {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            if (isConnected()) {
                //Internet is connected
            } else{
                //set error msg
            }
        }
}

public boolean isConnected(){
    ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

     retrun isConnected;

}

Upvotes: 0

klaudiusnaban
klaudiusnaban

Reputation: 306

Add internet permission to your manifest.xml

<uses-permission android:name="android.permission.INTERNET" />

Upvotes: 0

sam_c
sam_c

Reputation: 810

Use the ConnectivityManager:

ConnectivityManager cm =
    (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null &&
                  activeNetwork.isConnectedOrConnecting();

If isConnected is false, you can display a toast to the user.

Toast.makeText(context, "You must have a network connection", Toast.LENGHT_SHORT);

Upvotes: 1

Related Questions