I need a progress bar at the centre of my android webview it must be shown before the page loads and hides when the page is loaded. How can it be done? Can anyone help me?
This is my code for webview:
Bundle extras = getIntent().getExtras();
String title;
final String url;
if (!Datacon.checkInternetConnection(this)) {
Toast.makeText(getApplicationContext(), "Check your Internet Connection!", Toast.LENGTH_LONG).show();
} else {
if (extras != null) {
title = extras.getString("title");
url = extras.getString("url");
TextView text=(TextView) findViewById(R.id.textView1);
text.setText(title);
final WebView myWebView =(WebView)findViewById(R.id.WebView);
myWebView.loadUrl(url);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
myWebView.getSettings().setBuiltInZoomControls(true);
myWebView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
loadingProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);
myWebView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
Button refresh = (Button) actionBar.getCustomView().findViewById(R.id.but2);
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myWebView.loadUrl(url);
}
});
}
}}
}
You need to override a couple of more methods in the WebViewClient :
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
loadingProgressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
loadingProgressBar.setVisibility(View.GONE);
}
I'm assuming loadingProgressBar is a class field.
PS: As a side note I believe you overriding shouldOverrideUrlLoading is unnecessary. The default behaviour is to load the url, as you instruct it to do.
private void initializeProgressBar() {
if (progressBar == null){
progressBar = new ProgressDialog(this);
progressBar.setMessage(Constants.LOADING_MESSAGE);
progressBar.setCancelable(false);
}
}
Handler peogressBar = new Handler(){
public void handleMessage(android.os.Message msg) {
try{
switch (msg.what) {
case 1:
initializeProgressBar();
if(!progressBar.isShowing())
progressBar.show();
break;
case 2:
if (progressBar != null && progressBar.isShowing()) {
progressBar.dismiss();
progressBar = null;
}
break;
}
}catch(Exception e){
e.printStackTrace();
}
};
};
wv_graphLink = (WebView) findViewById(R.id.wv_graphLink);
wv_graphLink.getSettings().setJavaScriptEnabled(true);
wv_graphLink.getSettings().setBuiltInZoomControls(true);
wv_graphLink.getSettings().setSupportZoom(true);
wv_graphLink.setInitialScale(1);
wv_graphLink.getSettings().setLoadWithOverviewMode(true);
wv_graphLink.getSettings().setUseWideViewPort(true);
// wv_graphLink.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
// wv_graphLink.setScrollbarFadingEnabled(false);
peogressBar.sendEmptyMessage(1);
wv_graphLink.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress) {
if(progress == 100){
peogressBar.sendEmptyMessage(2);
}
}
});
wv_graphLink.loadUrl("Your url");
Related
When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
When I make a video full screen in WebView, the toolbar is not hidden. How can I hide it? Below you can see the codes I use.I'm using fragment and the navigation drawer menu.
Full screen
public class searchWebFragment extends Fragment {
public searchWebFragment() {
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.searchwb, container, false);
final ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.progressBarHome);
final WebView webView = (WebView) v.findViewById(R.id.wv_home);
final EditText araTxt = (EditText)v.findViewById(R.id.araTxt);
final Button araBtn = (Button)v.findViewById(R.id.araBtn);
final TextView uyariTxt = (TextView)v.findViewById(R.id.uyariTxt);
progressBar.setVisibility(View.INVISIBLE);
webView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int i, String s, String d1) {
webView.loadUrl("file:///android_asset/error.html");
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
progressBar.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setBuiltInZoomControls(true);
webView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, url);
DownloadManager dm = (DownloadManager) getActivity().getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
Toast.makeText(getActivity().getApplicationContext(), "Dosya İndiriliyor", //To notify the Client that the file is being downloaded
Toast.LENGTH_LONG).show();
}
});
webView.setVisibility(View.INVISIBLE);
araBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
webView.setVisibility(View.VISIBLE);
String aranacaksey = araTxt.getText().toString();
webView.getSettings().setDisplayZoomControls(false);
webView.getSettings().setAppCacheEnabled(false);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
String url = "http://www.ifsalar.16mb.com/?s=" + aranacaksey;
webView.loadUrl(url);
araTxt.setVisibility(View.INVISIBLE);
araBtn.setVisibility(View.INVISIBLE);
uyariTxt.setVisibility(View.INVISIBLE);
}
});
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (webView.canGoBack()) {
webView.goBack();
}
return true;
}
return false;
}
});
return v;
}
}
I would recommend you to try out the follow code and remove the listeners which are related to loading the contents of your WebView.
You need to implement the method to load the website in your webview first.
private void loadWebsite() {
ConnectivityManager connectivityManager = (ConnectivityManager) getApplication().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager .getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
mWebView.loadUrl("yourURL");
} else {
mWebView.setVisibility(View.GONE);
}
}
From here, you need to implement 2 different class "Browser_Home" and "MyChrome". For testing purposes, just write it outside searchWebFragment and later on you can implement it as a separate java file. With only the Browser_Home class, the fullscreen button will be disabled. When MyChrome class is added, fullscreen button is enabled and toolbar should disappear as intended.
class Browser_home extends WebViewClient {
Browser_home() {
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
setTitle(view.getTitle());
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
private class MyChrome extends WebChromeClient {
private View mCustomView;
private WebChromeClient.CustomViewCallback mCustomViewCallback;
protected FrameLayout mFullscreenContainer;
private int mOriginalOrientation;
private int mOriginalSystemUiVisibility;
MyChrome() {}
public Bitmap getDefaultVideoPoster()
{
if (mCustomView == null) {
return null;
}
return BitmapFactory.decodeResource(getApplicationContext().getResources(), 2130837573);
}
public void onHideCustomView()
{
((FrameLayout)getWindow().getDecorView()).removeView(this.mCustomView);
this.mCustomView = null;
getWindow().getDecorView().setSystemUiVisibility(this.mOriginalSystemUiVisibility);
setRequestedOrientation(this.mOriginalOrientation);
this.mCustomViewCallback.onCustomViewHidden();
this.mCustomViewCallback = null;
}
public void onShowCustomView(View paramView, WebChromeClient.CustomViewCallback paramCustomViewCallback)
{
if (this.mCustomView != null)
{
onHideCustomView();
return;
}
this.mCustomView = paramView;
this.mOriginalSystemUiVisibility = getWindow().getDecorView().getSystemUiVisibility();
this.mOriginalOrientation = getRequestedOrientation();
this.mCustomViewCallback = paramCustomViewCallback;
((FrameLayout)getWindow().getDecorView()).addView(this.mCustomView, new FrameLayout.LayoutParams(-1, -1));
getWindow().getDecorView().setSystemUiVisibility(3846);
}
}
And finally, apply the following functions and attributes to your webview and give it another try. Remember to apply these within your OnCreate method:
mWebView.setWebViewClient(new Browser_home());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowFileAccess(true);
webSettings.setAppCacheEnabled(true);
loadWebsite();
Let me know if this works and I can credit the corresponding person for the assistance with the code and classes.
create a folder row and copy the video on raw folder on resources and do the following steps,
On your XML file add VideoView,
<VideoView
android:id="#+id/vdoPlayer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentBottom="true"/>
On your .java class file do,
Uri uri = Uri.parse("android.resource://Your package name Here/" + R.raw.welcome_video);
vdoPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setLooping(true);
}
});
vdoPlayer.setVideoURI(uri);
vdoPlayer.start();
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());
I have a code in which the progress dialog appears along with main layout. I want the progress dialog to be on the forefront and the main layout in background just like its showing the link enter link description here.
public class MainActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setVisibility(View.GONE);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#SuppressLint("SetJavaScriptEnabled")
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
MainActivity.this.progress.setProgress(100);
super.onPageFinished(view, url);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setVisibility(View.VISIBLE);
MainActivity.this.progress.setProgress(0);
super.onPageStarted(view, url, favicon);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
Try to use WebChromeClient instead of WebViewClient to show and update progress :
show pregress bar before call webview.loadUrl() :
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
progress.setVisibility(View.VISIBLE);
webView.loadUrl(url);
}
Update progress in onProgressChanged :
webView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
progress.setVisibility(View.GONE);
} else {
progress.setProgress(newProgress);
}
}
});
I've created Android App with the webview. When trying to sign in with Google, it first asks for username & password, then the screen with the message 'Please close this window' shows up & nothing happens.
Also, the user is not logged in.
P.S. This works absolutely fine with my mobile website which itself is ported to Android Webview App. Can anyone tell why that doesn't work? I'm completely new to Android.
Two things in webview create problems in google sign-in.
Google doesn't allow us to sign-in from webview nowadays. So, User-Agent needs to be customized.
Popup handling in webview isn't appropriate. So, a function override is needed.
Using custom User-Agent and an AlertDialog in WebChromeClient to handle popups solve the issues for me.
Here's the full code:
public class MainActivity extends AppCompatActivity {
private Context contextPop;
private WebView webViewPop;
private AlertDialog builder;
private String url = "https://example.com";
private WebView webView;
private String userAgent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
webView.loadUrl(url);
WebSettings webSettings = webView.getSettings();
// Set User Agent
//userAgent = System.getProperty("http.agent");
// the upper line sometimes causes "403: disallowed user agent error"
userAgent = "";
webSettings.setUserAgentString(userAgent + "Your App Info/Version");
// Enable Cookies
CookieManager.getInstance().setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21)
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
// WebView Tweaks
webSettings.setJavaScriptEnabled(true);
webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setAppCacheEnabled(true);
webSettings.setDomStorageEnabled(true);
webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
webSettings.setUseWideViewPort(true);
webSettings.setSaveFormData(true);
webSettings.setEnableSmoothTransition(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
// Handle Popups
webView.setWebChromeClient(new CustomChromeClient());
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
contextPop = this.getApplicationContext();
}
#Override
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
}
else {
//super.onBackPressed();
// Terminate the app
finishAffinity();
System.exit(0);
}
}
class CustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
webViewPop = new WebView(contextPop);
webViewPop.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// to continue loading a given URL in the current WebView.
// needed to handle redirects.
return false;
}
});
// Enable Cookies
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
if(android.os.Build.VERSION.SDK_INT >= 21) {
cookieManager.setAcceptThirdPartyCookies(webViewPop, true);
cookieManager.setAcceptThirdPartyCookies(webView, true);
}
WebSettings popSettings = webViewPop.getSettings();
// WebView tweaks for popups
webViewPop.setVerticalScrollBarEnabled(false);
webViewPop.setHorizontalScrollBarEnabled(false);
popSettings.setJavaScriptEnabled(true);
popSettings.setSaveFormData(true);
popSettings.setEnableSmoothTransition(true);
// Set User Agent
popSettings.setUserAgentString(userAgent + "Your App Info/Version");
// to support content re-layout for redirects
popSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
// handle new popups
webViewPop.setWebChromeClient(new CustomChromeClient());
// set the WebView as the AlertDialog.Builder’s view
builder = new AlertDialog.Builder(MainActivity.this, AlertDialog.THEME_DEVICE_DEFAULT_LIGHT).create();
builder.setTitle("");
builder.setView(webViewPop);
builder.setButton("Close", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
webViewPop.destroy();
dialog.dismiss();
}
});
builder.show();
builder.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(webViewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onCloseWindow(WebView window) {
//Toast.makeText(contextPop,"onCloseWindow called",Toast.LENGTH_SHORT).show();
try {
webViewPop.destroy();
} catch (Exception e) {
Log.d("Webview Destroy Error: ", e.getStackTrace().toString());
}
try {
builder.dismiss();
} catch (Exception e) {
Log.d("Builder Dismiss Error: ", e.getStackTrace().toString());
}
}
}
}
Here is the working code:
public class MainActivity extends Activity {
protected WebView mainWebView;
// private ProgressBar mProgress;
private Context mContext;
private WebView mWebviewPop;
private FrameLayout mContainer;
private ProgressBar progress;
private String url = "http://m.example.com";
private String target_url_prefix = "m.example.com";
public void onBackPressed() {
if (mainWebView.isFocused() && mainWebView.canGoBack()) {
mainWebView.goBack();
} else {
super.onBackPressed();
finish();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this.getApplicationContext();
// Get main webview
mainWebView = (WebView) findViewById(R.id.webView);
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
mainWebView.setWebContentsDebuggingEnabled(true);
}
mainWebView.getSettings().setUserAgentString("example_android_app");
// Cookie manager for the webview
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
// Get outer container
mContainer = (FrameLayout) findViewById(R.id.webview_frame);
if (!InternetConnection.checkNetworkConnection(this)) {
showAlert(this, "No network found",
"Please check your internet settings.");
} else {
// Settings
WebSettings webSettings = mainWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setAppCacheEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
webSettings.setSupportMultipleWindows(true);
mainWebView.setWebViewClient(new MyCustomWebViewClient());
mainWebView.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
mainWebView.setWebChromeClient(new MyCustomChromeClient());
mainWebView.loadUrl(url);
}
}
// #Override
// public boolean onCreateOptionsMenu(Menu menu) {
// // Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.example_main, menu);
// return true;
// }
private class MyCustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progress.setProgress(0);
progress.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String host = Uri.parse(url).getHost();
Log.d("shouldOverrideUrlLoading", host);
//Toast.makeText(MainActivity.this, host,
//Toast.LENGTH_SHORT).show();
if (host.equals(target_url_prefix)) {
// This is my web site, so do not override; let my WebView load
// the page
if (mWebviewPop != null) {
mWebviewPop.setVisibility(View.GONE);
mContainer.removeView(mWebviewPop);
mWebviewPop = null;
}
return false;
}
if (host.contains("m.facebook.com") || host.contains("facebook.co")
|| host.contains("google.co")
|| host.contains("www.facebook.com")
|| host.contains(".google.com")
|| host.contains(".google.co")
|| host.contains("accounts.google.com")
|| host.contains("accounts.google.co.in")
|| host.contains("www.accounts.google.com")
|| host.contains("www.twitter.com")
|| host.contains("secure.payu.in")
|| host.contains("https://secure.payu.in")
|| host.contains("oauth.googleusercontent.com")
|| host.contains("content.googleapis.com")
|| host.contains("ssl.gstatic.com")) {
return false;
}
// Otherwise, the link is not for a page on my site, so launch
// another Activity that handles URLs
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//startActivity(intent);
//return true;
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
progress.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
#Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
Log.d("onReceivedSslError", "onReceivedSslError");
// super.onReceivedSslError(view, handler, error);
}
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
public void showAlert(Context context, String title, String text) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder.setMessage(text).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// if this button is clicked, close
// current activity
finish();
}
}).create().show();
}
private class MyCustomChromeClient extends WebChromeClient {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog,
boolean isUserGesture, Message resultMsg) {
mWebviewPop = new WebView(mContext);
mWebviewPop.setVerticalScrollBarEnabled(false);
mWebviewPop.setHorizontalScrollBarEnabled(false);
mWebviewPop.setWebViewClient(new MyCustomWebViewClient());
mWebviewPop.getSettings().setJavaScriptEnabled(true);
mWebviewPop.getSettings().setSavePassword(false);
mWebviewPop.setLayoutParams(new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
mContainer.addView(mWebviewPop);
WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(mWebviewPop);
resultMsg.sendToTarget();
return true;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
// TODO Auto-generated method stub
super.onProgressChanged(view, newProgress);
MainActivity.this.setValue(newProgress);
}
#Override
public void onCloseWindow(WebView window) {
Log.d("onCloseWindow", "called");
}
}
}
mainWebView.getSettings().setUserAgentString("example_android_app");
fixed it for me
just changed mainWebView to what my webview was called. In my case, i set it to
webView.getSettings().setUserAgentString("example_android_app");
I am using webview to display the html data.It is working fine if the data is less(less than 1 mb)..I am using following code
mDecryptDataWv.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
DebugLog.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
//showProgressDialog();
DebugLog.i(TAG, "************onPageStarted **************");
}
#Override
public void onPageFinished(WebView view, String url) {
DebugLog.i(TAG, "************onPageFinished **************");
if (mProgressDialog != null) {
if (mProgressDialog.isShowing()) {
DebugLog.i(TAG, "mProgressDialog ::::::stopping");
mProgressDialog.dismiss();
mProgressDialog = null;
}
}
If the data is more then 1MB it is taking more time to complete the loading.so my intention is to load the data page by page upon user scrolling with progress dialog..Can anyone has idea?
// I used this class and my code is working fime at my side please try this may be it will help you
public class WebViewActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
private TextView header_maintext;
private TextView headeroptiontext;
private RelativeLayout back;
private String url_string="http://www.google.com";
private String header_maintext_string="Your text";
/** Called when the activity is first created. */
#SuppressLint("SetJavaScriptEnabled") #Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.webview_layout);
webview = (WebView)findViewById(R.id.webview01);
header_maintext= (TextView)findViewById(R.id.header_maintext);
header_maintext.setText(header_maintext_string);
headeroptiontext = (TextView)findViewById(R.id.headeroptiontext);
headeroptiontext.setVisibility(View.GONE);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.getSettings().setLoadWithOverviewMode(true);
webview.getSettings().setUseWideViewPort(true);
back = (RelativeLayout) findViewById(R.id.back_layout);
back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(webview.canGoBack() == true)
{
webview.goBack();
}
else
{
finish();
}
}
});
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewActivity.this, "My application", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewActivity.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl(url_string);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webview.canGoBack() == true){
webview.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}