As soon as the Activity started from intent, need to display a ProgressBar. Once WebView is displayed, then ProgressBar need to be hidden.But not able to show ProgressBar in screen. Below is my xml,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="visible"
android:layout_centerInParent="true"/>
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:visibility="invisible"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true" />
</RelativeLayout>
below is my Activity,
public class WebViewActivity extends Activity {
String TAG= WebViewActivity.class.getSimpleName();
String url=null;
WebView webView;
ProgressBar progressBar=null;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
//getWindow().setFeatureInt( Window.FEATURE_PROGRESS, Window.PROGRESS_VISIBILITY_ON);
setContentView(R.layout.activity_webview);
progressBar=findViewById(R.id.progress_bar);
Intent intent=getIntent();
this.url=intent.getStringExtra("url");
webView =(WebView)findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webView.loadUrl(url);
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
AndroidLogger.log(5,TAG," error response"+error);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
AndroidLogger.log(5,TAG,"started"+url);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
webView.setVisibility(View.VISIBLE);
progressBar.setVisibility(View.INVISIBLE);
}
});
}
}
After starting Intent for WebViewActivity, instead of showing ProgressBar getting a blank white screen, until WebView opens up. So how to solve this. Anybody help with this.
Your xml file seems correct BUT your java file having unnecessary code stuff. just adding progress bar in xml will not work. you need to hide/show inside your java file.
correct it step by step and follow this.
public class WebViewActivity extends Activity implements Listener {
String TAG= PaymentGatewayActivity.class.getSimpleName();
String url=null;
String deviceType="ANDROID", name, password, code, pId=null;
String cur=null;
WebView webView;
ProgressBar progressBar=null;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_webview);
progressBar=(ProgressBar) findViewById(R.id.payment_progress_bar);
progressBar.setVisibility(View.VISIBLE);
AndroidLogger.log(5,TAG,"progress bar made visible");
Intent intent=getIntent();
this.pId=intent.getStringExtra("pId");
// HERE CALLING RETROFIT
CommunicationManager communicationManager = new CommunicationManager(WebViewActivity.this, this,pId );
communicationManager.getLink("get url");
}
//THIS METHOD WILL INVOKED WHEN GETTING SUCCESS RESPONSE
#Override
public void getUrlSuccessResponse(String url, String pId, String cur) {
this.url = url;
this.pId = pId;
this.cur = cur;
SharedPreferences sharedpreferences = this.getSharedPreferences(this.getResources().getString(R.string.app_preferences), Context.MODE_PRIVATE);
this.name = sharedpreferences.getString(this.getResources().getString(R.string.name), "");
this.password = sharedpreferences.getString(this.getResources().getString(R.string.password), "");
this.code = sharedpreferences.getString(this.getResources().getString(R.string.code), "");
webView = (WebView) findViewById(R.id.webView);
webView.setVisibility(View.VISIBLE);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webView.setBackgroundColor(Color.TRANSPARENT) //set this one to remove unnecessary background
//setup custom webview client here
webView.setWebViewClient(new PayWeb());
//load url inside webview
try {
String postData = "type=" + URLEncoder.encode("ANDROID", "UTF-8") + "&password=" + URLEncoder.encode(password, "UTF-8") + "&code=" + URLEncoder.encode(code, "UTF-8") + "&cur=" + URLEncoder.encode(cur, "UTF-8") + "&name=" + URLEncoder.encode(subscriberId, "UTF-8") + "&pId=" + URLEncoder.encode(pId, "UTF-8");
webView.postUrl(url, postData.getBytes());
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public class PayWeb extends WebViewClient{
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressBar.setVisibility(View.VISIBLE);
return false; // then it is not handled by default action
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//show progressbar
progressBar.setVisibility(View.VISIBLE);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
//hide progressbar
progressBar.setVisibility(View.INVISIBLE);
}
}
#Override
public void getUrlFailureResponse(int statusCode, String status) {
//manage webpage faliour case
}
#Override
public void getUrlNetworkFailureException(int statusCode, String status) {
//manage network faliour case
}
}
Related
I have internet permission in my manifest, I am trying to search for "facebook" on the searchbar of my webview, but the problem is, for the 50% searches, It does not load the search request! this is so weird and frustrating. I implemented everything correctly and checked everything 3 times, but no luck. every time I search for the same on other browsers, It always works. but when I search on my webview, It sometimes loads the page, and most of the times, progress bar shows loading, and disappears as if the page has actually loaded, but it is still white. Why is this happening???
public class MainActivity extends AppCompatActivity {
private EditText searchEditText;
private ProgressBar progressBar;
private WebView webView;
private String SearchString = "https://www.google.co.in/search?q=";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressBar.setMax(100);
webView = (WebView) findViewById(R.id.webView);
webView.setWebViewClient(new WebViewClientDemo());
webView.setWebChromeClient(new WebChromeClientDemo());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("about:blank");
// use keyboard go button to search
searchEditText = (EditText) findViewById(R.id.searchfield);
searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView arg0, int arg1, KeyEvent arg2) {
CustomSearch();
return false;
}
});
}
private class WebViewClientDemo extends WebViewClient {
#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);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getBaseContext(), "page error. please try again!", Toast.LENGTH_SHORT).show();
super.onReceivedError(view, errorCode, description, failingUrl);
}
}
private class WebChromeClientDemo extends WebChromeClient {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
}
public void CustomSearch() {
searchEditText = (EditText) findViewById(R.id.searchfield);
String url = searchEditText.getText().toString();
url = SearchString + url.replace(" ", "+");// replace_spaces_with_a_"+"_sign(prefix)
webView.loadUrl(url);
}
Did you try encoding your search text, as per my understanding you need to encode the search string.
I have a webview in my android application which renders html pages from a local folder, Now I want to show progress dialog when navigating from one html page to another but the progress dialog which I am using isn't showing up. Here is my code snippet:
#JavascriptInterface
public void save(String respString, boolean ifEndNode) throws JSONException {
ProgressDialog progDialog = null;
try {
if(ifEndNode){
//start loader
progDialog = new ProgressDialog(webView.getContext());
progDialog.setMessage("Saving survey, Please DON'T close the Application!! ");
progDialog.setCanceledOnTouchOutside(false);
progDialog.setCancelable(false);
progDialog.show();
}
//some code here
//...
}
catch (Exception e)
{
Logger.e(context,"exception", "jsonObjectexception");
}
finally {
if(progDialog != null && progDialog.isShowing())
progDialog.dismiss();
}
Can anyone suggest what the problem could be?
You can use WebView with ProgressDialog this way. This is nice and simple approch.
private WebView webView;
ProgressDialog prDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.page_news);
setSupportActionBar((Toolbar) findViewById(R.id.toolbar));
webView = (WebView) findViewById(R.id.wv_news);
webView.setWebViewClient(new MyWebViewClient());
String url = "http://google.com/";
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
webView.loadUrl(url);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
prDialog = new ProgressDialog(NewsActivity.this);
prDialog.setMessage("Please wait ...");
prDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(prDialog!=null){
prDialog.dismiss();
}
}
}
I get this error. How can I fix this in my situation?
"Bitmap cannot be resolved to a type"
The line where error occurs
public void onPageStarted(WebView view, String url, Bitmap favicon) {
My code
public class MainActivity extends Activity {
private Activity activity = this;
private String title = "";
private ActionBar mActionBar;
private SimpleSideDrawer mNav;
WebView myWebView;
int width, height;
float flick_width;
float flick_height;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
title = activity.getTitle().toString(); // (1)
requestWindowFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.activity_main);
getSize();
mActionBar = getActionBar();
mActionBar.hide();
mNav = new SimpleSideDrawer(this);
mNav.setLeftBehindContentView(R.layout.activity_behind_left_simple, this);
mNav.setRightBehindContentView(R.layout.activity_behind_right_simple, this);
myWebView = (WebView)findViewById(R.id.webView1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Log.d("HelloWebView", "onPageStarted : " + url);
activity.setTitle("Loading..."); // (2)
activity.setProgressBarVisibility(true);
}
#Override
public void onPageFinished(WebView view, String url) {
Log.d("HelloWebView", "onPageFinished : " + url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("HelloWebView", "shouldOverrideUrlLoading : " + url);
return super.shouldOverrideUrlLoading(view, url);
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d("HelloWebView", "onReceivedError : "+description);
//view.loadData("Error "+description, "text/plain", "utf-8");
view.loadDataWithBaseURL(null, "Error ("+errorCode+"):"+description, "text/plain", "utf-8", null);
}
});
myWebView.setWebChromeClient(new WebChromeClient() { // (3)
public void onProgressChanged(WebView view, int progress) {
activity.setProgress(progress * 100);
Log.d("HelloWebView", "progress="+progress);
if (progress==100) {
activity.setProgressBarVisibility(false);
activity.setTitle(title);
}
}
});
myWebView.loadUrl("http://yahoo.com");
myWebView.getSettings().setSupportZoom(true);
myWebView.getSettings().setLoadWithOverviewMode(true);
myWebView.getSettings().setUseWideViewPort(true);
Eclipse sometimes hiccups when trying to auto-resolve imports. In cases like that, you can try manually entering the import statement yourself: import android.graphics.Bitmap;
Just Click "Ctr+Shift+O" even though it doesnt show the import when you hover on it.. it will automatically import It when you click this --->> "Ctr+Shift+O"
i want to play a video from youtube on webview.. it displays the video,But i want to play it on the same page i mean i've to use WebViewClient.. but using that it doesn't play the video.. (on pressing play button it doesn't play the video) what should i do? my code is
setContentView(R.layout.main);
wvSpecials = (WebView) findViewById(R.id.webView1);
WebSettings webSettings = wvSpecials.getSettings();
webSettings.setJavaScriptEnabled(true);
wvSpecials.loadUrl("http://here.com/is link/");
wvSpecials.setWebViewClient(new WebViewClient() {
ProgressDialog progressDialog = new ProgressDialog(
specialsActivity.this);
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressDialog.setMessage("Please wait...");
progressDialog.show();
super.onPageStarted(view, url, favicon);
}
#Override
public void onPageFinished(WebView view, String url) {
if (progressDialog.isShowing()) {
progressDialog.dismiss();
}
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, url);
}
});
}
You may use the below listed code:
public class YouTube extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WebView myWebView;
myWebView = (WebView) findViewById( R.id.web);
myWebView.setWebViewClient(new MyWebViewClient());
String pre="<iframe class=youtube-player type=text/html width=";
String height=" height=";
String suffix=" src=http://www.youtube.com/embed/**xxxxxxxxxxx**?autoplay=1 frameborder=0>"; // replace xxxxxxxxxxx with the specific embed id of your video
String playVideo=pre+260+height+150+suffix;
myWebView.getSettings().setPluginsEnabled(true);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadData(playVideo,"text/html","UTF-8");
}
// override default behaviour of the browser
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
ProgressDialog dialog = ProgressDialog.show(getApplicationContext(), "",
"Loading. Please wait...", true);
#Override
public void onPageFinished(WebView view, String url) {
dialog.dismiss();
}
} }
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 :)