3

I have an android project and I want to handle the back button in the fragment when I use the webview. When I use the webView and click on more than one link and then I click on back. It closes the application. How can I make it go to the back page. So far, I have done the followings :

public class NewsFragment extends Fragment {


private ProgressDialog progressDialog;
private WebView myWebView ;

public NewsFragment()
{

    // Required empty public constructor
}






@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View rootView = inflater.inflate(R.layout.fragment_news, container, false);
    myWebView = (WebView) rootView.findViewById(R.id.mwl_Website);
    myWebView.setWebViewClient(new WebViewClient());
    myWebView.getSettings().setBuiltInZoomControls(true);
    myWebView.requestFocusFromTouch();
    myWebView.setVerticalScrollBarEnabled(true);
    myWebView.setHorizontalScrollBarEnabled(true);
    myWebView.setVerticalScrollBarEnabled(true);
    myWebView.setHorizontalScrollBarEnabled(true);
    myWebView.requestFocusFromTouch();
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.getSettings().setUseWideViewPort(true);
    myWebView.getSettings().setLoadWithOverviewMode(true);
    myWebView.addJavascriptInterface(new WebAppInterface(getActivity()), "Android");
    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl(getResources().getString(R.string.WEBSITE));

    new LoadViewTask().execute();

    rootView.setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == android.view.KeyEvent.ACTION_DOWN) {
                if ((keyCode == android.view.KeyEvent.KEYCODE_BACK)) {
                    if(myWebView!=null)
                    {
                        if(myWebView.canGoBack())
                        {
                            myWebView.goBack();

                        }
                    }
                }
            }
            return true;
        }
    });


    return rootView;

}
private class LoadViewTask extends AsyncTask<Void, Integer, Void>
{
    //Before running code in separate thread
    @Override
    protected void onPreExecute()
    {
        progressDialog = ProgressDialog.show(getActivity(),"Loading...",
                "Loading please wait...", false, false);
    }

    //The code to be executed in a background thread.
    @Override
    protected Void doInBackground(Void... params)
    {
        /* This is just a code that delays the thread execution 4 times,
         * during 850 milliseconds and updates the current progress. This
         * is where the code that is going to be executed on a background
         * thread must be placed.
         */
        try
        {
            //Get the current thread's token
            synchronized (this)
            {
                //Initialize an integer (that will act as a counter) to zero
                int counter = 0;
                //While the counter is smaller than four
                while(counter <= 4)
                {
                    //Wait 850 milliseconds
                    this.wait(1000);
                    //Increment the counter
                    counter++;
                    //Set the current progress.
                    //This value is going to be passed to the onProgressUpdate() method.
                    publishProgress(counter*25);
                }
            }
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
        return null;
    }

    //Update the progress
    @Override
    protected void onProgressUpdate(Integer... values)
    {
        //set the current progress of the progress dialog
        progressDialog.setProgress(values[0]);
    }

    //after executing the code in the thread
    @Override
    protected void onPostExecute(Void result)
    {
        //close the progress dialog
        progressDialog.dismiss();
    }
}
ama989
  • 463
  • 1
  • 5
  • 23
  • 1
    Possible duplicate of [How to go back to previous page if back button is pressed in WebView?](http://stackoverflow.com/questions/6077141/how-to-go-back-to-previous-page-if-back-button-is-pressed-in-webview) – Shahzeb Oct 25 '15 at 04:51
  • In that example, he used the webview in an activity. I am using the webview in a fragment. Though, I will try it – ama989 Oct 25 '15 at 04:56

1 Answers1

6

Problem you are facing is that your onBackPressed() is getting called, and you need to override that -

like this -

@Override
public void onBackPressed() {
   if(myWebView!=null) {
       if (webView.canGoBack()) {
           webView.goBack();   
       }
   }
   super.onBackPressed();
}

Ref

Community
  • 1
  • 1
Darpan
  • 5,623
  • 3
  • 48
  • 80
  • Ok, You mean that I should put your code after the OnCreateView finishes. Well, I have an error in super.onBackPressed(); which says : Method onBackPressed can't be resolved – ama989 Oct 25 '15 at 05:08
  • yes.. where onCreate's '}' comes. Try to write 'onback' and autocomplete it, you will get this method. Otherwise, you can write this code block as it is. – Darpan Oct 25 '15 at 05:10
  • Yes, sire. But I have " onBackPressed" can't be resolved error? – ama989 Oct 25 '15 at 05:11