0

I am developing an Android application with WebView. In that WebView I have a button. I need when I click that button and no internet available, the error message will be displayed. But I can't reach this. Anyone have an idea? Any help will be highly appreciated. Below is my code.

@SuppressLint("SetJavaScriptEnabled")
public class DashboardFragment extends Fragment implements SolutionHandler {
    private final String SAVE_DASHBOARD_PAGE = "saveDashboardPage";
    private final String SAVE_DASHBOARD_WEB_STATE = "saveDashboardWebState";

    private final String DASHBOARD_URL = "https://api.myapp.com/api_endpoint/dashboard/";
    private final String LOGOUT_URL = "myapp://logout/";
    private final String SOLUTION_URL = "myapp://solution/open?solution_id";
    private final String MY_APP = "myapp://";
    private final String SUPPORT_URL = "http://support";

    private View dashboardView;
    private WebView dashboardWebView;

    private String currentUrl;
    private User user;

    private LoadingDialog loadingDialog;

    private Bundle webState;

    private int supportUrlAcessCount = 0;


    public DashboardFragment() {
         setRetainInstance(true);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        OptimizeHIT.sendScreen(GAnalyticsScreenNames.DASHBOARD_SCREEN, null, null);

        dashboardView = inflater.inflate(R.layout.fragment_dashboard, container, false);

        user = User.sharedUser(getActivity());




        if (savedInstanceState != null) {
            currentUrl = savedInstanceState.getString(SAVE_DASHBOARD_PAGE);
            webState = savedInstanceState.getBundle(SAVE_DASHBOARD_WEB_STATE);
        }

        if (currentUrl == null || currentUrl.length() == 0) {
            currentUrl = DASHBOARD_URL + user.hash();
        }

        loadingDialog = new LoadingDialog(getActivity(), R.string.loading_dashboard, R.string.icon_arrows_cw, true);
        WebChromeClient webClient = new WebChromeClient();

        if (dashboardWebView == null) {
            dashboardWebView = new WebView(getActivity());
            dashboardWebView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

            dashboardWebView.setVerticalScrollBarEnabled(true);
            dashboardWebView.setHorizontalScrollBarEnabled(true);
            dashboardWebView.requestFocusFromTouch();
            dashboardWebView.getSettings().setAppCachePath(getActivity().getCacheDir().getAbsolutePath());
            dashboardWebView.getSettings().setAppCacheEnabled(true);
            dashboardWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);


//          dashboardWebView.setOnTouchListener(webViewTouchListener);

            dashboardWebView.setWebChromeClient(webClient);
            dashboardWebView.setWebViewClient(new WebViewClient() {

                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    // TODO Auto-generated method stub


                    if(!isNetworkAvailable(getActivity())){
                        showNoInternetError();
                    }
                    super.onPageStarted(view, url, favicon);
                }

                @Override
                public void onPageFinished(WebView view, String url) {
                    if (url.startsWith(DASHBOARD_URL)) {
                        view.clearHistory();
                        loadingDialog.dismiss();
                    }
                }

                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {

                        if (url != null && url.startsWith(OHITAPP)) {
                            if (url.startsWith(SOLUTION_URL)) {
                                loadingDialog.setStringResource(R.string.loading_solution);
                                loadingDialog.show();

                                Locker.lock(getActivity());

                                Pattern pattern = Pattern.compile("[0-9]+");
                                Matcher matcher = pattern.matcher(url);

                                String solutionId = "";

                                if (matcher.find()) {
                                    solutionId = matcher.group();
                                }



                            }

                            return true;
                        } else if (url.startsWith(SUPPORT_URL)) {
                            supportUrlAcessCount++;
                            if (supportUrlAcessCount == 2) {
                                ((MenuActivity) getActivity()).changeFragment(6, false, false, false, null, null);

                                return true;
                            }

                            return false;
                        } else {
                            return false;
                        }

                }


                @Override
                public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                    if ((failingUrl.startsWith(SUPPORT_URL) && supportUrlAcessCount == 2)
                            || failingUrl.startsWith(OHITAPP)) {
                        return;
                    }

                    showNoInternetError();
                }
            });

            if (webState == null) {
                if (CheckConnectionHelper.isNetworkAvailable(getActivity())) {
                    loadingDialog.show();
                    dashboardWebView.loadUrl(currentUrl);
                } else {
                    ErrorHelper.showError(TalkersConstants.JUST_FAILURE, (SuperActivity) getActivity());
                    dashboardWebView.loadUrl("about:blank");
                }


                dashboardWebView.getSettings().setSupportZoom(true);
                dashboardWebView.getSettings().setBuiltInZoomControls(true);
                dashboardWebView.getSettings().setDisplayZoomControls(false);
                dashboardWebView.getSettings().setLoadWithOverviewMode(true);
                dashboardWebView.getSettings().setUseWideViewPort(true);
                dashboardWebView.getSettings().setJavaScriptEnabled(true);
            } else {
                dashboardWebView.restoreState(webState);
            }
        } else {
            if (webState == null) {
                loadingDialog.show();
                dashboardWebView.loadUrl(currentUrl);

                dashboardWebView.getSettings().setSupportZoom(true);
                dashboardWebView.getSettings().setBuiltInZoomControls(true);
                dashboardWebView.getSettings().setDisplayZoomControls(false);
                dashboardWebView.getSettings().setLoadWithOverviewMode(true);
                dashboardWebView.getSettings().setUseWideViewPort(true);
                dashboardWebView.getSettings().setJavaScriptEnabled(true);
            } else {
                dashboardWebView.restoreState(webState);
            }
        }

        LinearLayout dashboardContainer = (LinearLayout) dashboardView.findViewById(R.id.dashboard_container);
        dashboardContainer.addView(dashboardWebView);

        getActivity().getWindow().getDecorView().getViewTreeObserver()
                .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                    @Override
                    public void onGlobalLayout() {
                        dashboardView.requestLayout();
                    }
                });

        return dashboardView;
    }

    @Override
    public void onDestroyView() {
        LinearLayout dashboardContainer = (LinearLayout) dashboardView.findViewById(R.id.dashboard_container);
        dashboardContainer.removeView(dashboardWebView);

        super.onDestroyView();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putString(SAVE_DASHBOARD_PAGE, getCurrentPage());
        outState.putBundle(SAVE_DASHBOARD_WEB_STATE, getCurrentWebViewState());

        super.onSaveInstanceState(outState);
    }

    public String getCurrentPage() {
        return dashboardWebView.getUrl();
    }

    public Bundle getCurrentWebViewState() {
        Bundle outState = new Bundle();
        dashboardWebView.saveState(outState);

        return outState;
    }



    public boolean navigatesBack() {
        if (dashboardWebView != null && dashboardWebView.canGoBack()) {
            dashboardWebView.goBack();

            return true;
        }

        return false;
    }

    public void showNoInternetError() {
        loadingDialog.dismiss();
        ErrorHelper.showError(TalkersConstants.JUST_FAILURE, (SuperActivity) getActivity());
        dashboardWebView.loadUrl("about:blank");
    }

    public void reloadWebView() {
        if (dashboardWebView.getUrl() == null
                || dashboardWebView.getUrl().isEmpty()
                || dashboardWebView.getUrl().equals("about:blank")) {
            dashboardWebView.loadUrl(currentUrl);
        }
    }

    OnTouchListener webViewTouchListener = new OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            if (System.currentTimeMillis() - SuperActivity.savedLastClickTime < 1000) {
                Log.d("I AM IN A FALSE", "FALSE");
                return true;
            }

            SuperActivity.savedLastWebViewInteractionTime = System.currentTimeMillis();

            Log.d("I AM IN A TOUCH LISTENER", "TOUCH LISTENER");
            return false;
        }
    };



    public boolean isNetworkAvailable( Context context ) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

}
Victor
  • 147
  • 1
  • 1
  • 8

2 Answers2

0

Create a common class ConnectionDetector

public class ConnectionDetector {
    private Context _context;

    public ConnectionDetector(Context context) {
        this._context = context;
    }

    public boolean isConnectingToInternet() {
        ConnectivityManager connectivity = (ConnectivityManager) _context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
                for (int i = 0; i < info.length; i++)
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }

        }
        return false;
    }
}

After that in your activity or fragment initialize these variables

    ConnectionDetector cd;
    Boolean isInternetPresent = false;

Before calling to webView just check the connection like this

        cd = new ConnectionDetector(context);
                    isInternetPresent = cd.isConnectingToInternet();
                    keyBoardHide();
                    if (isInternetPresent) {
                        //call webview here
                    } else {
                        // Use Toast to popup msg
                    }
Pavan Bilagi
  • 1,618
  • 1
  • 18
  • 23
  • Thank You for Your reply Pavan Bilagi. But what did you mean, when say "calling web view"? You mean click button inside the webView? – Victor Dec 01 '15 at 14:09
  • In onClick button method inside just use this code cd = new ConnectionDetector(context); isInternetPresent = cd.isConnectingToInternet(); keyBoardHide(); if (isInternetPresent) { // call function or whatever you want } else { // Use Toast to popup msg } – Pavan Bilagi Dec 01 '15 at 14:14
  • But how to set an onClick listener to button, that IS INSIDE A WEBVIEW? :) – Victor Dec 01 '15 at 14:18
0

Here is simillar question. You can check if there network is on with this, and if is not you can show error message.

Detect whether there is an Internet connection available on Android

Community
  • 1
  • 1
bogus998
  • 126
  • 2
  • 6
  • Thank You, bogus998. But my problem is not in connectivity detection. My isNetworkAvailable() method works fine in another places of my code. The problem that it is not working( maybe not called? ) when I click on a button in a webView. I think it is related with javaScript , because, as I know, javaScript worked when you click on a button in a webView. – Victor Dec 01 '15 at 14:39