Search code examples
androidandroid-fragmentswebviewcrash

Android app stops after pull-to-refresh action


I got the following problem: I'm making an android webview app using fragments, and I want to implement a SwipeToRefresh action.

I tried to do it, but the app stops immediately after user's pull-to-refresh action. Here are different codes:

fragment_home.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"
android:background="@android:color/holo_red_light">

<androidx.swiperefreshlayout.widget.SwipeRefreshLayout
    android:id="@+id/sr"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

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

</androidx.swiperefreshlayout.widget.SwipeRefreshLayout>

</RelativeLayout>    

HomeFragment.java public class HomeFragment extends Fragment {

public HomeFragment(){
    // Required
}

private SwipeRefreshLayout mRefreshLayout;
private WebView mWebView;

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

    View v = inflater.inflate(R.layout.fragment_home, container, false);
    mRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.sr);
    mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
            mRefreshLayout.setRefreshing(false);
        }
    });
    final WebView webView = (WebView) v.findViewById(R.id.webviewhome);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.loadUrl("MYURL");
    webView.setWebViewClient(new WebViewClient());
    webView.canGoBack();

    webView.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == MotionEvent.ACTION_UP
                    && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });

    webView.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
            try {
                webView.stopLoading();
            } catch (Exception e) {
            }

            if (webView.canGoBack()) {
                webView.goBack();
            }

            webView.loadUrl("about:blank");
            AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
            alertDialog.setTitle("Erreur !");
            alertDialog.setMessage("Veuillez vérifier votre connexion internet et réessayer");
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Réessayer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    getActivity().finish();
                    startActivity(getActivity().getIntent());
                }
            });

            alertDialog.show();
            super.onReceivedError(webView, errorCode, description, failingUrl);
        }
    });

    return v;
}    

Can you help me please?


Solution

  • If we are not missing parts of your code, then you have created two instances for webview, in the refresh layout you are calling mWebView which hasn't been initialized. try this:

    public HomeFragment(){
        // Required
    }
    
    private SwipeRefreshLayout mRefreshLayout;
    private WebView WebView;
    
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    
    View v = inflater.inflate(R.layout.fragment_home, container, false);
    mRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.sr);
    mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            mWebView.reload();
            mRefreshLayout.setRefreshing(false);
        }
    });
    webView = (WebView) v.findViewById(R.id.webviewhome);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.getSettings().setAppCacheEnabled(true);
    webView.loadUrl("MYURL");
    webView.setWebViewClient(new WebViewClient());
    webView.canGoBack();
    
    webView.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == MotionEvent.ACTION_UP
                    && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });
    
    webView.setWebViewClient(new WebViewClient() {
        public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
            try {
                webView.stopLoading();
            } catch (Exception e) {
            }
    
            if (webView.canGoBack()) {
                webView.goBack();
            }
    
            webView.loadUrl("about:blank");
            AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
            alertDialog.setTitle("Erreur !");
            alertDialog.setMessage("Veuillez vérifier votre connexion internet et réessayer");
            alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Réessayer", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    getActivity().finish();
                    startActivity(getActivity().getIntent());
                }
            });
    
            alertDialog.show();
            super.onReceivedError(webView, errorCode, description, failingUrl);
        }
    });
    
        return v;
    }