Reputation: 62394
I've had an incredibly difficult time getting the below app to not show an error when the back button is pressed. All I want is the site to load a web page and the back button to perform as it normally does. Does anyone see anything wrong here? The LogCat shows no errors and with the emulator it doesn't break, but it always breaks on my tablet.
MyWebViewClient.java
package com.MySite;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
MySite.java
package com.mysite;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
public class MySite extends Activity {
WebView DCWebView;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//init webview
WebView DCWebView = (WebView) findViewById(R.id.webview);
DCWebView.getSettings().setJavaScriptEnabled(true);
DCWebView.loadUrl("http://mobile.mysite.com");
//when a link is clicked, use the WebView instead of opening a new browser
DCWebView.setWebViewClient(new MyWebViewClient());
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && DCWebView.canGoBack()) {
DCWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Upvotes: 2
Views: 294
Reputation: 36289
You are declaring a local variable called DCWebView
inside of onCreate()
. Change the line
WebView DCWebView = (WebView) findViewById(R.id.webview);
to
DCWebView = (WebView) findViewById(R.id.webview);
Then, when the back key is pressed, there will be a back stack (which is currently false when you call DCWebView.canGoBack()
, since your global DCWebView
was never initialized), the back button will be handled the way you are expecting.
Upvotes: 1
Reputation: 3017
What error are you getting when you hit back on a tablet? Have you tried overriding onBackPressed instead of onKeyDown?
Upvotes: 1