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)
}
}
Related
I have gone through every related post I found here and still can't get it to work.
I'm opening my WebView with a URL that has redirects (sometimes many redirects) and I want to know when the loading is really finished (URL finished loading with no more redirects).
So any suggestions?
Every post I read said to override shouldOverrideUrlLoading but no matter what I do shouldOverrideUrlLoading does not get called.
My code:
mWebView = (WebView) findViewById(R.id.webview);
WebSettings settings = mWebView.getSettings();
settings.setLoadWithOverviewMode(true);
settings.setJavaScriptEnabled(true);
settings.setLoadsImagesAutomatically(true);
mWebView.setVerticalScrollBarEnabled(false);
mWebView.setHorizontalScrollBarEnabled(false);
mWebView.setWebViewClient(new MyWebViewClient());
mUrl = "http://cdn.something.com/something.html";
// mUrl = "https://www.google.com";
mWebView.loadUrl(mUrl);
public class MyWebViewClient extends WebViewClient {
public MyWebViewClient() {}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
Log.d(TAG, "WebViewClient: shouldOverrideUrlLoading");
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
Log.d(TAG, "WebViewClient: onPageStarted: url: " + url);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d(TAG, "WebViewClient: onPageFinished: url: " + url);
super.onPageFinished(view, url);
}
}
Thank you
you are overriding the new shouldOverrideUrlLoading method which was added in android N,
you have to override both methods to make it work (old one which is deprecated and new one)
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
final Uri uri = Uri.parse(url);
return handleUri(uri);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
final Uri uri = request.getUrl();
return handleUri(uri);
}
refer this
,and onPageFinished will be called when page has finished loading
In my case WebViewClient wasn't showing if there was changes on the webview, I supposed that is something about the web that is been running.
I could get that information from the WebChromeClient with OnProgressChanged, I don't know if this would help people anyway, but here is the code:
webview.webChromeClient = object : WebChromeClient(){
override fun onProgressChanged(view: WebView?, newProgress: Int) {
super.onProgressChanged(view, newProgress)
if (newProgress == 100) {
Log.d("testing", webview.getOriginalUrl())
Log.d("testing", webview.url)
}
}
}
This way I could know what is been loaded and when is finished.
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.
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 ..
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"
}
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"
}