Android : Progressbar to load url, continues to load - android

In my application, i'm using a webview to open a url. The url is very simple, it just takes secs to load. But the progress bar doesn't hide when the url loads completely. I'm not able to figure out whats wrong. please help me. Below i'm posting the code.
WebView Class
public class noti_cse extends BaseActivity {
private WebView webView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.noti_cse);
// overridePendingTransition(0, 0);
// webView = (WebView) findViewById(R.id.webcse);
// webView.setWebViewClient(new MyWebViewClient());
if (!DetectConnection.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
webView = (WebView) findViewById(R.id.webcse);
webView.setWebViewClient(new CustomWebViewClient());
webView.clearCache(true);
webView.clearHistory();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setBuiltInZoomControls(true);
startWebView("http://notify.php");
}
// webView.getSettings().setJavaScriptEnabled(true);
// startWebView("http://notify.php");
// webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
// webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
}
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
//Show loader on url load
public void onLoadResource(WebView view, String url) {
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
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);
}
private class CustomWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
}
#Override
protected boolean useDrawerToggle() {
return false;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_placements)
return true;
if (item.getItemId() == android.R.id.home)
onBackPressed();
return super.onOptionsItemSelected(item);
}

You are setting 2 WebViewClient.
First:
webView.setWebViewClient(new CustomWebViewClient());
And after that, you are calling
startWebView()
which sets a new WebviewClient.
You can change your method like below:
private void startWebView(String url) {
//Create new webview Client to show progress dialog
//When opening a url or click on link
webView.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog;
//If you will not use this method url links are opeen in new brower not in webview
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!DetectConnection.checkInternetConnection(noti_cse.this)) {
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
} else {
view.loadUrl(url);
}
return true;
}
//Show loader on url load
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon){
if (progressDialog == null) {
// in standard case YourActivity.this
progressDialog = new ProgressDialog(noti_cse.this);
progressDialog.setMessage("On the Way!!!");
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
super.onPageStarted(view, url, favicon);
}
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);
}
And remove this line form onCreate() method:
webView.setWebViewClient(new CustomWebViewClient());

Related

Ajax not working in android webview

I am loading a website in webview,we have used Ajax in website and its working fine on web browser and mobile browser also but in android webview ajax is not working no error is there in the console.Here is my code:-
public class Activity_WebView extends AppCompatActivity implements
ConnectivityReceiver.ConnectivityReceiverListener {
WebView webview;
ProgressDialog pro_dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setPluginState(WebSettings.PluginState.ON);
webview.setWebViewClient(new loadinsame());
pro_dialog = new ProgressDialog(Activity_WebView.this);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
boolean connection = checkConnection();
if (connection) {
webview.loadUrl("website url");
} else {
Toast.makeText(Activity_WebView.this, "Sorry! Not connected to
internet", Toast.LENGTH_SHORT).show();
dialog_Show(webview, "Please check you Inernet connect and Reload.",
false);
}
}
#Override
public void onNetworkConnectionChanged(boolean isConnected) {
if (!isConnected) {
Toast.makeText(Activity_WebView.this, "Sorry! Not connected to
internet", Toast.LENGTH_SHORT).show();
}
}
private class loadinsame extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
pro_dialog.setCancelable(false);
pro_dialog.setMessage("Loading...");
pro_dialog.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
pro_dialog.dismiss();
}
#Override
public void onReceivedError(final WebView webview, WebResourceRequest
request, WebResourceError error) {
super.onReceivedError(webview, request, error);
pro_dialog.dismiss();
// dialog_Show(webview, "Error Occur, Do you want to Reload?", true);
}
}
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
}
private boolean checkConnection() {
boolean isConnected = ConnectivityReceiver.isConnected();
return isConnected;
}
#Override
protected void onResume() {
super.onResume();
MyApplication.getInstance().setConnectivityListener(this);
}
}
when i inspect the website in chrome using emulator, find that my ajax remain pending and then cancel after sometime.
Thanks in advance.
Just promoting #Jeff Thomas comment, by setting
mWebView.getSettings().setDomStorageEnabled(true);
worked!!
When i enabled the java script, its working.
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("");
myWebView.getSettings().setDomStorageEnabled(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebClient());
Solutions
If you want to load web url in WebView so you need follow my code It's code working fine and In web any type of script language used in web page.
public void webviewCallBack(String coverUrl) {
WebView WebView webView = (WebView) findViewById(R.id.web_view);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setPluginState(WebSettings.PluginState.ON);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.clearView();
webView.measure(100, 100);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient() {
// For api level bellow 24
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("weburl__", url);
if (url.startsWith("http") || url.startsWith("https")) {
// Return false means, web view will handle the link
return false;
} else if (url.startsWith("tel:")) {
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
// From api level 24
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
// Get the tel: url
String url = request.getUrl().toString();
Log.d("weburl_____", url);
if (url.startsWith("http") || url.startsWith("https")) {
// Return false means, web view will handle the link
return false;
} else if (url.startsWith("tel:")) {
// Handle the tel: link
handleTelLink(url);
// Return true means, leave the current web view and handle the url itself
return true;
}
return false;
}
});
// Load the url into web view
webView.loadUrl(coverUrl);
hoadler();
}
public void hoadler() {
Runnable task = new Runnable() {
public void run() {
material_design_progressbar.setVisibility(View.VISIBLE);
}
};
worker.schedule(task, 5, TimeUnit.SECONDS);
}
I hope this code is helpful for you!
Here is how to edit the AndroidManifes.xml:
Find AndroidManifest.xml file in application folder at:
android/app/src/main/AndroidManifest.xml
Locate the application subelement.
Add the following tag:
android:usesCleartextTraffic=”true”
The application subelement should now look like:
<application
android:name=”io.flutter.app.Test”
android:label=”bell_ui”
android:icon=”#`enter code
here`mapmap/ic_launcher”
android:usesCleartextTraffic=”true”>
Save the AndroidManifest.xml file.

Progress Dialog not showing in webview

I have a webview in my android application which renders html pages from a local folder, Now I want to show progress dialog when navigating from one html page to another but the progress dialog which I am using isn't showing up. Here is my code snippet:
#JavascriptInterface
public void save(String respString, boolean ifEndNode) throws JSONException {
ProgressDialog progDialog = null;
try {
if(ifEndNode){
//start loader
progDialog = new ProgressDialog(webView.getContext());
progDialog.setMessage("Saving survey, Please DON'T close the Application!! ");
progDialog.setCanceledOnTouchOutside(false);
progDialog.setCancelable(false);
progDialog.show();
}
//some code here
//...
}
catch (Exception e)
{
Logger.e(context,"exception", "jsonObjectexception");
}
finally {
if(progDialog != null && progDialog.isShowing())
progDialog.dismiss();
}
Can anyone suggest what the problem could be?
You can use WebView with ProgressDialog this way. This is nice and simple approch.
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();
}
}
}

Android webview custom error page

I am creating application that use WebView to access a online website. I am stuck where I have to add code to check availability of page.
public class SpartanWeb extends Activity {
WebView mWebView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Adds Progrss bar Support
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
// Makes Progress bar Visible
getWindow().setFeatureInt(Window.FEATURE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
// Get Web view
mWebView = (WebView) findViewById(R.id.webView1);
WebSettings websettings = mWebView.getSettings();
websettings.setJavaScriptEnabled(true);
mWebView.stopLoading();
mWebView.clearCache(true);
mWebView.loadUrl("http://google.com");
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
});
// onProgressChanged
final Activity MyActivity = this;
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// bar disappear after URL is loaded, and changes string to
// Loading...
MyActivity.setTitle("Loading...");
MyActivity.setProgress(progress * 100); // Make the bar
// disappear after URL
// is loaded
// Return the app name after finish loading
if (progress == 100)
MyActivity.setTitle(R.string.app_name);
}
});
}// EOM oc
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I am trying to add onReceivedError but for some reason custom page is not loading.
/** Called when the activity is first created. */
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
mWebView.loadUrl("file:///android_asset/error.html");
}
Please advise what to do.
You can call loadErrorPage(view) function in the onReceivedError function.
The following code will load the error content you need to show.Here i am load the html file with loadDataWithBaseURL.
public void loadErrorPage(WebView webview){
if(webview!=null){
String htmlData ="<html><body><div align=\"center\" >"This is the description for the load fail : "+description+"\nThe failed url is : "+failingUrl+"\n"</div></body>";
webview.loadUrl("about:blank");
webview.loadDataWithBaseURL(null,htmlData, "text/html", "UTF-8",null);
webview.invalidate();
}
}
I added onReceivedError to mWebView.setWebViewClient(new WebViewClient so now it's working. Thanks for tips.
mWebView.setWebViewClient(new WebViewClient() {
#Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
mWebView.loadUrl("file:///android_asset/error.html");
} });
You can use the following code ..
public class TestResultWebclient extends WebViewClient {
ProgressDialog progressDialog;
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressDialog == null) {
progressDialog = new ProgressDialog(TermsAndCondsMrupeeActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.show();
}
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
if (progressDialog != null)
try {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
progressDialog = null;
}
} catch (Exception exception) {
exception.printStackTrace();
}
super.onPageFinished(view, url);
}
}

unable to load url in android webview

I want to load one url "http://connect.mayoclinic.org/discussions" in webview .i tried lots of ways but i am unable to load it.its showing blank page. I am using the following for this.when i use simple load url by removing other functions,then also its giving the blank page.but when i tested on webbrowser its showing the webpage. its showing on iphone also..only unable to show in android webview
this.wb = (WebView) findViewById(R.id.wb);
WebSettings settings = wb.getSettings();
settings.setJavaScriptEnabled(true);
final AlertDialog alertDialog = new AlertDialog.Builder(BrowserViewHealthAlertActivity.this).create();
progressBar = ProgressDialog.show(BrowserViewHealthAlertActivity.this, "", "Loading...");
progressBar.setCancelable(true);
progressBar.setOnKeyListener(new DialogInterface.OnKeyListener() {
#Override
public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
CommonFunction.startTimer(context);
if (keyCode == KeyEvent.KEYCODE_SEARCH && event.getRepeatCount() == 0) {
return true; // Pretend we processed it
}
if (keyCode == KeyEvent.KEYCODE_MENU && (event.getFlags() & KeyEvent.FLAG_LONG_PRESS) == KeyEvent.FLAG_LONG_PRESS) {
return true;
}
return false; // Any other keys are still
}
});
wb.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
CommonFunction.startTimer(context);
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
wb.loadUrl(link);
I have tried your URL. Its not woring in browser.
might be problem with the URL itself #asiya.
Is it giving black page still??
Check my code with another URL like www.google.com. Its my working code.
A simple Webview goes here displaying loading until URL take to load.
Webview webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
// Log.e("in", "onPageStarted" + isInternetPresent);
if (isInternetPresent) {
// Log.e("in", "if" + isInternetPresent);
progressBar.setVisibility(View.VISIBLE);
noconnection.setVisibility(View.INVISIBLE);
retry.setVisibility(View.INVISIBLE);
} else
noconnection.setVisibility(View.VISIBLE);
}
#Override
public void onLoadResource(WebView view, String url) {
super.onLoadResource(view, url);
// Log.e("in", "onloadresoure");
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
});
WebSettings webSettings = webview.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setSupportZoom(true);
webview.getSettings().setDisplayZoomControls(false);
webSettings.setJavaScriptEnabled(true);
// webview.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
webSettings.setLoadWithOverviewMode(true);
webSettings.setUseWideViewPort(true);
webview.setInitialScale(1);
if (isInternetPresent) {
isInternetPresent = true;
webview.loadUrl("http://your url");
} else {
ExitAlertClass.QuizSelectOptionAlert(ctx, "No Internet Connection"); //here goes your alert code
noconnection.setVisibility(View.VISIBLE);
retry.setVisibility(View.VISIBLE);
};
progressBar is a simple progress:
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progressBar1);
Here, I am getting status of internet usng broadcast receiver. You can make that code.

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 :)

Categories

Resources