android webview loadurl slow - java

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

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.

make a spinner selectively translate strings

I am trying to make a spinner I have selectively translate strings on a page. I have my app set up to translate the bulk of the page based on locale languages already. In the image below, The locale language will effect the top string, but I have a spinner on my home page that has all the available android languages in it, and I want users to be able to select one of the spinner items, and as a result the bottom string in the picture below will be translated to that language. I can't find a way to set it up, all the advice I've seen so far is just how to configure the application to set up locale language's. Any direction would be greatly appreciated!
I think you can use Android-LocalizationActivity
Here a portion of its readme:
It's basic for android application to be supported multiple languages. Yeah! It's very easy because android has String Resource. Developer just had to prepare the text for different languages then android system will use itself. But frequently problem is "On-time Language Changing". Because the String Resource was designed to be depending on current device language. but if we want to change the language by click some button. It will be difficult to handle it. This problem will solved because I have created a new library to handle application language. It called "Localization Activity" library.
It's so simple to implement it. Just extend your Activity with LocalizationActivity. Here a sample code with Button:
import android.os.Bundle;
import android.view.View;
import com.akexorcist.localizationactivity.LocalizationActivity;
public class MainActivity extends LocalizationActivity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_simple);
findViewById(R.id.btn_th).setOnClickListener(this);
findViewById(R.id.btn_en).setOnClickListener(this);
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_en) {
setLanguage("en");
} else if (id == R.id.btn_th) {
setLanguage("th");
}
}
}
When user click btn_th (Thailand), all language will be translated to Thai language. So you only need to adjust it with spinner.

webpage takes a lot of time to load

In a webview in Android, I first load a webpage and then display only a part of it using some javascript commands. During the whole process a "loading" message is displayed.
Problem : It take s alot of time to load even if the internet speed is fast. (>60 sec always). How to reduce time ?
This is my WebViewClient class that I attach with the webview (and the class contains only 1 method):
#Override
public void onPageFinished(WebView view, String url){
view.loadUrl("javascript:document.getElementsByClassName('menu')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementsByClassName('gbh')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementsByClassName('input')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementsByClassName('card_title')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementsByClassName('cell_input')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementsByName('pre')[0].innerHTML=''");
view.loadUrl("javascript:document.getElementById('footer').innerHTML=''");
view.loadUrl("javascript:document.getElementsByClassName('foot')[0].innerHTML=''");
}
Sir, You could use the YSlow or Google PageLoad plugins for your browser, to get specific tips on how to improve page load and speed up your page.
By default, a WebView provides no browser-like widgets, it does not enable JavaScript and also web page errors are ignored.

Android Project with Eclipse - HTML - WebSources

I am creating an Android project with eclipse. My main on create class refers ton an HTML file so I can program my application within HTML (where I am most fluent) using this code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/www/index.html");
}
This works just fine but when I work within my .html file I cannot fetch a file from the internet. For example this line:
<img src="http://www.johndoe.gr/newpicks.jpg"
It does not return the picture I want. What do I have to do to be able to fetch data from the web into my application?
ps. the picture link I added is random and does not refer to a real picture in the Question. I use a real link on my code and it doesn't work.
#Symeon - Have to Provided the Internet Permission in Manifest File.
And to use HTML i will suggest Please use Phonegap.. import CoroDova.jar and required Permissions for phonegap.. than when u run the HTML through Phonegap on Android i will run with ease and Even u will be able to use jquery mobile and javascripts and all

android webview displaying blank page

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.

Categories