Turn javascript on in android webview - javascript

hello i am new to android developing,
I want to set my javscript turn on in my android webview. I tried everything, but it doesn't work. My code below is my webview class. I hope someone can help me.
package visuals.Webview;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class VisualsActivity extends Activity {
/** Called when the activity is first created. */
final Activity activity = this;
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
// webview.setWebViewClient(new myWebClient());
webview.loadUrl("http://192.168.0.62/lastversion/index.php");
webview.getSettings().setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setUserAgentString(getString(R.string.user_agent_suffix));
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
return true;
} else {
view.loadUrl(url);
return true;
}
}
}
// To handle "Back" key press event for WebView to go back to previous screen.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Thank you for helping

WebView webView;
webView.getSettings().setJavaScriptEnabled(true);
Pretty easy :)

webview.getSettings().setPluginState(PluginState.ON);
or when using older version ( < API 8)
webView.getSettings().setJavaScriptEnabled(true);

WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
And if you want your webview's javascript to be able to interact with your android application. Take a look at webview's addJavascriptInterface method documentation.

Related

How to load a custom error page in webview when no internet connection?

Im trying to find out how I add a custom offline page to my webview app. The app works well I just feel like a custom offline page would look much better! I have looked at some answers online but they dont seem to work any more :(. I hope someone can help!
Here is my Main code is (Made in the android studio):
package com.rizwan.yvsse;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import com.onesignal.OneSignal;
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.init();
Intent intent = new Intent(MainActivity.this, splash_screen.class);
startActivity(intent);
progressBar= (ProgressBar)findViewById(R.id.progressBar);
webView = (WebView) findViewById(R.id.webview);
String url="https://yvsse.com/billing/";
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.setWebViewClient(new HelloWebViewClient());
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(view.GONE);
// TODO Auto-generated method stub
super.onPageFinished(view, url);
}
}
}
Thank you!
Overrride the onReceivedError method and check internet connectivity inside it to confirm that the url failed because of the internet connectivity
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if(!isappOnline()) {
webView.loadUrl("file:///android_asset/error.html");
}
}
private boolean isappOnline() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null;
}
also add your fallback page in assets folder src/main/assets/

Webview isn't showing the page

Yesterday I began a project for my father to have all his web radio's on an app using the embed code that radionomy provides.
I think the code is well formed but when I execute the application, the app just shows a blank page.
Main activity code:
import android.annotation.TargetApi;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CalsicaActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calsica);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
setContentView(clasica);
clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});
//clasica.loadUrl("file:///android_asset/index.html");
}
}
Html code:
<html>
<head><script>
(function (win, doc, script, source, objectName) {
(win.RadionomyPlayerObject = win.RadionomyPlayerObject || []).push(objectName);
win[objectName] = win[objectName] || function (k, v) {
(win[objectName].parameters = win[objectName].parameters || { src: source, version: '1.1' })[k] = v;
};
var js, rjs = doc.getElementsByTagName(script)[0];
js = doc.createElement(script);
js.async = 1;
js.src = source;
rjs.parentNode.insertBefore(js, rjs);
}(window, document, 'script', 'https://www.radionomy.com/js/radionomy.player.js', 'radplayer'));
radplayer('url', 'bravo-clasic');
radplayer('type', 'medium');
radplayer('autoplay', '1');
radplayer('volume', '50');
radplayer('color1', '#000000');
radplayer('color2', '#ffffff');
</script></head>
<body>
<div class="radionomy-player"></div>
</body>
</html>
I already added <uses-permission android:name="android.permission.INTERNET"/> on the android manifest.
I have no idea of what I could've done wrong, I'd appreciate some help.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView clasica = new WebView(this);
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
}
try this first load url in to your web view that perform setContentView
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
//clasica.loadUrl("file:///android_asset/index.html");
}
Well below code will be called only when load some url (by loadUrl() method ). Please check method signature it says should override.
By setting webview client you are just stating that what should happen during load time. But the things that your trying to make happen should start first. Am i making any sense ?
clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});
Solution :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_calsica);
WebView clasica = new WebView(this);
clasica.getSettings().setJavaScriptEnabled(true);
// remove below code you dont need this
/* clasica.setWebViewClient(new WebViewClient() {
#Override
#TargetApi(Build.VERSION_CODES.N)
public boolean shouldOverrideUrlLoading(WebView clasicav, WebResourceRequest request) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
#Override
#SuppressWarnings("deprecation")
public boolean shouldOverrideUrlLoading(WebView clasicav, String url) {
clasicav.loadUrl("file:///android_asset/index.html");
return false;
}
});*/
// you need this line
clasica.loadUrl("file:///android_asset/index.html");
setContentView(clasica);
}

Jquery and CSS animation not working in ANDROID Webview application

I am trying to make a Webview for my website. But i have one problem with jquery code.
This is my DEMO site. In this demo site you can see when you click the image then detail div will open with animation.
But that detail is not open when i click the image.
Note: I am a new in Android
Here is my application code for Webview:
package ecowebtr.ecowebtr;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
private WebView webView;
private CustomWebViewClient webViewClient;
private String Url = "http://www.ecowebtr.com/";
ProgressDialog mProgressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading...");
webViewClient = new CustomWebViewClient();
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(webViewClient);
webView.loadUrl(Url);
}
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if(!mProgressDialog.isShowing())
{
mProgressDialog.show();
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(mProgressDialog.isShowing()){
mProgressDialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
}
}
public void onBackPressed()
{
if(webView.canGoBack()){
webView.goBack();
}else{
super.onBackPressed();
}
}
Try this code to solve:
webView = (WebView) findViewById(R.id.web);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAppCacheEnabled(true);
settings.setDomStorageEnabled(true);
settings.setDatabaseEnabled(true);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
settings.setDatabasePath("/data/data/" + this.getPackageName() + "/databases/");
}

Webview Fragment : Back button and Download Listener?

I make simple webview app. using Webview fragment. App working properly. but problem is i click back button app close down. and second problem is i click on html page link. link not open in default browser. error says webpage not open. i want all tab open in same webview and back button and download link work properly. my code is
MyWebViewFragment.java
package com.example.com;
import android.app.Fragment;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MyWebViewFragment extends Fragment {
ProgressDialog mProgress;
WebView webview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.web_fragment, container,
false);
Bundle bundle = getArguments();
String url = bundle.getString("url");
webview = (WebView) rootView.findViewById(R.id.webview1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
mProgress = ProgressDialog.show(getActivity(), "Loading",
"Please wait for a moment...");
webview.loadUrl(url);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
return rootView;
}
}
MainActivity.java
package com.example.com;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
public class MainActivity extends Activity {
String[] menutitles;
TypedArray menuIcons;
String[] pageUrl;
// nav drawer title
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
private List<RowItem> rowItems;
private CustomAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = mDrawerTitle = getTitle();
menutitles = getResources().getStringArray(R.array.titles);
menuIcons = getResources().obtainTypedArray(R.array.icons);
pageUrl = getResources().getStringArray(R.array.pageurl);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.slider_list);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < menutitles.length; i++) {
RowItem items = new RowItem(menutitles[i], menuIcons.getResourceId(
i, -1), pageUrl[i]);
rowItems.add(items);
}
menuIcons.recycle();
adapter = new CustomAdapter(getApplicationContext(), rowItems);
mDrawerList.setAdapter(adapter);
mDrawerList.setOnItemClickListener(new SlideitemListener());
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.app_name,
R.string.app_name) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
updateDisplay(0);
}
}
class SlideitemListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
updateDisplay(position);
}
}
private void updateDisplay(int position) {
String url = rowItems.get(position).getPageUrl();
Fragment fragment = new MyWebViewFragment();
Bundle bundle = new Bundle();
bundle.putString("url", url);
fragment.setArguments(bundle);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
setTitle(menutitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
To open urls in webview use the code
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setPluginState(WebSettings.PluginState.OFF);
webSettings.setSupportMultipleWindows(true);
webSettings.setBuiltInZoomControls(true);
webSettings.setAppCacheMaxSize(1);
webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
webSettings.setAppCacheEnabled(false);
// webView.setVerticalScrollBarEnabled(false);
// webView.setHorizontalScrollBarEnabled(false);
webView.setWebChromeClient(new WebChromeClient());
webView.clearCache(true);
// webView.setInitialScale(100);
// webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setBackgroundColor(0);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
Log.e("", "shouldOverrideUrlLoading load url" + url);
return false;
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
isLoaded = false;
progressDialog.setMessage("Unknown Error!");
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
displayProgress(getString(R.string.loading), getString(R.string.loading));
Log.e("onPageStarted",url);
}
public void onPageFinished(WebView view, String url) {
isLoaded = true;
super.onPageFinished(view, url);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
try {
progressDialog.dismiss();
} catch (Exception e) {
}
}
}, 1500);
}
});
web_link = "https://twitter.com";
webView.loadUrl(web_link);
}
public void displayProgress(String title,String mes){
if (progressDialog!=null)
progressDialog.dismiss();
progressDialog = new ProgressDialog(MainActivity.this);
// progressDialog.setTitle(title);
progressDialog.setMessage(mes);
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(true);
try {
progressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
}
To go back on web view override this method to your activity
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (web_link!=null && !webView.getUrl().equals(web_link))
webView.goBack();
else{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.to_exit)
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MainActivity.this.finish();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
return super.onKeyDown(keyCode, event);
}

Webview Back Button

Wondering how to make webview go back.
Tried putting in the webview back on press but it seems that with my code it's not working. Not sure if i initiated it, still confused about this.
Also is it possible to get rid of scrollbars in webview? i found some posts about it but am still on the fence about how exactly to put it into my code
package com.webapp.area956;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.Menu;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebViewClient yourWebClient = new WebViewClient()
{
// Override page so it's load on my view only
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// This line we let me load only pages inside Firstdroid Webpage
if ( url.contains("area956") == true )
// Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do nothing).
return true;
}
};
String url = "http://www.area956.com";
WebView view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
}
public void onBackPressed (){
if (WebView.canGoBack()) {
WebView.goBack();
}
else {
super.onBackPressed();
finish();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Have webview as a class member
WebView view;
#Override
public void onCreate(Bundle savedInstanceState) {
Then initialize
view = (WebView) this.findViewById(R.id.webView1);
view.setWebViewClient(yourWebClient);
view.getSettings().setJavaScriptEnabled(true);
view.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
view.loadUrl(url);
Then use onKeyDown
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) && view.canGoBack()) {
view.goBack();
return true;
}
else
{
finish();
return true;
}
}
You have declared WebView view in onCreate and initialized it there. So it becomes local to onCreate.
Edit:
You can also use onBackPressed as of 2.0
http://android-developers.blogspot.in/2009/12/back-and-other-hard-keys-three-stories.html
public void onBackPressed (){
super.onBackPressed();
if (view.canGoBack()) {
view.goBack();
}
else {
finish();
}
}

Categories