简体   繁体   中英

Internet Connection Error on fragment Android

im using a webview inside a fragment and i would like to add internet connection error message and a loading pregress bar, can someone please help Here is my

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class FoodFragment extends Fragment {


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_food, container, false);

    WebView webView = (WebView) view.findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    webView.getSettings().setJavaScriptEnabled(true);
    webView.loadUrl("http://food.pacho.co.ke/");

    return view;
}


}

You could do something like this:

 public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager)
            getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

Then in your code where you want to check for connection:

  if(isNetworkAvailable())
 {
   // do things when connection is available
 }
 else
   {
    final android.app.AlertDialog.Builder alertDialog = new 
    android.app.AlertDialog.Builder(project_details.this);
    alertDialog.setMessage("You don't have internet connection").setNegativeButton("OK", new DialogInterface.OnClickListener() {
             @Override
      public void onClick(DialogInterface dialogInterface, int i) {
                dialog.dismiss();
              }
         });
    alertDialog.show();

}

Also I think you have to add permission in manifest:

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

And I'm not sure will this work when you have network but actually not having internet connection.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM