I am trying to add a progress bar in the android webview based app. I have added following code but not working when tested.
Note: index.html have redirect tag which loads random URL. Everything is working fine except the progressbar.
MainActivity.java
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
ProgressBar Pbar;
private final int ID_MENU_EXIT = 1;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
Pbar = (ProgressBar) findViewById(R.id.pB1);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new MyAppWebViewClient());
if (isNetworkAvailable())
mWebView.loadUrl("file:///android_asset/www/index.html");
else
mWebView.loadUrl("file:///android_asset/www/404.html");
}
public class myWebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
Pbar.setVisibility(View.GONE);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
//get the MenuItem reference
MenuItem item =
menu.add(Menu.NONE,ID_MENU_EXIT,Menu.NONE,R.string.exitOption);
//set the shortcut
item.setShortcut('5', 'x');
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
//check selected menu item
if(item.getItemId() == ID_MENU_EXIT)
{
//close the Activity
this.finish();
return true;
}
return false;
}
}
Activity_main.xml
<ProgressBar android:id="#+id/pB1"
style="?android:attr/progressBarStyleHorizontal" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_centerVertical="true"
android:padding="2dip">
</ProgressBar>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
Well,
Use this code for Progress Bar when your WebView waiting for loading WebView. :
Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
Activity:
public class MapActivity extends MenuActivity {
private final static String TAG = "HearingTest";
private WebView webView;
private String urlString;
private ProgressDialog progressDialog;
private Context context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
context = MapActivity.this;
urlString = getString(R.string.location_url);
WebViewSettings();
LoadWebPage(urlString);
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Loading...");
progressDialog.setMessage("Please wait.");
//progressDialog.setCancelable(false);
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
try {
//Do something...
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (progressDialog!=null) {
progressDialog.dismiss();
}
}
};
task.execute((Void[])null);
}
public void LoadWebPage(String url){
try {
webView.loadUrl(url);
Log.d(TAG, "URL" + url + "connected");
}
catch (Exception e) {
Log.d(TAG, "URL: " + url + " couldn't connect.");
}
}
public void WebViewSettings(){
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals(urlString)) {
// This is my web site, so do not override; let my WebView load the page
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;
}
#Override
public void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error) {
handler.proceed();
}
});
}
protected void DisplayProgressBar(){
}
}
Related
Need some advice. I want to be able to redirect the user to a specific link in WebView. Example: we go to the first link and if it directs us to "google.com" then we will have to direct the user to "http://test.com". I made an implementation, put a redirect in shouldOverrideUrlLoading, however, after SplashScreen-loading image done its work, a white background appears and that's it. At the same time, if you remove the code for redirection, then after performing its work, the SplashScreen - loading image, the first link opens and the page from the Internet is displayed correctly. How do I redirect to other pages after opening the first one?
public class MainActivity extends AppCompatActivity {
private WebView webView;
private final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://test/start");
new TaskForRedirecting().execute();
}
public class TaskForRedirecting extends AsyncTask<Boolean, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Boolean doInBackground(Boolean... booleans) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Log.d(TAG, "Start loading here");
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return false;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return false;
} else {
}
return true;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
view.loadUrl(request.getUrl().toString());
return false;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return false;
}
return true;
}
};
webView.setWebViewClient(webViewClient);
Log.d(TAG, "Do in background: APP is Working!!!");
}
});
return false;
}
#Override
protected void onPostExecute(Boolean success) {
success = false;
if (success) {
Toast toast = Toast.makeText(MainActivity.this, "App is under maintenance!", Toast.LENGTH_SHORT);
toast.show();
} else {
Toast toast = Toast.makeText(MainActivity.this, "Let's start to work!", Toast.LENGTH_SHORT);
toast.show();
}
Log.d(TAG, "upload - final! ");
}
}
}
public class SplashScreenActivity extends AppCompatActivity {
long Delay = 6000;
private final String TAG = "SplashScreenActivity";
private WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash_screen);
new SplashScreen().execute();
}
public class SplashScreen extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void...voids) {
Timer RunSplash = new Timer();
TimerTask ShowSplash = new TimerTask() {
#Override
public void run() {
finish();
Intent intent = new Intent(SplashScreenActivity.this, MainActivity.class);
startActivity(intent);
}
};
RunSplash.schedule(ShowSplash, Delay);
Log.d(TAG, "ShowSplash - final! ");
return null;
}
}
}
Your implementation needs to change a bit, we don't need to set the webview client inside an AsyncTask, instead, we can set it directly but it should be set before we call loadurl.
I have removed the asynctask, and set the client in onCreate method before calling loadUrl.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = findViewById(R.id.webView);
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
WebViewClient webViewClient = new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("google.com")) {
view.loadUrl("http://test1.com");
return true;
} else if (url.contains("yahoo.com")) {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
if (request.getUrl().toString() == "google.com") {
view.loadUrl("http://test1.com");
return true;
} else if (request.getUrl().toString() == "yahoo.com") {
view.loadUrl("http://test2.com");
return true;
}
return false;
}
};
webView.setWebViewClient(webViewClient);
webView.loadUrl("http://test/start");
}
UPDATE
Please check out the shouldOverrideUrlLoading Doc, You should return true when you want to cancel the current load, so when you want to load a different URL, then return true else return false to continue the current load. Returning false means the URL which is being loaded to the webview will continue, your custom URL will not be loaded.
I have a URL of a presentation and i want to show this in the webview in android. I have tried the below code but it is redirecting in google drive app.
String url1 =
"https://docs.google.com/presentation/d/1nL5yO1HX_";
And my Webiew code is below:
WebView mywebview = findViewById(R.id.webview);
WebSettings settings = mywebview.getSettings();
settings.setJavaScriptCanOpenWindowsAutomatically(true);
settings.setBuiltInZoomControls(true);
settings.setAllowFileAccess(true);
settings.setJavaScriptEnabled(true);
mywebview.loadUrl(url1);
Use setWebViewClient and getHitTestResult.It is use to get the url which will be going to open and then check whether it is ppt file or not.
First XML File :-
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"></WebView>
Main Activity :-
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request)
{
try{
if(webView.getHitTestResult().getExtra().endsWith(".pptx"))
{
try
{
Intent intent=new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("url",webView.getHitTestResult().getExtra());
startActivity(intent);
return true;
}
catch (Exception e)
{
Toast.makeText(MainActivity.this, e+"", Toast.LENGTH_SHORT).show();
}
return true;
}
else
{
webView.loadUrl(request);
return true;
}}
catch (Exception e)
{
return false;
}
}
Then in new activity get value of intent :-
public class Main2Activity extends AppCompatActivity {
WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Intent intent=getIntent();
String t=intent.getStringExtra("url");
String s="http://docs.google.com/viewer?url=";
s=s.concat(t);
webView=(WebView)findViewById(R.id.webView);
webView.loadUrl(s);
}
#Override
protected void onResume()
{
this.finish();
super.onResume();
}
Second XML File :-
<WebView
android:id="#+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
I have used webclient and it worked for me
public class WebClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
the webpage have some popup ads is there any way to prevent the popup from loading when the popup loads the main site doesnt appears is there any way to load the main page with out popups and how can i add a download handler l mean the webview should support downloading .torrent file
public class MainActivity extends AppCompatActivity {
private WebView webView;
private ProgressBar progressBar;
private LinearLayout layoutProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
layoutProgress = (LinearLayout) findViewById(R.id.layoutProgress);
webView.setVisibility(View.GONE);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setBuiltInZoomControls(true);
settings.setSupportZoom(true);
settings.setDisplayZoomControls(false);
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) {
webView.setVisibility(View.VISIBLE);
layoutProgress.setVisibility(View.GONE);
progressBar.setIndeterminate(false);
super.onPageFinished(view, url);
}
public void but(View v){
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
layoutProgress.setVisibility(View.VISIBLE);
progressBar.setIndeterminate(true);
super.onPageStarted(view, url, favicon);
}
});
if(isOnline()) {
webView.loadUrl("http://testsite.com/");
} else {
String summary = "<html><body><font color='red'>No Internet Connection</font></body></html>";
webView.loadData(summary, "text/html", null);
toast("No Internet Connection.");
}
}
private void toast(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
public void onBackPressed() {
if(webView.canGoBack()) {
webView.goBack();
} else {
super.onBackPressed();
}
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return (netInfo != null && netInfo.isConnected());
}
public void but(View v){
webView.loadUrl("http://testsite.com/");
}
}
if the url changes then use shouldOverrideUrlLoading with some regex
so
List<String> validUrls = new LinkedList<>();
validUrls.add("https://www\\.google\\.com/*");
validUrls.add("https://www\\.facebook\\.com/*");
#Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (isValidUrl(url)) {
return false;
}
return true;
}
private boolean isValidUrl(String url) {
for (String validUrl : validUrls) {
Pattern pattern = Pattern.compile(validUrl, Pattern.MULTILINE);
Matcher matcher = pattern.matcher(url);
if (matcher.find()) {
return true;
}
}
return false;
}
would match against any www.google.com or facebook.com urls
You can intercept the urls that are opened from the webview, I don't know if it would work with the popup:
WebViewClient client= new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
if (url.equals("popupURL"){
return true;
}
return false;
}
}
webView.setWebViewClient(client);
I am using webview with ProgressDialog. My issue is that on the Initial Launch, the progressDialog appears abd load properly but whenever I click a link (post links) inside webview, the progress is not showing. Here's the code -
public class Xyz extends WebViewClient
{
public void onLoadResource (WebView view , String url ) {
if (progressDialog == null ) {
progressDialog = new ProgressDialog(getActivity());
progressDialog . setMessage( "Loading..." );
progressDialog.setIndeterminate(true);
progressDialog . show();
}
}
public void onPageFinished(WebView view , String url ) {
if (progressDialog . isShowing()) {
progressDialog . dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
}
You are overriding the wrong method to achieve your goal. I've put up an Activity here which works as intended.
I'm using onPageStarted() instead of onLoadResource().
Activity MainActivity.java:
public class MainActivity extends AppCompatActivity {
ProgressDialog progressDialog;
WebViewClient mClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (progressDialog == null) {
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Loading...");
progressDialog.setIndeterminate(true);
}
if(!progressDialog.isShowing()) {
progressDialog.show();
}
}
public void onLoadResource(WebView view, String url) {
}
public void onPageFinished(WebView view, String url) {
if (progressDialog!=null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
};
WebView webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(mClient);
webView.loadUrl("http://www.google.com");
}
}
Layout 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="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.prasad.myapplication.MainActivity">
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</RelativeLayout>
Try to track the webview load progress using webChoromeClient like this:
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
progressBar.setVisibility(View.GONE);
} else {
progressBar.setVisibility(View.VISIBLE);
}
}
});
and replace your webview client as follwing
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
To create a webView recently I was using webViewClient. mWebView.setWebViewClient(new WebViewClient());
But I need to implement a progress bar. When user clicks a link, this progress bar will be visible. After page complete, progressbar will be hidden and webView will be visible. Regarding to this and this, So I added a WebChromeClient. But it loads first URL, but when I click a button inside my web page, a dialog opens and asks to open URL with which application.
I read that I should override shouldOverrideUrlLoading() method. but I get an error that "shouldOverrideUrlLoading" can't be overriden for WebChromeClient.
I would be happy if you can give an example that has progressbar and webView, also opens new URLs inside the same webView.
public class WebActivity extends Activity {
WebView mWebView;
ProgressBar mProgress;
Context mContext;
ProgressBar mProgressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
this.mContext = getApplicationContext();
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebChromeClient(new myWebChromeClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setUserAgentString("myApp");
mProgressBar = (ProgressBar) findViewById(R.id.webProgressBar);
mProgressBar.setMax(100);
}
public class myWebChromeClient extends WebChromeClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onProgressChanged(WebView view, int newProgress) {
//WebActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
}
try with this code
webView = (WebView) view.findViewById(R.id.transcationwebview);
progressdialog = ProgressDialog.show(mContext, "",
mContext.getString(R.string.please_wait));
progressdialog.setCancelable(true);
progressdialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
webView.stopLoading();
// webView.clearView();
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new MyChromeClient());
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if (progressdialog != null && progressdialog.isShowing()) {
progressdialog.dismiss();
} else {
}
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
webView.loadUrl("url");
webView.getSettings().setBuiltInZoomControls(true);
public class MyChromeClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
try {
if (progressdialog.isShowing()) {
progressdialog.setMessage(getString(R.string.loading)
+ newProgress + " %");
} else {
/*
* webView.stopLoading(); webView.clearView();
*/
}
} catch (Throwable e) {
e.printStackTrace();
}
}
}
you can extends WebViewClient instead of WebChromeClient and override the onPageStarted to show the ProgressBar and dismiss it in onPageReceived
I made some changes in the Activity.
use WebViewClient instead of WebChromeClient
and also use ProgressDialog instead of ProgressBar
public class WebActivity extends Activity {
WebView mWebView;
Context mContext;
ProgressDialog mProgressBar;
private static final int DIALOG2_KEY = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
this.mContext = getApplicationContext();
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new MyWebChromeClient());
mWebView.getSettings().setBuiltInZoomControls(true);
showDialog(DIALOG2_KEY); }
#Override
protected void onResume() {
super.onResume();
mWebView.loadUrl("YOUR_URL");
}
private final class MyWebChromeClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
dismissDialog(DIALOG2_KEY);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("file")) {
return false;
} else{
view.loadUrl(url);
return true;
}
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id)
{
case DIALOG2_KEY:
{
mProgressBar.setMessage("Loading");
mProgressBar.setIndeterminate(true);
mProgressBar.setCancelable(false);
return mProgressBar;
}
}
return null;
}
}
Hope this help you