Skip to content Skip to sidebar Skip to footer

How Can I Create A Back Button In A Webview?

The app consists of two activities: first - a listview with links to HTML files from assets, second - a webview with this HTML file. So there are some links in this HTML file (in t

Solution 1:

I use the Back button, as follows:

@OverridepublicbooleanonKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
        mWebView.goBack();
        returntrue;
    }
    returnsuper.onKeyDown(keyCode, event);
}

The advantage of this approach is that it does not use up any of the screen,

Solution 2:

Your problem is that the wWebView class member variable is not initialized so it is null. See this part of your code:

WebViewwWebView= (WebView) findViewById(R.id.webview);

Perfect, you are initializing, but not what you think you are: you declare a local variable for the method and initialize it. However you shadow the class member wWebView, because of the local variable with the same name. Thus you do not initialize the class member, it is null and you get your NPE. Change the above line to (note the absence of the type):

wWebView = (WebView) findViewById(R.id.webview);

EDIT I was never able to make your way of navigating between the pages work. However I did certain changes to your onCreate method and now everything seems fine on my device:

@OverridepublicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    TextViewtitle= (TextView) findViewById(R.id.app_name);
    title.setText(getString(R.string.app_name));

    ButtonbackButton= (Button) findViewById(R.id.button_back);
    backButton.setOnClickListener(this);

    ButtoninfoButton= (Button) findViewById(R.id.button_info);
    infoButton.setOnClickListener(this);

    Bundlebundle= getIntent().getExtras();

    StringhtmlFileName="m" + bundle.getString("defStrID") + ".html";
    StringLINK_TO_ASSETS="file:///android_asset/";
    wWebView = (WebView) findViewById(R.id.webview);
    wWebView.getSettings().setJavaScriptEnabled(true);
    wWebView.loadURL(LINK_TO_ASSETS + htmlFileName);
}

Now you need to change also the contents of the HTML files you load. First of all add the <html><body> at the beginning of each file in the assets and </body></html> at the end. Second now you will need to change your links. For example the link you have included in your question:

<ahref="second.html">Second file</a>

As you see, these become now relative links. All these changes might make your readAssetTextFile useless, but I believe this is easier-to-understand code.

Post a Comment for "How Can I Create A Back Button In A Webview?"