I am getting this error on pressing volume button - android

I have created a webview app. On pressing volume keys, my app crashes. This is the error in logcat
W/ViewRootImpl[MainActivity]: Cancelling event due to no window focus:
KeyEvent { action=ACTION_UP, keyCode=KEYCODE_VOLUME_DOWN,
scanCode=114, metaState=0, flags=0x28, repeatCount=0,
eventTime=196583031, downTime=196582864, deviceId=9, source=0x101 }
Below is my MainActivity.java file:
package app.freeairdrop.io;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity{
private ProgressBar progressBar;
private WebView webView;
private SwipeRefreshLayout mySwipeRefreshLayout;
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
webView.loadUrl("http://freeairdrop.io/");
mySwipeRefreshLayout = (SwipeRefreshLayout)this.findViewById(R.id.swipeContainer);
mySwipeRefreshLayout.setOnRefreshListener(
new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
webView.reload();
mySwipeRefreshLayout.setRefreshing(false);
}
}
);
}
private class WebViewClientDemo extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri = Uri.parse(url);
if (uri.getHost() != null && (url.startsWith("https://freeairdrop.io/") || url.startsWith("https://www.freeairdrop.io/"))) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
// This method is used to detect back button
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
// Let the system handle the back button
super.onBackPressed();
}
}
}

Remove
finish();
from here :
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish();
}

add focus to webview using:
<WebView android:id="#+id/webview"
android:layout_weight="1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="true"/>
Or
webview.requestFocus(View.FOCUS_DOWN|View.FOCUS_UP);

Remove call to finish() from here,
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
webView.goBack();
return true;
}
else {
finish(); // Remove this, onBackPressed() should handle it.
}
return super.onKeyDown(keyCode, event);
}

Related

can webview start an activity onReceivedError?

I am trying to start an activity (Errorpage) when webview failed to load content.But there is no error during the build, but the app closes, while inernet is off. It was supposed to launh the Errorpage activity.
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.appcompat.app.AppCompatActivity;
public class smwebview extends AppCompatActivity {
private WebView webview;
private ProgressBar spinner;
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView; //added for back buton override
public boolean mShouldPause = false;
String fullurl;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smwebview);
getIntent();
fullurl= getIntent().getStringExtra("full_url");
webview = (WebView) findViewById(R.id.webView_Latest);
webview.setWebViewClient(new CustomWebViewClient());
spinner = (ProgressBar)findViewById(R.id.progressBar2);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// keep screen on
webview.loadUrl(fullurl);
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onLoadResource(WebView webview, String url) {
super.onLoadResource(webview, url);
if (url.contains("youtube.com")) mShouldPause = true;
}
public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
Intent intent7 = new Intent(smwebview.this,Errorpage.class);
startActivity(intent7);
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onResume()
{
super.onResume();
webview.onResume();
}
#Override
public void onPause() {
super.onPause();
if(mShouldPause){
webview.onPause();
}
mShouldPause = false;
}
#Override
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 {
super.onBackPressed();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If anybody have any idea Please help me. Also please comment your suggestions on the code/logic. (I am very new to android programming)
Internet if off. Its different scenario you must add check internet connection before load.
Or onRwleceiveError is different case. When you load wrong url or utl you entered is not working

How do I make my webview in android responsive to jquery and other js library

Hello stackoverflowers,
I created an android webView app for one of my partner website.
The website is mobile responsive.
Now we decided to develop an app webview android version for the website and we noticed, some slight changes which will affect user experience which are:
1) The nav menu is sticky on the brower and mobile browser but on the android webview, it is not sticky.
2) The popUp tour dialog is not positioning correctly on the webView.
I will attach screenshots
I will appreciate if I can get helps, hints on how to solve it. We tried to create the app on web2app platform and it works just fine.
web2App demo version
Android webView not responsive
The website link is tweecampus.com
package com.gaspercloud.tweecampus;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.res.ResourcesCompat;
import com.daimajia.androidanimations.library.Techniques;
import com.daimajia.androidanimations.library.YoYo;
public class WebViewActivity extends AppCompatActivity {
private WebView webView;
private Context context;
private ProgressBar progressBar;
private float m_downX;
// private PullToRefreshView mPullToRefreshView;
private int REFRESH_DELAY = 3000;
private ImageView logo;
private String DEFAULT_ERROR_PAGE_PATH = "file:///android_asset/html/default_error_page.html";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
context = this;
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setLogo(R.drawable.t_icon_white60x60);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
progressBar = findViewById(R.id.progressBar);
webView = findViewById(R.id.webView);
initWebView();
webView.loadUrl(https://tweecampus.com);
/*
mPullToRefreshView = findViewById(R.id.pull_to_refresh);
mPullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener() {
#Override
public void onRefresh() {
mPullToRefreshView.postDelayed(new Runnable() {
#Override
public void run() {
webView.loadUrl(webView.getUrl());
mPullToRefreshView.setRefreshing(false);
}
}, REFRESH_DELAY);
}
});*/
}
private void initWebView() {
webView.setWebChromeClient(new MyWebChromeClient(context));
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
logo.setVisibility(View.VISIBLE);
invalidateOptionsMenu();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
logo.setVisibility(View.GONE);
invalidateOptionsMenu();
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
view.stopLoading();
try {
view.clearView();
} catch (Exception e) {
}
view.loadUrl("about:blank");
progressBar.setVisibility(View.GONE);
logo.setVisibility(View.GONE);
invalidateOptionsMenu();
webView.loadUrl(DEFAULT_ERROR_PAGE_PATH);
webView.clearHistory();
}
});
webView.clearCache(true);
webView.clearHistory();
webView.requestFocus();
webView.getSettings().setLoadsImagesAutomatically(true);
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setScrollbarFadingEnabled(false);
//webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setSavePassword(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
//this is to reload webPage via JavaScript
webView.addJavascriptInterface(new SimpleWebJavascriptInterface(this, webView), "Android");
webView.setHorizontalScrollBarEnabled(false);
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getPointerCount() > 1) {
//Multi touch detected
return true;
}
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: {
// save the x
m_downX = event.getX();
}
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
// set x so that it doesn't move
event.setLocation(m_downX, event.getY());
}
break;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.browsermenu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (!webView.canGoBack()) {
menu.getItem(0).setEnabled(false);
menu.getItem(0).getIcon().setAlpha(130);
} else {
menu.getItem(0).setEnabled(true);
menu.getItem(0).getIcon().setAlpha(255);
}
if (!webView.canGoForward()) {
menu.getItem(1).setEnabled(false);
menu.getItem(1).getIcon().setAlpha(130);
} else {
menu.getItem(1).setEnabled(true);
menu.getItem(1).getIcon().setAlpha(255);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == android.R.id.home) {
finish();
}
if (item.getItemId() == R.id.action_back) {
back();
}
if (item.getItemId() == R.id.action_forward) {
forward();
}
return super.onOptionsItemSelected(item);
}
private void back() {
if (webView.canGoBack()) {
webView.goBack();
}
}
private void forward() {
if (webView.canGoForward()) {
webView.goForward();
}
}
private class MyWebChromeClient extends WebChromeClient {
Context context;
public MyWebChromeClient(Context context) {
super();
this.context = context;
}
}
#Override
protected void onResume() {
super.onResume();
if (webView.canGoBack()) {
webView.goBack();
} else if (webView.canGoForward()) {
webView.reload();
} else {
webView.loadUrl(getString(R.string.tweecampuswebsite));
}
}
#Override
public void onBackPressed() {
if (webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}

Android onBackPressed issue

I created a basic webview app following instructions from web.
everything works well except the backpress button, when webview connected to server backpress goes to home screen, but when i clicked the home in menu items (search and aboutpage) the app closed.
Here is my code
MainActivity.java
package com.dijitalyayincim.cekmekoy.cekmekoy_web;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
private WebView webView;
private boolean isRedirected;
private ProgressBar progress;
String url = "file:///android_asset/www/index.html";
String url1 ="http://www.cekmekoy.info/index.php?option=com_sppagebuilder&view=page&id=12";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//setContentView(R.layout.aa);
webView = (WebView) findViewById(R.id.webView);
startWebView(webView, url);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.action_info:
Element adsElement = new Element();
adsElement.setTitle("Advertise with us");
View aboutPage = new AboutPage(this)
.isRTL(false)
.setImage(R.drawable.logo_cekmekoy)
.addItem(new Element().setTitle("Version 1.0"))
.addItem(adsElement)
.addGroup("Bize Ulaşın")
.addEmail("info#cekmekoy.info")
.addWebsite("http://www.cekmekoy.info/")
.addFacebook("cekmekoyinfo")
.addTwitter("cekmekoyinfo")
.addYoutube("UCYt3Z595jctz5oUhg0SMLqQ")
.addInstagram("cekmekoy_info")
.create();
setContentView(aboutPage);
setTitle("Bize Ulaşın");
return true;
case R.id.action_search:
setContentView(R.layout.test);
webView = (WebView) findViewById(R.id.search);
startWebView(webView, url1);
setTitle("Arama");
default:
// If we got here, the user's action was not recognized.
// Invoke the superclass to handle it.
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(intent);
view.reload();
return true;
}
view.loadUrl(url);
isRedirected = true;
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
isRedirected = false;
}
public void onLoadResource (WebView view, String url) {
if (!isRedirected) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Yükleniyor...");
progressDialog.show();
}
}
}
public void onPageFinished(WebView view, String url) {
MainActivity.this.setTitle(view.getTitle());
try{
isRedirected=true;
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
}
i really appreciate if you can help
thanks...
#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);
}
Use this code. Hope help you.
Comment this finish line.and use your method. webView.goBack();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// finish();
return true;
}
}

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

backbutton on my android webview

I tried to add a back button to my android webview but i've got this error:
The method onBackPressed() of type new WebViewClient(){} must override or implement a supertype method
This is my Java file:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
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("Loading...");
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)
{
// Handle the error
}
#Override
public void onBackPressed() {
// do something on back.
return;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://example.com");
}
}
Thanks for your help.
According to the doc, there is no onBackPressed method in the WebViewClient class. Did you want to Override it on your activity ?
try smthing like this:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webView;
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) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
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)
{
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://example.com");
}
#Override
public void onBackPressed (){
if(webView.canGoBack()) webView.goBack();
else super.onBackPressed();
}
}
You have to override the onkeyDown() method in your Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true){
mWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Try this
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
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) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://example.com");
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
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)
{
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if(mWebView.canGoBack() == true)
webview.goBack();
else finish();
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
}
And this method should be override in Activty.
WebView webView = (WebView) findViewById(R.id.webview);
Change it to:
webView = (WebView) findViewById(R.id.webview);
and then use the second answer - works like a charm!

Categories

Resources