简体   繁体   中英

Show toast error and prevent display of webview when no connection is available

When there is no connection available it displays the deafult browser error page, What is want is simply not to display any browser error page instead a toast message and a blank screen.

My code:

public class EarnFragment extends Fragment {
WebView mWebView;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    View v=inflater.inflate(R.layout.fragment_earn, container, false);
    mWebView = (WebView) v.findViewById(R.id.webview);
    mWebView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");

    // Enable Javascript
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);

    // Force links and redirects to open in the WebView instead of in a browser
    mWebView.setWebViewClient(new WebViewClient());

    return v;
}

}

if you want to display black screen instead of webview, first you need to change your layout file. then you check internet connection before load the url. check if internet connection not available taht time hide your webview and display your Toast message and relative layout. Othervise hide Relativelayout noConnection.

Step 1 : create layout like this

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webViewData"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

    <RelativeLayout
        android:id="@+id/noConnection"
        android:layout_width="match_parent"
        android:background="#000000"
        android:layout_height="match_parent"/>
</RelativeLayout>

</LinearLayout>

Step 2 : Check your internet connection using this function.

public static boolean checkInternetConnection(Context context) {
    if (context != null) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm != null) {
            return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isAvailable() && cm.getActiveNetworkInfo().isConnected() && cm.getActiveNetworkInfo().isConnectedOrConnecting();
        } else {
            return false;
        }
    } else {
        return false;
    }

}

At the end do this in your code, before load you url,

public class EarnFragment extends Fragment {
WebView mWebView;
RelativeLayout noConnection;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                     Bundle savedInstanceState) {

View v=inflater.inflate(R.layout.fragment_earn, container, false);
mWebView = (WebView) v.findViewById(R.id.webview);
noConnection = (RelativeLayout)v.findViewById(R.id.noConnection);

// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);

if(checkInternetConnection(getActivity())){
 noConnection.setVisibility(View.GONE);
 mWebView.setVisibility(View.VISIBLE);
 mWebView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");

}else{
 noConnection.setVisibility(View.VISIBLE);
 mWebView.setVisibility(View.GONE);
}


// Force links and redirects to open in the WebView instead of in a browser
mWebView.setWebViewClient(new WebViewClient());

return v;
}

Step 1: Make include_error_list_view.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ebebeb"
    android:gravity="center"
    android:orientation="vertical">
    <!--android:background="#ebebeb"-->

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/labelError"
            android:layout_centerHorizontal="true"
            android:src="@drawable/img_icon_error_list" />

        <TextView
            android:id="@+id/labelError"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:gravity="center"
            android:padding="10dp"
            android:text="@string/err_error_list"
            android:textColor="@color/color_app_font_primary" />

        <ProgressBar
            android:id="@+id/errorProgressBar"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/labelError"
            android:layout_centerHorizontal="true"
            android:layout_margin="20dp"
            android:visibility="gone"/>

    </RelativeLayout>

</LinearLayout>

Step 2: Make fragment layout fragment_abc.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:id="@+id/errorView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="gone">

        <include layout="@layout/include_error_list_view" />

    </RelativeLayout>

</RelativeLayout>

Step 3: Bind Layout with JAVA.

public class AbcFragment extends Fragment {

    private final String TAG = "AbcFragment";
    private WebView webView;
    private ProgressDialog progress;
    private RelativeLayout errorView;
    private boolean isShowErrorWiew = false;
    private ProgressDialog progress;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_abc, container, false);
        webView = (WebView) view.findViewById(R.id.webview);
        errorView = (RelativeLayout) view.findViewById(R.id.errorView);
        TextView labelError = (TextView) view.findViewById(R.id.labelError);
        labelError.setText("Application unable to connect with internet.");
        return view;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);

        showProgressBarWithoutHide();

        errorView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShowErrorWiew = false;
                showProgressBarWithoutHide();
                webView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");
            }
        });
        try {
            webView.setWebViewClient(new WebViewClient() {
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    Log.i(TAG, "Processing webview url click...");
                    view.loadUrl(url);
                    return true;
                }

                public void onPageFinished(WebView view, String url) {
                    Log.i(TAG, "Finished loading URL: " + url);
                    if (!isShowErrorWiew) {
                        errorView.setVisibility(View.GONE);
                    }
                    hideProgressBar();
                }

                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    Log.e(TAG, "Error: " + description);
                    isShowErrorWiew = true;
                    errorView.setVisibility(View.VISIBLE);
//                Snackbar.make(webView, getString(R.string.err_process_webView), Snackbar.LENGTH_LONG).show();
                }
            });

            webView.loadUrl("https://demo.hazzardweb.com/easylogin-pro/");

        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        webView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        /*Todo Always Pause WebView Because Background video play is violating google policy*/
        webView.onPause();
    }

    public void hideProgressBar() {
             if (progress != null) {
             progress.dismiss();
             }
      }

public void showProgressBarWithoutHide() {


        if (progress == null) {
            progress = new ProgressDialog(getActivity());
            progress.setMessage(getString(R.string.please_wait));
            progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progress.setIndeterminate(true);
            progress.setCancelable(false);
            progress.show();
        } else if (!progress.isShowing()) {
            progress.show();
        }

}
}

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