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 :)
Related
I am using android in that I am calling a link via webview. Now, the problem is that whenever I click any button or call any page of that link at that time after some second progress bar coming i.e. progress bar performance is delay while load anything.
From this problem user can't know that button/link has been clicked or not, without getting any progress bar sign, and hence from that user clicked many times that button/link.
Here is my android code of MainActivity.java,
public class MainActivity extends AppCompatActivity {
WebView webView;
ProgressBar bar;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bar = (ProgressBar)findViewById(R.id.progressBar2);
webView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setAppCacheEnabled(true);
webView.setWebViewClient(new myWebClient());
webView.loadUrl("http://florro-001-site2.etempurl.com/");
}
public class myWebClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
view.setVisibility(webView.VISIBLE);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
bar.setVisibility(View.VISIBLE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean overrideUrlLoading = false;
view.loadUrl(url);
return true;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()){
webView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
I searched many things but related topics I didn't get.
use bar.setVisibility(View.VISIBLE); in the shouldOverrideUrlLoading not in onPageStarted try to use like that
public class myWebClient extends WebViewClient{
#Override
public void onPageFinished(WebView view, String url) {
bar.setVisibility(View.GONE);
view.setVisibility(webView.VISIBLE);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
boolean overrideUrlLoading = false;
view.loadUrl(url);
bar.setVisibility(View.VISIBLE);
return true;
}
}
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);
}
}
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 ..
Simply put how can I make a progress dialog show up every time a new link is clicked in my webview. I have tried many tutorials and methods but every one of them only shows the dialog once, when the app is initially loaded.
Here is my code
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
ProgressDialog dialog = ProgressDialog.show(myActivity.this, "",
"Loading. Please wait...", true);
#Override
public void onPageFinished(WebView view, String url) {
dialog.dismiss();
}
check out this:
wvCouponsAndOffers.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog = new ProgressDialog(CouponsWebViewUI.this);
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressDialog.setMessage(StringConstants.PROGRESS_DIALOG_MSG);
progressDialog.setCancelable(false);
progressDialog.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
}
else
return false;
}});
progressDialog.show();
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressDialog.setMessage(StringConstants.PROGRESS_DIALOG_MSG);
progressDialog.setCancelable(false);
progressDialog.setOnKeyListener(new OnKeyListener(){
#Override
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if(keyCode == KeyEvent.KEYCODE_SEARCH) {
return true;
}
else
return false;
}});
progressDialog.show();
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
});
Try this,
// Let's display the progress in the activity title bar, like the
// browser app does.
getWindow().requestFeature(Window.FEATURE_PROGRESS);
webview.getSettings().setJavaScriptEnabled(true);
final Activity activity = this;
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
// Activities and WebViews measure progress with different scales.
// The progress meter will automatically disappear when we reach 100%
activity.setProgress(progress * 1000);
}
});
webview.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
webview.loadUrl("http://slashdot.org/");
And if you want to make your own progressDialog then
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// Start PROGRESS DIALOG
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//HIDE PROGRESS DIALOG LOADING IT HAS FINISHED
}
});
And let me know what happen..
Try this easiest one,it work for me
public class HomeWebViewActivity extends AppCompatActivity{
private String weburl;
private WebView webview;
private Toolbar toolbar;
private ProgressDialog prDialog;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_webview_activity);
toolbar = (Toolbar) findViewById(R.id.toolbar_homewebview);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
weburl="ADD YOUR URL HERE";
webview = (WebView) findViewById(R.id.webviewinfo);
webview.setWebViewClient(new WebVwClientcls());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webview.loadUrl(weburl);
}
private class WebVwClientcls 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(HomeWebViewActivity.this);
prDialog.setMessage("Please wait ...");
prDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
}
}
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"
}