Want to implement back button functionality to a basic Android WebView application - android

I created a basic WebView app, want to add a back button function which would take the user to the previous page rather than exiting the app. Have attached the MainActivity.java code with this question below.I am a newbie to stack overflow and android development.
package example.com;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView webview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview =(WebView)findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("https://www.example.com");
}
}

#Override onBackPress() inside your mainActivity and add your navigation logic inside it. Here is working snipped
public class MainActivity extends AppCompatActivity {
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView = new WebView(MainActivity.this);
webView.loadUrl(...);
}
#Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
}else{
//Your App exit logic here
}
}
}
I hope this will meet your requirements.

Try this, hope this helps
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mWebView.canGoBack()) {
mWebView.goBack();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Related

webview back button stopped

In my webview app if I press the back button I get an error:
unfortunately app has stopped
I've tried 2 different ways of doing the back button. Am I missing something?
P.s. first app so please bear with me
package au.com.industryresponsetraining.mdt;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView mwebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String "http://www.google.com";
WebView mwebview = (WebView) this.findViewById(R.id.webView);
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.loadUrl(url);
mwebview.setWebViewClient(new WebViewClient());
}
private class MyWebviewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://www.google.com")) {
return false;
} else {
//here open external links in external browser or app
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
}
//back button function thats not working
#Override
public void onBackPressed() {
if (mwebview.canGoBack()) {
mwebview.goBack();
} else {
super.onBackPressed();
}
}
}
your onCreate method should be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String "http://www.google.com";
mwebview = (WebView) this.findViewById(R.id.webView);
}
instead of
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String "http://www.google.com";
WebView mwebview = (WebView) this.findViewById(R.id.webView);
}
Try this:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mwebview.canGoBack()) {
mwebview.goBack();
} else {
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Method "onBackPressed" not working on WebView Fragment

I'm finishing my WebViev app but I have an issue with going back in a page using WebView, when pressing "back" button the app closes. I need to go back to a previous page on the WebView, but I get the "cannot resolve mehtod onBackPressed();" error.
Fragment Code:
package com.lfcchile;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
/**
* A simple {#link Fragment} subclass.
*/
public class MyFragment4 extends Fragment {
private WebView webView;
public MyFragment4() {
// Required empty public constructor
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View mainView = (View) inflater.inflate(R.layout.fragment_my_fragment1, container, false);
//webView.getSettings().setBuiltInZoomControls(true);
//webView.setInitialScale(50);
//webView.getSettings().setPluginsEnabled(true);
WebView webView = (WebView)mainView.findViewById(R.id.webview);
webView.setWebViewClient(new MantenerDominioWeb());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(false);
webView.getSettings().setSupportZoom(false);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.canGoBack();
webView.goBack();
webView.loadUrl("http://www.lfcchile.com/sitios-interes/");
return mainView;
}
#Override
public View onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
super.onBackPressed();
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
When I put the onBackPressed on MainActivity and press the back button, the app crashes... any ideas please?
Since you are using fragment, you have to get the back key touched event... Follow the below code as a reference...
mainView.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(webView!=null)
{
if(webView.canGoBack())
{
webView.goBack();
}
}
}
}
return true;
}
});
To get the touched key event you have to override the onkeylistener...
Fragments do not have backPressed. You have to use backPressed of its container activity. In your activity override onBackPressed & call it from fragment using getActivity.onBackPressed().
Override onKeyDown instead of onBackPressed. Not necessarily . But this works for me
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
// back button is pressed.. Do your stuff here
if(webView!=null)
{
if(webView.canGoBack())
{
webView.goBack();
}
}
return true;
}
return false;
}

Basic webview app problems

I am trying to make a basic webview application, but it's giving 4 errors.
Error:(35, 9) error: method does not override or implement a method
from a supertype
Error:(46, 32) error: non-static method canGoBack() cannot be
referenced from a static context
Error:(47, 32) error: non-static method goBack() cannot be referenced
from a static context
Error:Execution failed for task ':app:compileDebugJava'.
Compilation failed; see the compiler error output for details.
Can anyone tell me what's wrong with my code?
Here's my code:
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
setContentView(R.layout.activity_main);
WebView mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.loadUrl("http://facebook.com/");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (WebView.canGoBack()) {
WebView.goBack();
} else {
finish();
}
return true;
}
}
}
}
This is my new code now with your help which shows no errors, but still doesn't work(Failed to complete gradle execution, when I try to run it in the emulator):
public class MainActivity extends ActionBarActivity {
private WebView mainWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
setContentView(R.layout.activity_main);
mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.loadUrl("http://facebook.com/");
}
private class MyCustomWebViewClient extends WebViewClient {
public boolean shouldOvrrideLoading (WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mainWebView.canGoBack()) {
mainWebView.goBack();
} else {
finish();
}
return true;
}
}
return false;
}
}
The error actually explains what is wrong:
"non-static method goBack() cannot be referenced from a static context"
You need to replace the static WebView.canGoBack() with your instantiated webview mainWebView.canGoBack()
The same applies for WebView.goBack()
mainWebView variable should be object of class MainActivity
public class MainActivity extends ActionBarActivity {
private WebView mainWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN);
setContentView(R.layout.activity_main);
mainWebView = (WebView) findViewById(R.id.mainWebView);
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.loadUrl("http://facebook.com/");
}
private class MyCustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (mainWebView.canGoBack()) {
mainWebView.goBack();
} else {
finish();
}
return true;
}
}
}
}

webview app force closes when back key is pressed

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);
}
}
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
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();
}
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

How to add back button to Android Web App

I'm trying to sort out a web app but cannot find a possible way to include the use of a back button via the phone's soft keys. How can I go about doing this?
i.e I want to use the back button on my phone to return to the previous viewed web page.
Thank you
Jordan
package com.wear2gym;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Wear2gym extends Activity
{
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Pumping some iron...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(activity, "Sorry but there is no internet connection! " , Toast.LENGTH_LONG).show();
view.loadUrl("file:///android_asset/nointernet.html");
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://wear2gym.co.uk");
webView.canGoBack();
}
}
I wouldn't recommand onBackPressed() as thatÅ› only available since API level 5
You will find great info here: http://developer.android.com/guide/webapps/webview.html
#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) && myWebView.canGoBack() {
myWebView.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);
}
override the onBackPressed() method:
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
}
else {
super.onBackPressed();
}
}
This will go back on the WebView until it can't go back, in which case it will exit the Activity

Categories

Resources