Reputation: 59
In my webview app i open a website for showing lways in landscape.I also added the onKeyDown function() also. But when a link is opened and back key is pressed the app is closed.please help me to solve
WebActivity.java
package com.example.samworkshops;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebActivity extends Activity {
public WebView webview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient());
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.getSettings().setLoadWithOverviewMode(true);
webview.loadUrl("http://app.samworkshops.org");
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
Upvotes: 0
Views: 395
Reputation: 133560
Change
WebView webview = (WebView) findViewById(R.id.webview);
// declared again and initialized. becomes local to onCreate
to
webview = (WebView) findViewById(R.id.webview);
coz you already have
public class WebActivity extends Activity {
public WebView webview; // declared but this is never initialized
I guess its a NullPointerException
leading to crash
Upvotes: 1
Reputation: 2879
You have two times declared WebView
Try this:
Replace this WebView webview = (WebView) findViewById(R.id.webview);
by
webview = (WebView) findViewById(R.id.webview);
and also do this
@Override
public void onBackPressed() {
webview.goBack();
}
before you will add onBackPressed() method please comment the onKeyDown method
Upvotes: 0
Reputation: 3268
Probably the onBackPressed() method is called before call onKeyDown
Do this. Delete your onKeyDown
and put this one:
@Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
return;
}
super.onBackPressed();
}
Upvotes: 0