Android WebView issue on override url loading - android

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.

Related

Android web-view not working properly on device back press

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.

Detect when #close is a part of url in WebView

I have a WebView that I'm trying to handle behavior for when #close is added to the end of a url.
The code below triggers for every load url that doesn't have #close appended to it. How do I handle for this?
WebViewClient wvc = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
return true;
}
#Override
public void onLoadResource(WebView view, String url){
if( url.equals("https:<coreofurl>/?#close") ){
// handle event - does not enter
}
}
};
webView.setWebViewClient(wvc);
Edit: I've also tried the following with no luck.
WebChromeClient wcc = new WebChromeClient() {
#Override
public void onCloseWindow(WebView window) {
// handle event - does not enter
}
};
webView.setWebChromeClient(wcc);
This seems like a "how do I tell if my url ends with x" string question, so... try this
if (url.endsWith("#close")) {
// close stuff here
}
(this would be implemented in your onLoadResource() method)

Android WebView is not shown

I am trying to open an url in a new webview (created in a non activity class).
When debugging the mContext is not null, and i am on the main thread. I can see the toast and the last print but the webview is not shown. I don't understand what i am doing wrong.. can you spot a mistake? Thank you
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(mContext, "test", Toast.LENGTH_LONG).show();
System.out.println("creating a new webview");
WebView wv = new WebView(mContext);
wv.loadUrl("urlhere");
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
System.out.println("finished loading url: " + url);
}
public void onLoadResource(WebView view, String url) {
}
public boolean shouldOverrideUrlLoading(WebView view,
String url) {
return true;
}
});
wv.setVisibility(View.VISIBLE);
System.out.println("should see the webview now");
}
});
You are creating a new WebView but not giving it a parent where it can attach and display. Or use it in a setContentView.

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

Trying to display url in Web View

I am experimenting with the loopj package. I am trying to make a HTTP request to a website and display the website in the webview.
I am successfully getting a result back, however the web view does not display the page as desired, instead chrome opens up and displays the page.
Am I missing something or is there a way I can override this unwanted behaviour?
Below is my oncreate method where I am making the request:
public class MainActivity extends Activity {
Button connectBtn;
TextView status;
WebView display;
String url = "http://www.google.com";
AsyncHttpClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
status = (TextView)findViewById(R.id.statusbox);
connectBtn = (Button)findViewById(R.id.connectBtn);
display = (WebView)findViewById(R.id.webView1);
connectBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
client = new AsyncHttpClient();
client.get(url, new AsyncHttpResponseHandler(){
#Override
public void onSuccess(String response) {
Toast.makeText(getApplicationContext(), "Success!", Toast.LENGTH_SHORT).show();
display.loadUrl(url);
}
});
}
});
}
setWebViewClient to your WebView and override shouldOverrideUrlLoading() now write view.loadUrl(url); in that method.
Just add this code,
display.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}});
You need to set a WebViewClient and override the shouldOverrideUrlLoading method. Something like this:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(final WebView view, final String url) {
view.loadUrl(url);
}
});
That makes sure that clicks on links in the WebView are handled by the WebView itself.
Edit: Actually, I misread the question. You aren't dealing with a click in the WebView itself, so this isn't relevant. Sorry!
just use this code under you webviewclient
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
final EditText editText = (EditText) findViewById(R.id.urlfield);
editText.setText(url);
}
}

Categories

Resources