Android ProgessBar while loading WebView - android

In my application, I have a WebView which loads any URL from the internet. Now, sometimes due to slow networks the page takes a long time to load and the user sees only a blank screen.
I want to show a ProgressBar while the WebView gets loaded and hide the ProgessBar when the WebView gets loaded completely.
I know how to use the ProgressBar and AsyncTasks, but here is my problem.
This is the code that I use to load my WebView.
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.loadUrl(web_URL);
And this my custom WebViewClient class
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Now, if I try to show the ProgressBar using AsyncTasks then I guess I would have to give the code to load the URL in the doInBackGround() function of my AsyncTask and show the progress through the onProgressUpdate() function.
But, how do I load the URL inside the doInBackground() as doInBackground() runs on the Non-UI thread and I wont be able to use mWebView.loadUrl(web_URL) inside it.
Any suggestions? Am I missing something obvious? Please guide me.

Check the source code. Help you and solve your problem...
public class AppWebViewClients extends WebViewClient {
private ProgressBar progressBar;
public AppWebViewClients(ProgressBar progressBar) {
this.progressBar=progressBar;
progressBar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
I think it help you.
Thanks.

pass your url in this method
private void startWebView(String url) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
progressDialog = new ProgressDialog(ContestActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl(url);
}

if you want to show the progressbar every time the user loads page (and not only the first load), then you can use this:
MainActivity.java
public class MainActivity extends Activity
{
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
final ProgressDialog progressBar = new ProgressDialog(MainActivity.this);
progressBar.setMessage("Please wait...");
webView.loadUrl("https://example.org/");
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (!progressBar.isShowing()) {
progressBar.show();
}
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});
}
}
activity_main.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="0dp"
android:paddingLeft="0dp"
android:paddingRight="0dp"
android:paddingTop="0dp"
tools:showIn="#layout/activity_main">
<WebView
android:id="#+id/webView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true" />
</RelativeLayout>

Using WebChromeClient:
webView.webChromeClient = object: WebChromeClient() {
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
progressBar?.isVisible = newProgress < 100
progressBar?.progress = newProgress
}
}
In this case you can even show determined progress bar.
Using WebViewClient:
String url = "https://stackoverflow.com/questions/11241513/android-progessbar-while-loading-webview";
setProgressBarVisibility(View.VISIBLE);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
setProgressBarVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
setProgressBarVisibility(View.GONE);
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
setProgressBarVisibility(View.GONE);
}
});
webView.loadUrl(url);
Also add method:
private void setProgressBarVisibility(int visibility) {
// If a user returns back, a NPE may occur if WebView is still loading a page and then tries to hide a ProgressBar.
if (progressBar != null) {
progressBar.setVisibility(visibility);
}
}

#SuppressLint("SetJavaScriptEnabled")
private void init() {
webView = (WebView) findViewById(R.id.kamal);
webView.setBackgroundColor(0);
webView.getSettings().setJavaScriptEnabled(true);
progressDialog = new ProgressDialog(WebView_Ofline.this);
progressDialog.setMessage("Loading Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

myThanh.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(MainActivity.this,"Đang tải dữ liệu", "Vui lòng chờ...");
myThanh.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
});

This simple solution worked for me in KOTLIN:
private fun setupWebView() {
val webViewClient: WebViewClient = object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
showProgressDialog()
super.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
hideProgressDialog()
super.onPageFinished(view, url)
}
}
webView.webViewClient = webViewClient
webView.settings.javaScriptEnabled = true
webView.settings.defaultTextEncodingName = "utf-8"
}

I try dismis progress on method onPageFinished(), but not good too much, it has time delay to render webview.
try with onPageCommitVisible() better:
val progressBar = ProgressDialog(context)
progressBar.setCancelable(false)
progressBar.show()
web_container.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
progressBar.show()
return true
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
progressBar.dismiss()
}
}

Paste This in your code and add your URL
var progressDialog: ProgressDialog? = null
private fun startWebView(url: String) {
val settings = webView.getSettings()
settings.setJavaScriptEnabled(true)
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY)
webView.getSettings().setBuiltInZoomControls(true)
webView.getSettings().setUseWideViewPort(true)
webView.getSettings().setLoadWithOverviewMode(true)
progressDialog = ProgressDialog(this)
progressDialog!!.setMessage("Loading...")
progressDialog!!.show()
webView.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return true
}
override fun onPageFinished(view: WebView, url: String) {
if (progressDialog!!.isShowing()) {
progressDialog!!.dismiss()
}
}
override fun onReceivedError(view: WebView, errorCode: Int, description: String, failingUrl: String) {
Toast.makeText(this#MainActivity, "Error:$description", Toast.LENGTH_SHORT).show()
}
})
webView.loadUrl(url)
}

You can use something like that:
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
super.onPageStarted(view, url, favicon)
binding.pbLoader.visibility = ProgressBar.VISIBLE
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
binding.pbLoader.visibility = ProgressBar.GONE
}

WebView webView;
ProgressDialog progressDialog;
TextView text;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
String message = getIntent().getStringExtra("key").toString();
setTitle(message);
Bundle isNetworkAvailable = getIntent().getExtras();
String value = "file:///android_asset/n/o/i/no_connection.html";
if (isNetworkAvailable()) {
value = isNetworkAvailable.getString("keyHTML");
}
webView = (WebView) findViewById(R.id.kamal);
webView.loadUrl(value);
init();
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void init() {
webView = (WebView) findViewById(R.id.kamal);
webView.getSettings().setBuiltInZoomControls(true);
webView.setBackgroundColor(0);
webView.getSettings().setJavaScriptEnabled(true);
progressDialog = new ProgressDialog(WebView_Online.this);
progressDialog.setMessage("Loading Please wait...");
progressDialog.setCancelable(false);
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
try {
progressDialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}

A better way to showing loader when page is loading in Webview
I created a loader in BaseActivity :-
lateinit var loader: Dialog
loader = Loader.getLoader(this)
in Webview Activity
webView.settings.javaScriptEnabled = true
webView.addJavascriptInterface(MyJavaScriptInterface(this#MbWayWebViewActivity), "HtmlViewer")
webView.settings.setSupportZoom(true)
webView.settings.builtInZoomControls = true
webView.webViewClient = object : WebViewClient() {
#Deprecated("Deprecated in Java")
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
loader.show()
return false
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
loader.dismiss()
binding.webView.loadUrl("javascript:HtmlViewer.showHTML" + "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');")
}
}
show loader in shouldOverrideUrlLoading method and dismiss loader inside onPageFinished.
Hope your problem resolve ..

Related

Android Webview throws "err_SSL_VERSION_INTERFERENCE" when resumed after inactivity

I am making an app which has a webview inside a fragment! The webview shows a https website and it works fine!
But when I use the app after sometime, it throws "err_SSL_VERSION_INTERFERENCE". The only way I can resume it is by force closing the app and restarting it.
Is there any way to handle this exception and reload the page?
The code I am using for the webview segment is this: -
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl(webUrl);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
progressBar.setVisibility(View.VISIBLE);
progressDialog.show();
if(newProgress==100){
progressBar.setVisibility(View.GONE);
progressDialog.dismiss();
}
super.onProgressChanged(view, newProgress);
}
});
}
Error log:
E/chromium: [ERROR:ssl_client_socket_impl.cc(947)] handshake failed; returned -1, SSL error code 1, net_error -101
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
Any help will be appreciated! Thanks
Below this code worked for me.
val webView = view.findViewById<View>(R.id.webview_payment) as WebView
webView.isVerticalScrollBarEnabled = true;
webView.loadUrl(requireArguments().getString("redirect_url")!!)
val settings: WebSettings = webView.settings
settings.allowUniversalAccessFromFileURLs = true
settings.javaScriptEnabled = true
settings.javaScriptCanOpenWindowsAutomatically = true
settings.cacheMode = WebSettings.LOAD_NO_CACHE
settings.setAppCacheEnabled(false)
settings.domStorageEnabled = true
// webView.webViewClient = WebViewClient()
webView.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
val url = request?.url.toString()
view?.loadUrl(url)
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageFinished(view: WebView?, url: String?) {
webView.visibility = View.VISIBLE
Log.e("CurrentUrl", "ur :" + url.toString())
super.onPageFinished(view, url)
}
override fun onReceivedError(
view: WebView,
request: WebResourceRequest,
error: WebResourceError
) {
super.onReceivedError(view, request, error)
}
}

Adding a Progress Dialog in a webview

I have been trying to incorporate a progress dialog into my app when pages are loading in the webview so there isn't just a blank white screen. I know this question is posted everywhere but I can't seem to figure out anything that works for me. I am new to programming and working with android so any information would be helpful. Below is the code that I currently have now. With the onPageStarted I am getting a compile error for Bitmap and I'm not sure what the problem is. Thanks.
public class Grades extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//requesting system settings
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().requestFeature( Window.FEATURE_PROGRESS);
WebView webview = new WebView(this);
//web settings
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setDisplayZoomControls(true);
webSettings.setBuiltInZoomControls(true);
setContentView(webview);
//loads webpages in webview instead of launching browser
webview.setWebViewClient(new WebViewClient() {
ProgressDialog prDialog;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
prDialog = ProgressDialog.show(Grades.this, null, "loading, please wait...");
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
prDialog.dismiss();
super.onPageFinished(view, url);
}
});
//loading webpage
webview.loadUrl("page__link");
}
Check this code,
final ProgressDialog pd = ProgressDialog.show(OnlinePaymentActivity.this, "", "Please wait, your transaction is being processed...", true);
WebView mWebview = (WebView)findViewById(R.id.webView1);
mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript
mWebview.getSettings().setLoadWithOverviewMode(true);
mWebview.getSettings().setUseWideViewPort(true);
mWebview.getSettings().setBuiltInZoomControls(true);
mWebview.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pd.show();
}
#Override
public void onPageFinished(WebView view, String url) {
pd.dismiss();
String webUrl = mWebview.getUrl();
}
});
mWebview .loadUrl("www.google.com");
Webview with progress dialog working for me. full working code
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import com.yubrajpoudel.R;
/**
* Created by yubraj on 12/25/15.
*/
public class NewsActivity extends AppCompatActivity {
private WebView webView;
ProgressDialog prDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_news);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
webView = (WebView) findViewById(R.id.wv_news);
webView.setWebViewClient(new MyWebViewClient());
String url = "http://google.com/";
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.loadUrl(url);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
prDialog = new ProgressDialog(NewsActivity.this);
prDialog.setMessage("Please wait ...");
prDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
}
}
Try this and I hope, this is what you are after
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
//Also you can show the progress percentage using integer value 'progress'
if(!prDialog.isShowing()){
prDialog = ProgressDialog.show(Grades.this, null, "loading, please wait...");
}
if (progress == 100&&prDialog.isShowing()) {
prDialog.dismiss();
}
}
});
Kotlin web view with progress dialog working for me. full working code
var webView = web_view_privacy_policy
webView?.settings?.javaScriptEnabled = true
webView?.settings?.loadWithOverviewMode = true
webView?.settings?.useWideViewPort= true
webView.webViewClient = object : WebViewClient(){
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
showProgress(getString(R.string.please_wait))
}
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
hideProgress()
}
}
webView.loadUrl(ApiEndPoint.ENDPOINT_PRIVACY_POLICY)
web_view_privacy_policy is id of WebView in .xml

How to show a loading bar when rendering with Webview.loadUrl in android?

When using webview to show html pages,
there will be several seconds of blank page before it finished rendering.
For better user experience, is there a way to make it show a loading image during that several seconds?
Try this
......
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);
}
});
...
Try this segment of code. Show a progressDialog or image or layout whatever you want in onPageStarted() & hide in onPageFinished()
webview.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
// TODO show you progress image
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url)
{
// TODO hide your progress image
super.onPageFinished(view, url);
}
});
Try this code to show a ProgressDialog
webView.setWebChromeClient(new WebChromeClient() {
private ProgressDialog mProgress;
#Override
public void onProgressChanged(WebView view, int progress) {
if (mProgress == null) {
mProgress = new ProgressDialog(getActivity());
mProgress.show();
}
mProgress.setMessage("Loading " + String.valueOf(progress) + "%");
if (progress == 100) {
mProgress.dismiss();
mProgress = null;
}
}
});
Simple code for Java--
webView.setWebViewClient(new WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
pdialog.show();
}
#Override
public void onPageFinished(WebView view, String url)
{
pdialog.hide();
});
This is what worked for me in KOTLIN:
private fun setupWebView() {
val webViewClient: WebViewClient = object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
showProgressDialog()
super.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
hideProgressDialog()
super.onPageFinished(view, url)
}
}
webView.webViewClient = webViewClient
webView.settings.defaultTextEncodingName = "utf-8"
}

Add a Progress Bar in WebView

I am trying to add a progress/loading bar to my application that uses WebView. I am confused on how to implement a progress bar that appears every time a link is clicked.
Current code:
public class CULearnBrowser extends Activity {
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("https://culearn.colorado.edu/webct/entryPageIns.dowebct");
}
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
webview.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Activity layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
</LinearLayout>
I have added few lines in your code and now its working fine with progress bar.
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main );
// Makes Progress bar Visible
getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
webview = (WebView) findViewById(R.id.webview);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
//Make the bar disappear after URL is loaded, and changes string to Loading...
setTitle("Loading...");
setProgress(progress * 100); //Make the bar disappear after URL is loaded
// Return the app name after finish loading
if(progress == 100)
setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new HelloWebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");
pass your url in this method
private void startWebView(String url) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
progressDialog = new ProgressDialog(ContestActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(ContestActivity.this, "Error:" + description, Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl(url);
}
in oncreate method where you have set your Webview.
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);
web_view = (WebView) findViewById(R.id.web_view);
pd = new ProgressDialog(SiteOpenInWebView.this);
pd.setMessage("Please wait Loading...");
pd.show();
web_view.setWebViewClient(new MyWebViewClient());
web_view.loadUrl("ur site name");
}
WebViewClient
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if (!pd.isShowing()) {
pd.show();
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("on finish");
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Here is the code that I am using:
Inside WebViewClient:
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
findViewById(R.id.progress1).setVisibility(View.GONE);
}
Here is the XML :
<ProgressBar
android:id="#+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Hope this helps..
The best approch which worked for me is
webView.setWebViewClient(new WebViewClient() {
#Override public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
mProgressBar.setVisibility(ProgressBar.VISIBLE);
webView.setVisibility(View.INVISIBLE);
}
#Override public void onPageCommitVisible(WebView view, String url) {
super.onPageCommitVisible(view, url);
mProgressBar.setVisibility(ProgressBar.GONE);
webView.setVisibility(View.VISIBLE);
isWebViewLoadingFirstPage=false;
}
}
Put a progress bar and the webview inside a relativelayout and set the properties for the progress bar as follows,
Make its visibility as GONE.
CENTRE it in the Relativelayout.
and then in onPageStarted() of the webclient make the progress bar visible so that it shows the progressbar when you have clicked on a link. In onPageFinished() make the progress bar visiblility as GONE so that it disappears when the page has finished loading... This will work fine for your scenario. Hope this helps...
I try dismis progress on method onPageFinished(), but not good too much, it has time delay to render webview.
try with onPageCommitVisible() better:
val progressBar = ProgressDialog(context)
progressBar.setCancelable(false)
progressBar.show()
val url = "your url here"
web_container.settings.javaScriptEnabled = true
web_container.loadUrl(url)
web_container.webViewClient = object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
progressBar.show()
return true
}
override fun onPageFinished(view: WebView?, url: String?) {
super.onPageFinished(view, url)
}
override fun onPageCommitVisible(view: WebView?, url: String?) {
super.onPageCommitVisible(view, url)
progressBar.dismiss()
}
}
web_container.setOnKeyListener(View.OnKeyListener { _, keyCode, event ->
if (keyCode == KEYCODE_BACK && event.action == MotionEvent.ACTION_UP
&& web_container.canGoBack()) {
web_container.goBack()
return#OnKeyListener true
}
return#OnKeyListener false
})
You can try this code into your activity
private void startWebView(WebView webView,String url) {
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
public void onLoadResource (WebView view, String url) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(SponceredDetailsActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
}
public void onPageFinished(WebView view, String url) {
try{
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
}catch(Exception exception){
exception.printStackTrace();
}
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Call this method using this way:
startWebView(web_view,"Your Url");
Sometimes if URL is dead it will redirected and it will come to onLoadResource() before onPageFinished method. For this reason progress bar will not dismis. To solve this issue see my this Answer.
Thanks :)

how to show progress bar on webview?

I am trying to open a webpage in my application using WebView. When I open webpage it shows me blank screen for a while and then open that page in browser inside my application.
Anyone suggest me how to show progress or get rid of that blank screen which comes during loading of webview?
I am using following code:
WebView mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);
// error handling
final Activity activity = this;
mWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
// error handling
mWebView.loadUrl(URL);
mWebView.setWebViewClient(new HelloWebViewClient());
Try this:
getWindow().requestFeature(Window.FEATURE_PROGRESS);
WebView mWebView = (WebView) findViewById(R.id.mywebview);
mWebView.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle("My title");
}
});
mWebView.loadUrl(URL);
Here is the code that I am using:
Inside WebViewClient:
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
findViewById(R.id.progress1).setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
findViewById(R.id.progress1).setVisibility(View.GONE);
}
});
Here is the XML :
<ProgressBar
android:id="#+id/progress1"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Hope this helps..
You need to do something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_PROGRESS);
this.setProgressBarVisibility(true);
}
And then
final Activity activity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100);
}
});
Update
I know it is a bit too late but I have little side note: you shouldn't use setWebViewClient() twice. Second call cancels the first call so you wouldn't get error handling.
1. In oncreate ur call AsyncTask.
2. In asynctask u just make progress dialog and show progress dialog.
3. In webview client u just show again progress dialog click on any link of web site which open in ur webview and after complete load link we override method onPageFinished and in this method we dismiss the progress dialog.
oncreate
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.web_view);
web_view = (WebView) findViewById(R.id.web_view);
OpenWebSiteInWebView opensite = new OpenWebSiteInWebView();
opensite.execute();
}
AsyncTask
private class OpenWebSiteInWebView extends AsyncTask<String, Void, String> {
#SuppressWarnings("deprecation")
#SuppressLint("SetJavaScriptEnabled")
#Override
protected String doInBackground(String... params) {
web_view.setWebViewClient(new MyWebViewClient());
web_view.loadUrl("ur site name");
return null;
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onPreExecute() {
pd = new ProgressDialog(SiteOpenInWebView.this);
pd.setMessage("Please wait Loading...");
pd.show();
}
}
WebViewClient
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if (!pd.isShowing()) {
pd.show();
}
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
System.out.println("on finish");
if (pd.isShowing()) {
pd.dismiss();
}
}
}
Here is the code I'm using in KOTLIN:
private fun setupWebView() {
val webViewClient: WebViewClient = object: WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {
view?.loadUrl(request?.url.toString())
return super.shouldOverrideUrlLoading(view, request)
}
override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
showProgressDialog()
super.onPageStarted(view, url, favicon)
}
override fun onPageFinished(view: WebView?, url: String?) {
hideProgressDialog()
super.onPageFinished(view, url)
}
}
webView.webViewClient = webViewClient
webView.settings.javaScriptEnabled = true
webView.settings.defaultTextEncodingName = "utf-8"
}

Categories

Resources