android webview displaying blank page - java

I have an android application that I am developing using the emulator running on android 2.3.3 with an embedded WebView in a framelayout nested in a linearlayout (vertical). No matter what code I use it never actually does anything. I have Permissions on the android application set to INTERNET.
Even when trying to load just the HTML code. I get a blank white page, no errors no nothing. Nothing in logcat as well.
WebView wview = (WebView)findViewById(R.id.webView1);
wview.getSettings().setJavaScriptEnabled(true);
I have tried all three of these to attempt to load anything into the webview:
wview.loadUrl("http://www.google.com");
wview.loadData("<HTML><BODY><H3>Test</H3></BODY></HTML>","text/html","utf-8");
wview.loadDataWithBaseURL(null, "<HTML><BODY><H3>Test</H3></BODY></HTML>","text/html","utf-8",null);
All three give me the same results. Nothing.
Any ideas?

WebSettings settings = wbView.getSettings();
settings.setDomStorageEnabled(true);

It might be a bit too late, but I wanted to share my experience with you, because I had the same problem and spent a lot of time on it.
Put your WebView in RelativeLayout and not in FrameLayout.
What I have tested: My WebView's onPageFinished() was called every time, but on the screen I got blank page.
From chrome://inspect WebView debugger I was able to "ping" my WebView by pressing inspect button, and after that WebView was refreshing immediately.
My thoughts - WebView isn't rendered correctly in FrameLayout, and RelativeLayout fixes the issue (even invalidate() and requestLayout() calls didn't help).

I think if you edit some of your code then it will be ok.Look how i do it in my case below.Try for you in this way..
For displaying a web page
final WebView wbView = (WebView) findViewById(R.id.WebView);
WebSettings settings = wbView.getSettings();
settings.setJavaScriptEnabled(true);
wbView.loadUrl("https://play.google.com/store/apps");
wbView.clearView();
wbView.measure(100, 100);
settings.setUseWideViewPort(true);
settings.setLoadWithOverviewMode(true);
For showing HTML:
See this tutorial..
android-tutorial-html-file-in-webview

instead of passing null, you should pass an empty String to it. ex: ""
So you should call it like this:
wview.loadDataWithBaseURL("", "<HTML><BODY><H3>Test</H3></BODY></HTML>","text/html","utf-8","");

In my case, it was due to the fact that my webview was attempting to load a page using HTTPS where the certificate was untrusted.
You can check if this is the case in your code using the following snippet:
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
Java
override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
handler?.proceed()
}
Kotlin
Then, if it is the case, quickly remove the snippet and refer to the documentation to diagnose the problem further and potentially add the certificate to your keystore.

If it still Doesn't work then please make sure that you have added "http://" or "https://" before the web address.

I gave +1 because these were both valid assistance to getting the webview to working properly, but it was not the solution to my issue.
What I didn't realize is I had a wrap_content on the include of my webview layout and this caused it to have a height of 0px. By setting this to fill_parent I resolved the issue. (Webview with white background and app with white background you cant really tell its not full height when it shows up as full height in the layout designer.)
Thanks for your help though!

clearView is deprecated.
Use:
webView.loadUrl("about:blank")

change wrap_content to fill_parent in your webview layout. it worked for me

use ip address instead of web url then override webclient using following ssl error handling method
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}

I think What you need is WebViewClient. After setting webviewclient call webview.loadUrl(_url);
Somethin like this ....
private void loadUrlInWebView(String _URL){
WebView myWebView = (WebView) findViewById(R.id.webviewer);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setUseWideViewPort(true);
webSettings.setLoadWithOverviewMode(true);
myWebView.setWebViewClient(new MyWebViewClient());
myWebView.loadUrl(_URL);
}
private class MyWebViewClient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
}

just use loadDataWithBaseURL
loadDataWithBaseURL(null,"html content" , "text/html" , "utf-8",null)

Try increasing the RAM for your emulated device. That solved the problem for me.
I found this out by looking at the logcat messages in Android Monitor (Android Studio). The messages below gave me the idea about what was wrong to increasing RAM :
W/art: Throwing OutOfMemoryError "Failed to allocate a 6635532 byte allocation with 1170528 free bytes and 1143KB until OOM"
W/JavaBrowserViewRendererHelper: Error allocating bitmap
E/chromium: [ERROR:java_browser_view_renderer_helper.cc(132)] Error unlocking java bitmap pixels.

My webview was displaying a white blank square on top of it, sometimes totally blank. This only occurred when it was loading certain data.
Changing it to a RelativeLayout, and setting layout_height to match_parent worked for me.
<RelativeLayout xmlns:android=...
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:id="#+id/ll_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="3dp"
android:gravity="center_vertical"
android:orientation="horizontal">
.....
</RelativeLayout>
<WebView
android:id="#+id/web_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/ll_title"
android:background="#color/colorYellow" />
<ProgressBar
android:id="#+id/pb_spinning"
style="?android:attr/progressBarStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>

You can use the following code, this will be helpful:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.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;
}
}

In my case I was trying to load an html file. The solution came to be:
val webClient = object : WebViewClient() {
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, myUrl)
binding.newsWebView.stopLoading()
}
}
binding.newsWebView.webViewClient = webClient
binding.newsWebView.loadUrl(myUrl)
After the html file has been loaded, it loaded about:blank and the screen was going blank.

Related

How do I get access to the html contents of a popup displayed in a webview?

My application needs to retrieve data from a web site.
I use a webview to access the required page. In the page displayed in this webview there are links leading to the detailed info that the app needs. When following a link (using the webView.loadUrl()) a popup is displayed on top of the webview.
The app gets access to the links with the following code:
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(new BackgroundScriptInterface(), "HTMLOUT");
webView.setWebViewClient(new WebViewClient(){
#Override
public void onPageFinished(WebView view, String url)
{
webView.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
}
});
and
public class BackgroundScriptInterface {
#JavascriptInterface
public void processHTML(String html) {
...
}
But this BackgroundScriptInterface is not called when a popup displays.
How do I get access to the html contents of the popup?
EDIT
As suggested by Eddie below, I've tried
webView.evaluateJavascript(item.competDetailUrl, new ValueCallback<String>() {
#Override
public void onReceiveValue(String s) {
Log.d("competDetail", s);
}
});
The popup is still displayed as expected. However the value passed to the onReceiveValue callback is "null".
Try using webView.evaluateJavascript() instead of webView.loadUrl(), unless you need to work with pre-Kitkat devices
Reference:
Android Calling JavaScript functions in WebView
The info the app retrieves from that site do not need to be displayed on the UI. They are parsed and used in the app logic. Hence I have designed the following work-around: I have replaced the original javascript:apex.navigation.dialog() by a javascript:apex.navigation.redirect() that displays the requested info directly into the webview instead of into a popup window.
As the info now comes into the webview, it can be accessed by the above BackgroundScriptInterface.

Create an activity that has a webView in it

I'm developing an android app just for fun and practice.
The app consists of a splash screen and 4 activities.
One of the activites is filled with a webView.
I'm not able to get that webView work, when I run the app it shows only a white background.
here is my code :
https://drive.google.com/open?id=1oXHzBauNDy68mEIyI5EeNooIc9GaVPFh
Sorry to link the code in google drive, I wasn't able to properly format the question.
Any help will be appreciated
btw : activity_livechat is not a launcher activity.
First of all, enable JavaScript on your webview
Webview.getsettings().setJavaScriptEnabled(true);
Additionally, it's best to have error received methods in place for your webview so you'll know exactly what is the problem related to.
webView.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(context, "this is my error: " + description, Toast.LENGTH_LONG);
}
});

android webview loadurl slow

I am working on an application where i am loading a webpage from a an external url in a webview.
Loading the page take so much time to be loaded it take between 30 Seconds and 1 Minute
so please take look here on my code
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class WebActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
webView = (WebView)findViewById(R.id.webView);
progressBar= (ProgressBar)findViewById(R.id.progressBar2);
String link = getIntent().getExtras().getString("webLink");
String title = getIntent().getExtras().getString("webTitle");
setTitle(title);
webView.setVisibility(View.GONE);
progressBar.setVisibility(View.VISIBLE);
Log.d("WEB", link);
webView.setWebViewClient(new MyBrowser());
webView.getSettings().setJavaScriptEnabled(true);
//webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
//webView.getSettings().setDomStorageEnabled(true);
//webView.getSettings().setAppCachePath(String.valueOf(getCacheDir()));
//webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.loadUrl(link);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// app icon in action bar clicked; goto parent activity.
this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class MyBrowser extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.GONE);
}
}
}
any idea to improve the performance ?
Unofortunately, there won't be much you can do to fix this. However:
Try to load your URL in the browser on your android device. Is it faster ? If not, there's not really much you can do.
There's a couple of things you can try though, and a few things to check. Specifically:
You're setting the visibility to View.GONE (making your webview invisible) while the page is loading, and then making it visible again when the page has loaded. This is probably the problem.
Try without this, and you will probably find that it will be quicker. In my experience, onPageFinished(..) only fires some time after the page is loaded.
Does the page really require JavaScript ? If not, don't enable it.
If it's feaseable in your case, you can use a HTML parser like Jsoup to extract only the desired data from the page, and show that to the user. This will be a lot faster.
If the page uses Ajax to load data dynamically, you can also load the data directly from the endpoints it uses. Open the page in a desktop browser, and open the network tab of developer tools to find out how the page works and loads data.
You can block requests from the WebView with shouldInterceptRequest(..). This may help if the page has things like eg. Facebook share buttons or extra images which you don't need. Blocking these will speed up load times.
If you show us the URL you're using, maybe I can investigate more and tell you axactly how you could speed it up in your case. Let me know if it helps.
I think depends on the amount of data that need to download . Also keep in mind that while you are in debug mode the application is much slower as it has to to trace all information.
Maybe this links can help you to improve performance:
WebView performance
WebView performace 2
While loading URLs in your webview if you put all your static resources like CSS, JS fonts etc in your android app's local assets folter and give relative URL to your resource in page then it will load much faster.
This is because right now your webview is loading all the resource from your or third party server wherever they exists but if they are in assets folder then you can load them locally.
So over all your data and HTML will come from your server and static content will be stored and loaded locally.
You have use loadDataWithBaseURL method of webview insteed of loadUrl
Here is a detailed article which can be helpful
http://www.codewithasp.net/2016/06/speedup-android-webview-app-localise-static-resources.html

Why doesn't Android's WebView load some URLs?

My WebView doesn't show some URLs especially if it has the leading www. part missing. http://google.com doesn't load but http://www.google.com loads just fine. I don't get any exceptions or messages in the logcat so it seems rather hard to find out what's going on behind the scenes. Here's the snippet that actually displays my WebView.
WebView wbvBrowser = new WebView(this.objContext);
wbvBrowser.getSettings().setBuiltInZoomControls(true);
wbvBrowser.getSettings().setJavaScriptEnabled(true);
wbvBrowser.loadUrl("http://google.com");
Would any of you know what's causing this issue? I'm baffled.
Thanks.
Enable DOM Storage APIs
wbvBrowser.setDomStorageEnabled(true);
Make sure the app has permission to access the Internet. Add the following to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
try this...
wbvBrowser.setWebViewClient(new Callback());
private class Callback extends WebViewClient{ //HERE IS THE MAIN CHANGE.
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (false);
}
}
This worked for me: Add an 's' to the http. Make it https
wbvBrowser.loadUrl("https://google.com");

Android Webview, working with Anchors

I am loading a webpage into a webview from the database with the loadDataWithBaseURL() function and am trying to subsequently jump to an Anchor point. When I place a button just below the webview that uses the loadUrl()-function, it jumps to the Anchor point just fine. But if I place the loadUrl() after the loadDataWithBaseURL() it says page not found.
webview.loadDataWithBaseURL("app:myhtml", data, "text/html", "UTF-8", null);
webview.loadUrl("app:myhtml#tips");
I assumed it was because the load had not completed, and thus it couldn't find the Anchor, but I tried a loop to wait for it to getProgress() to equal 100, and have verified it's reaching 100 before that command executes, but it still won't find the page unless it's associated with the button click.
Any Ideas out there on how I can load a page from the database and then jump to an anchor point at the same time. I'm working with the Android 2.1 SDK.
Thanks to your help I got it to load directly to my anchor by adding this little bit of code. However I can't scroll around on the page, it starts to move and then snaps back. I suspect because it is reloading the page to that anchor each time. I'm fairly new to Android, and Java even, so this may be the wrong implementation of your suggestion, but I'd certainly appreciate a little more direction. Here is the code I used:
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webview, "app://data");
webview.loadUrl("app://data#tips");
}
});
It seems this is making an infinite loop.
Try using valid URL as a base URL in loadDataWithBaseURL(), such as app://myhtml.
Also, to make sure the data was loaded implement WebViewCLient.onPageFinished().
It was getting in an infinite onPageFinished loop before. It had nothing to do with me scrolling, it was just continuously loading the same page. This code allows it to load without without getting stuck in a loop.
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
if(url.contains("#") != true){
webview.loadUrl("app://data#tips");
}
}
});

Categories