Android web-view not working properly on device back press - android

Hi I am developing android in which I am using web-view. My web-view has more than one pages inside that. So my intended functionality is like that when I press device back button it should return to previous web url and when it on last web page it should close that activity and come to previous activity. I tried it in following way which works fine on new devices but not working properly on older android versions.My code looks like:
webView = new WebView(this);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(URLManager.URL_DICOM_BACK_PRESSED_URL)) {
processBackPressed();
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (failingUrl.contains(URLManager.URL_DICOM_BACK_PRESSED_URL)) {
processBackPressed();
} else {
showError("Server unreachable");
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
runOnUiThread(new Thread() {
#Override
public void run() {
super.run();
if(!webviewLoaded) {
webviewLoaded = true;
content.removeAllViews();
content.setOrientation(LinearLayout.VERTICAL);
// LLM.addInParent(content, textView, -1001, -999, 0);
LLM.addInParent(content, webView, -1001, 0, 1);
}
}
});
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
#Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
processBackPressed();
}
}
public void processBackPressed() {
super.onBackPressed();
finish();
}
Above code works fine one new android versions but not working on older versions.
What I observe shouldOverrideUrlLoading not works on older versions.
Am I doing anything wrong? Need some help. Thank you.

Related

How to save last state when reload url in webview [duplicate]

This question already exists:
How to save form's info last time in webview
Closed 5 years ago.
1.Webview has a goback method , it can save web state when click back.
2.My layout is a Linearlayout and it has a webview on top of two button.
Every button match a url. Also I add webView.goBack() in onKeyDown method
The first url has a form, the second doesn't have a form
I wrote some info at form in first url, after I click the second button
then ,I click the first button,but the url is reload.but if when I click back
the form info is save.
I want to save those form info like when I click back button,it can save last form info
I want to save form info in last time, how to do that?
my code is here
private void checkone(String url) {
if (!Netutils.isNetworkAvalible(MyApplication.mcontext)) {
fl.removeAllViews();
webView.loadUrl(url);
webView.setVisibility(View.GONE);
webView.removeAllViews();
fl.setVisibility(View.VISIBLE);
fl.addView(mErrorView);
} else {
handler.postDelayed(new Runnable() {
#Override
public void run() {
fl.setVisibility(View.GONE);
webView.setVisibility(View.VISIBLE);
fl.removeAllViews();
}
},1000);
Map extraHeaders = new HashMap();
extraHeaders.put("Referer", "www.emiaoqian.com");
webView.loadUrl(url, extraHeaders);
settings = webView.getSettings();
settings.setBuiltInZoomControls(true);
settings.setUseWideViewPort(true);
settings.setJavaScriptEnabled(true);
settings.setSaveFormData(true);
settings.setCacheMode(WebSettings.LOAD_DEFAULT);
settings.setAppCachePath(MyApplication.mcontext.getCacheDir().getPath());
webView.setWebChromeClient(new ChomeClient(this) {
#Override
public void onProgressChanged(WebView view, int newProgress) {
currentProgress = pg1.getProgress();
if (newProgress >= 100 && !isAnimStart) {
isAnimStart = true;
pg1.setProgress(newProgress);
startDismissAnimation(pg1.getProgress());
} else {
startProgressAnimation(newProgress);
}
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
if (title.contains("404")) {
showErrorPage();
}
}
});
settings.setAllowFileAccess(true);
settings.setAllowContentAccess(true);
settings.setDomStorageEnabled(true);
String ua = webView.getSettings().getUserAgentString();
webView.getSettings().setUserAgentString(ua.replace("Android", "emiaoqian"));
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pg1.setVisibility(View.VISIBLE);
pg1.setAlpha(1.0f);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("weixin://wap/pay?")) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
//startActivityForResult(intent,233);
startActivity(intent);
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
CookieSyncManager.getInstance().sync();
} else {
CookieManager.getInstance().flush();
}
if (!(url.equals(Constants.LOGIN)) && !(url.equals(Constants.LOGINOUT))) {
if (homeTb != null && supportActionBar != null) {
supportActionBar.setDisplayHomeAsUpEnabled(false);
supportActionBar.setDisplayShowHomeEnabled(false);
homeTb.setTitle("");
}
radiogroup.setVisibility(View.VISIBLE);
nouserl.setVisibility(View.VISIBLE);
} else if (url.equals(Constants.LOGIN) || url.equals(Constants.LOGINOUT)) {
inittoolbar2();
radiogroup.setVisibility(View.GONE);
nouserl.setVisibility(View.GONE);
}
if (url.startsWith("https://wx.tenpay.com")) {
String newurl = url.substring(url.length() - 12, url.length());
LogUtil.e("--", newurl);
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
showErrorPage();
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
showErrorPage();
}
});
fixDirPath();
// webParentView = (LinearLayout) webView.getParent();
}
}
You can set :
mWebView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT); // WebSettings.LOAD_CACHE_ELSE_NETWORK
Also to Save in Specify the app cache path :
mWebView.getSettings().setAppCachePath(mContext.getCacheDir().getPath());
And tell me the result.

Android WebView issue on override url loading

I’m trying to override url loading when clicking on a link on an app WebView.
The page loads but the WebView will keep it’s last scroll position and content size.
Is there some parameter I forgot to set on the WebView to reset the content size and the scroll position on next load?
Here’s how I’m using it:
#SuppressLint("SetJavaScriptEnabled")
#AfterViews
protected void afterViews() {
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebClient());
webView.setWebChromeClient(new ChromeClient());
webView.loadUrl(url);
}
public class WebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean isValidEmail = url.startsWith("mailto:") && Patterns.EMAIL_ADDRESS.matcher(url.substring("mailto:".length())).matches();
boolean isValidPhone = url.startsWith("tel:") && Patterns.PHONE.matcher(url.substring("tel:".length())).matches();
if (url.startsWith("about:")) {
return super.shouldOverrideUrlLoading(view, url);
}
if (isValidEmail) {
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
startActivity(Intent.createChooser(sendIntent, ""));
} else {
if (isValidPhone) {
Intent dialIntent = new Intent(Intent.ACTION_DIAL, Uri.parse(url));
startActivity(Intent.createChooser(dialIntent, ""));
} else {
WebViewActivity.this.setPageTitle(url);
webView.loadUrl(url);
}
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//..
}
}
public class ChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int progress) {
//...
}
}
Thanks.
Did you try to set scroll position in onPageFinished?
#Override
public void onPageFinished(WebView view, String url) {
// other code...
view.scrollTo(0,0);
}
That should set WebView content back to top, and not on old scroll position
Edit 1:
Sometimes if the page loads for a long time this won't work properly, so we must wait for page to get fully loaded:
#Override
public void onPageFinished(WebView view, String url) {
view.postDelayed(new Runnable() {
#Override
public void run() {
webView.scrollTo(0, 0);
}
// Delay the scrollTo to make it work
}, 300);
}
Please note that webView this time is not the WebView from the method onPageFinished, but the WebView fetched from the layout (same one as in afterViews() method).
#Bojan Kopanja, my sincere apologies for misleading.
It turns out I had the webview inside a pull to refresh listener with a scrollview and removing that got rid of the problem.
Thanks for your help nevertheless.

Android back button with web view functionality not working properly

Hi I am developing android application in which I am using one web view. My web view has some data which redirect to some different link. So when I click it should come back to previous content. And finally it should close the web view when it comes to landing page. I tried it in following ways :
webView = new WebView(this);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(URLManager.URL_DICOM_BACK_PRESSED_URL)) {
processBackPressed();
return true;
} else {
return super.shouldOverrideUrlLoading(view, url);
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (failingUrl.contains(URLManager.URL_DICOM_BACK_PRESSED_URL)) {
processBackPressed();
} else {
showError("Server unreachable");
}
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
#Override
public void onBackPressed() {
if (webView != null && webView.canGoBack()) {
webView.goBack();
} else {
processBackPressed();
}
}
So problem is that whenever it is coming back to previous page it is fist showing current page and then previous page.So looks like first refresh the page and then load previous url. Am I doing anything wrong. Need Some Help. Thank you.
Try this -
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(myWebView.canGoBack()){
myWebView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}

Clicklistner in webview

The question can be a little vague, I have created a webview and showing the webpage of the URL which I get from some server. Now When i navigate to different pages , On one page there is only a button which will send me a different URL , I need that when user is on that page and click on that button the webview should hide and user continue other operation. I have read that addJavascriptInterface is needed to do this , can anyone tell me if this is possible and how to achieve this , any good tutorial will work.
I also tried this but of no use
wv.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
HitTestResult result = wv.getHitTestResult();
if (result.getType() == HitTestResult.UNKNOWN_TYPE) {
Message msg = mHandler.obtainMessage();
wv.requestFocusNodeHref(msg);
}
return false;
}
});
topupWV.setWebViewClient(new WebViewClient());
topupWV.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("XXXXX")) {
try {
URL urls = new URL(url);
query = urls.getQuery();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
}
you can do something like this for detecting click within a webview
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isNetworkConnected()) {
//DO YOU OPERATION HERE
}
return true;
}
});

webview to open sites of certain domain

I'm trying to make an app that opens all web pages of a certain site, for example www.yahoo.com, in the webview, but all other web pages in the defaultbrowser. Here is the code that I am using but can not quite get it work.
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("http://www.yahoo.com")) {
// This is my web site, so do not override; let my WebView load
// the page
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
It looks to me that this code should work, but when i load yahoo it still goes to an outside browser. Any help would be appreciated. Thanks!
Here is a different way to do it.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String urlHost = Uri.parse(url).getHost();
switch (urlHost) {
case "yahoo.com":
return false;
case "www.yahoo.com":
return false;
case "m.yahoo.com":
return false;
default:
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
getHost() usually returns just the domain name, or sometimes with www. prefixed to it. It never contains an http:// protocol AFAIK. Try using:
if ((Uri.parse(url).getHost().equals("yahoo.com")) || (Uri.parse(url).getHost().equals("www.yahoo.com")) || (Uri.parse(url).getHost().equals("m.yahoo.com"))) {
//Your code
Try this it should help you
private WebView mWebview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_yahoo);
mWebview = new WebView(this);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
final Activity activity = this;
mWebview.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#TargetApi(android.os.Build.VERSION_CODES.M)
#Override
public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
// Redirect to deprecated method, so you can use it in all SDK versions
onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
}
});
mWebview .loadUrl("http://www.yahoo.com");
setContentView(mWebview );
}
}

Categories

Resources