Method "onBackPressed" not working on WebView Fragment - android

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

Related

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

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

Go back to previous page one back key press Android WebView Fragment

I am using Navigation drawer activity and have 5 fragments, each and every fragment uses WebView to open webpage. Before I was using just one MainActivity which just opened one site and was able to go back to previous opened page easily but now I can't find anything that will let me do this. I am using this code currently in my fragments, I am using the code to go back from here and whenever I open a fragment, app just force-closes.
package com.science.s11;
import android.app.Fragment;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
public class ask extends Fragment {
public WebView mWebView;
public ProgressBar progressBar;
public LinearLayout layoutProgress;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.ampproject, container, false);
mWebView = (WebView) v.findViewById(R.id.aboutuswebViewask);
progressBar = (ProgressBar) v.findViewById(R.id.progressBarask);
layoutProgress = (LinearLayout) v.findViewById(R.id.layoutProgressask);
mWebView.setVisibility(View.GONE);
mWebView.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if(event.getAction() == KeyEvent.ACTION_DOWN)
{
WebView webView = (WebView) v;
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack())
{
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
WebSettings settings = mWebView.getSettings();
settings.setSupportMultipleWindows(true);
settings.setBuiltInZoomControls(false);
settings.setSupportZoom(false);
settings.setDisplayZoomControls(false);
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
mWebView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(true);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(false);
super.onPageStarted(view, url, favicon);
}
});
if (isOnline()) {
mWebView.loadUrl("http://google.com");
} else {
mWebView.loadUrl("file:///android_asset/cti.html");
}
return v;
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}}
Can you guys please help me?
Try this, its simple and works fine.
In all of your 5 Fragments, set the variable to public static:
public static WebView mWebView;
In your Mainactivity:
#Override
public void onBackPressed() {
if (Fragment_1.mWebView!= null) {
if (Fragment_1.mWebView.canGoBack()) {
Fragment_1.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_2.mWebView!= null){
if (Fragment_2.mWebView.canGoBack()) {
Fragment_2.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_3.mWebView!= null){
if (Fragment_3.mWebView.canGoBack()) {
Fragment_3.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
if (Fragment_4.mWebView!= null){
if (Fragment_4.mWebView.canGoBack()) {
Fragment_4.mWebView.goBack();
} else {
// do when mWebView cant go back anymore
}
}
//and so on......
}
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);
}
you can make a base fragment like this
public abstract class BaseFragments extends Fragment {
abstract public int setContentView();
public void replaceFragment(Context context, Fragment fragment) {
((BaseActivity) context).getSupportFragmentManager().beginTransaction()
.replace(R.id.container, fragment).commit();
}
#Override
public void onResume() {
super.onResume();
// preferencesUtility.setuserData(context, userdata);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP
&& keyCode == KeyEvent.KEYCODE_BACK) {
// Toast.makeText(context, "clicked", Toast.LENGTH_LONG)
// .show();
backPressed();
return true;
}
return false;
}
});
}
protected abstract void backPressed();
}
and override onBackPressed()in your fragment something like this
public class TestFragment extends BaseFragments {
#Override
public int setContentView() {
return R.layout.weblayout;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.weblayout, container, false);
cabmoneyview = (WebView) rootView.findViewById(R.id.webview);
return rootView;
}
#Override
protected void backPressed() {
// TODO Auto-generated method stub
}
}

How to know when you return from a Fragment to an Activity

If I add a fragment from an Activity, and then close that fragment, how am I able to track this? The issues I am running into with this scenario are the following:
Adding a fragment does not call any Activity life cycles, so I have no onPause/onResume to bail me out
I am not starting a new Activity, so starting the Activity for results isn't viable.
Any help with this would be appreciated.
Thanks in advance.
If you use the support version, in the AppCompatActivity
#Override
protected void onResumeFragments() {
super.onResumeFragments();
}
#Override
public void onAttachFragment(Fragment fragment) {
super.onAttachFragment(fragment);
}
package com.example.keralapolice;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentManager.OnBackStackChangedListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
public class ChiefFragment extends Fragment {
View view;
// public OnBackPressedListener onBackPressedListener;
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle args) {
view = inflater.inflate(R.layout.activity_chief, container, false);
getActivity().getActionBar().hide();
view.setFocusableInTouchMode(true);
view.requestFocus();
view.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.i(getTag(), "keyCode: " + keyCode);
if (keyCode == KeyEvent.KEYCODE_BACK) {
getActivity().getActionBar().show();
Log.i(getTag(), "onKey Back listener is working!!!");
getFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
// String cameback="CameBack";
Intent i = new Intent(getActivity(), home.class);
// i.putExtra("Comingback", cameback);
startActivity(i);
return true;
} else {
return false;
}
}
});
return view;
}
}
As Neil mentioned, this can be done using getSupportFragmentManager().addOnBackStackChangedListener();
The implementation I did was the following:
getSupportFragmentManager().addOnBackStackChangedListener(
new android.support.v4.app.FragmentManager.OnBackStackChangedListener() {
public void onBackStackChanged() {
int backCount = getSupportFragmentManager().getBackStackEntryCount();
// do some logic
}
});

Go Back To Previous Page if Back is Pressed in WebView

I'm a beginner at Android Development this is my Project :
I want to go back to the previous page in the WebView.
When i run the code these are the errors :
1. Error:(67, 5) error: method does not override or implement a method from a supertype
2. Error:(75, 18) error: cannot find symbol method onBackPressed()
3. Error:(70, 13) error: cannot find symbol variable view
package com.veereshc.veer.resultapp;
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;
import android.webkit.WebViewClient;
import android.view.KeyEvent;
import com.veereshc.veer.resultapp.dummy.DummyContent;
public class WebpageDetailFragment extends Fragment {
public static final String ARG_ITEM_ID = "item_id";
private DummyContent.DummyItem mItem;
public WebpageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments().containsKey(ARG_ITEM_ID)) {
mItem = DummyContent.ITEM_MAP.get(getArguments().getString(ARG_ITEM_ID));
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_webpage_detail, container, false);
if (mItem != null) {
WebView view = (WebView) rootView.findViewById(R.id.detail_area);
view.setWebViewClient(new WebViewClient());
view.loadUrl(mItem.url);
}
return rootView;
}
#Override
public void onBackPressed(){
if(view.canGoBack()){
view.goBack();
}
else
{
super.onBackPressed();
}
}
}
There are two ways of Go Back To Previous Page if Back is Pressed in WebView:
First, override onBackPressed():
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
if (webview.canGoBack()) {
webview.goBack();
return;
} else {
super.onBackPressed();
}
}
Second, override onKeyDown:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
use onBackPressed method like this
#Override
public void onBackPressed() {
if (myWebView.canGoBack()) {
myWebView.goBack();
} else {
super.onBackPressed();
}
}

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