I am loading url into webview:
WebView webview=(WebView)findViewById(R.id.webview);
webview.loadUrl(url);
It's taking some time to load url, during which it shows a blank screen. I want to display a progress dialog while the url is loading:
ProgressDialog dialog = ProgressDialog.show(this, "HI","Loading......", true);
However, the above is code is not working. If any have any ideas, please help.
set a WebViewClient to your WebView, start your progress dialog on you onCreate() method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
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) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "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("http://www.google.com");
}
}
your main.xml 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 android:id="#string/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
You will have to over ride onPageStarted and onPageFinished callbacks
mWebView.setWebViewClient(new WebViewClient() {
public void onPageStarted(WebView view, String url, Bitmap favicon) {
if (progressBar!= null && progressBar.isShowing()) {
progressBar.dismiss();
}
progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
Check out the sample code. It help you.
private ProgressBar progressBar;
progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
WebView urlWebView= new WebView(Context);
urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
urlWebView.getSettings().setJavaScriptEnabled(true);
urlWebView.loadUrl(detailView.getUrl());
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);
}
}
Thanks.
You need to set an own WebViewClient for your WebView by extending the WebViewClient class.
You need to implement the two methods onPageStarted (show here) and onPageFinished (dismiss here).
More guidance for this topic can be found in Google's WebView tutorial
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
Related
I'm having a problem with my WebView-App.
I want to add a "Connection-check" on startup that's popping up an error when no Internet-connection is aviable or the WebView is timed out. I can't get it done by myself because I'm new in Android-programming.
I also want to add an options-menu where i can reload the actual page.
Hope someone can help me...
The actual code:
package com.sabithpkcmnr.webviewmaster;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.DownloadListener;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
ImageView superImageView;
ProgressBar superProgressBar;
WebView superWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().setDisplayShowHomeEnabled(true);
superImageView = findViewById(R.id.myImageView);
superProgressBar = findViewById(R.id.myProgressBar);
superWebView = findViewById(R.id.myWebView);
superProgressBar.setMax(100);
superWebView.loadUrl("http://google.com");
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.setWebViewClient(new 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);
}
});
superWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
superProgressBar.setProgress(newProgress);
}
#Override
public void onReceivedTitle(WebView view, String title) {
super.onReceivedTitle(view, title);
getSupportActionBar().setTitle(title);
}
#Override
public void onReceivedIcon(WebView view, Bitmap icon) {
super.onReceivedIcon(view, icon);
superImageView.setImageBitmap(icon);
}
});
superWebView.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
Uri myUri = Uri.parse(url);
Intent superIntent = new Intent(Intent.ACTION_VIEW);
superIntent.setData(myUri);
startActivity(superIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater myMenuInflater = getMenuInflater();
myMenuInflater.inflate(R.menu.super_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.myMenuOne:
onBackPressed();
break;
case R.id.myMenuTwo:
GoForward();
break;
case R.id.myMenuThree:
break;
}
return true;
}
private void GoForward() {
if (superWebView.canGoForward()) {
superWebView.goForward();
} else {
Toast.makeText(this, "Can't go further!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onBackPressed() {
if (superWebView.canGoBack()) {
superWebView.goBack();
} else {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("(Exit?");
dialog.setMessage("Name has nothing to go back, so what next?");
dialog.setPositiveButton("EXIT ME", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
dialog.setCancelable(false);
dialog.setNegativeButton("STAY HERE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
}
}
Try below method by replacing your setWebViewClient,
superWebView= (WebView) findViewById(R.id.webView);
superWebView.setWebViewClient(new myWebClient());
superWebView.getSettings().setJavaScriptEnabled(true);
superWebView.loadUrl("LOAD_YOUR_URL");
superWebView.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
try {
webView.stopLoading();
} catch (Exception e) {
}
if (webView.canGoBack()) {
webView.goBack();
}
webView.loadUrl("about:blank");
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Error");
alertDialog.setMessage("Check your internet connection and try again.");
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
startActivity(getIntent());
}
});
alertDialog.show();
super.onReceivedError(webView, errorCode, description, failingUrl);
}
});
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
Below method can be used to check internet connection.
public static boolean checkInternetConnection(Context context) {
ConnectivityManager con_manager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
return (con_manager.getActiveNetworkInfo() != null
&& con_manager.getActiveNetworkInfo().isAvailable()
&& con_manager.getActiveNetworkInfo().isConnected());
}
you can check internet connection before loading url in webview.
Check below code snippet.
if (checkInternetConnection(this)) {
superWebView.loadUrl("http://google.com");
}else{
Toast.makeText(getApplicationContext(), "No Internet!", Toast.LENGTH_SHORT).show();
}
I am trying to load the site in an android app web view.
The site loads without the images ,all the images from the site are not loaded and i can't add to the cart product or even open details of other product
The code for MainActivity.java is shown below.
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ShareActionProvider;
public class MainActivity extends Activity {
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://shopliek.com");
mWebView.setWebViewClient(new MyAppWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
//hide loading image
findViewById(R.id.progressBar1).setVisibility(View.GONE);
//show webview
findViewById(R.id.activity_main_webview).setVisibility(View.VISIBLE);
}});
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private ShareActionProvider mShareActionProvider;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Inflating the current activity's menu with res/menu/items.xml */
getMenuInflater().inflate(R.menu.menu_main, menu);
/** Getting the actionprovider associated with the menu item whose id is share */
mShareActionProvider = (ShareActionProvider) menu.findItem(R.id.share).getActionProvider();
/** Setting a share intent */
mShareActionProvider.setShareIntent(getDefaultShareIntent());
return super.onCreateOptionsMenu(menu);
}
/** Returns a share intent */
private Intent getDefaultShareIntent(){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, "Make your Life Easier");
intent.putExtra(Intent.EXTRA_TEXT," Visit google");
return intent;
}
}
and also this MyAppWebViewClient:
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().endsWith("www.shopliek.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
}
I'm beginner so please explain kindly with simple instruction and thanks
Try this
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.google.com");
Hope this will work. Let me know if it works.
I've used the below code & everything worked correctly: show pictures, details page ... ...
public class WebviewActivity extends Activity {
#BindView(R.id.webview)
WebView web;
#BindView(R.id.progressBar)
ProgressBar progressBar;
#Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview);
ButterKnife.bind(this);
web.setWebViewClient(new myWebClient());
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl(WebserviceUrl.BASE_URL);
} catch (Exception e) {
e.printStackTrace();
}
}
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
progressBar.setVisibility(View.VISIBLE);
web.loadUrl(url);
return true;
}
public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
final AlertDialog.Builder builder = new AlertDialog.Builder(WebviewActivity.this);
builder.setMessage(R.string.notification_error_ssl_cert_invalid);
builder.setPositiveButton(R.string.continue_to_page, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.proceed();
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
handler.cancel();
}
});
final AlertDialog dialog = builder.create();
dialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
}
}
}
try it & let me know the result
I meet a serious problems when load url with android WebView, in case a page can not load url and the page is blank, other pages which use WebView are not load out the page and i must exit my app to reboot it, so the WebView page can load url success. I do not know why this happens?
Can somebody tell me Why and How to solve this questions?
Thank you.
Try this on Your activity in Mainfest set this
android:onHistory="true"
if You have problem also when not result than try this code also
On Create
webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
//ws.setJavaScriptEnabled(true);
settings.setJavaScriptCanOpenWindowsAutomatically(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click..."+url);
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.e(TAG, "Finished loading URL: " + url);
//webview.reload();
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
}
});
webview.loadUrl("your Url");
Inside the class
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
finish();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Display confirmation here, finish() activity.
if (webview.canGoBack()) {
webview.goBack();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
Try this code may work
WebViewSampleActivity.java
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class WebViewSampleActivity extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.id.webView1);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(WebViewSampleActivity.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
#SuppressWarnings("deprecation")
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(WebViewSampleActivity.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("http://www.google.com");
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webView1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
Add the internet permission in the manifest
<uses-permission android:name="android.permission.INTERNET"/>
I've tried everything I know how to do to kill it. What I want it to do is load the webpage and then kill the ProgressDialog. How do?
package com.calebfultz.package;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class Lists extends Activity {
private WebView webView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web);
ProgressDialog pd = ProgressDialog.show(Lists.this, "",
"Loading. Please wait...", true);
// Create reference to UI elements
webView = (WebView) findViewById(R.id.web_engine);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://cfultz.tumblr.com");
// workaround so that the default browser doesn't take over
webView.setWebViewClient(new MyWebViewClient()
);
}
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
You may want to make your ProgressDialog variable as a member variable of the Lists class and in your shouldOverrideUrlLoading method, add the line
pd.dismiss();
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// Show your progress dialog here
prDialog = ProgressDialog.show(this, "", "Loading, please wait...", true);
super.onPageStarted(view, url, favicon);
}
public void onPageFinished(WebView view, String url) {
//Finish your progress dialog here
if (prDialog.isShowing() || prDialog != null) {
prDialog.dismiss();
}
super.onPageFinished(view, url);
}
I think you can override the onPageFinished function in MyWebViewClient: you can dismiss the ProgressDialog in this function. Or you can override the onProgressChanged in MyWebChromeClient(extends WebChromeClient): when the progress is 100, you can dismiss the ProgressDialog.
Please see this code:
// the init state of progress dialog
mProgress = ProgressDialog.show(this, "Loading", "Please wait for a moment...");
// add a WebViewClient for WebView, which actually handles loading data from web
mWebView.setWebViewClient(new WebViewClient() {
// load url
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
// when finish loading page
public void onPageFinished(WebView view, String url) {
if(mProgress.isShowing()) {
mProgress.dismiss();
}
}
});
it is working fine for me.........enjoy.
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
//start loading animation
//loading is a ProgressBar type
this.loading.setVisibility(0);
view.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if(progress >= 100) {
this.loading.setVisibility(8);
}
}
});
I want to load URL one by one.I used String array to store the URL.My requirement is that if the webview loads the first url it should print the msg "page started" when page starts and when the page finshes it should show "page finished". After the first url loading finishes it should load second URL and continues the same process.
The coding i wrote is as follows:
package com.browser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class browser extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String[] url={"http://www.yahoo.com","http://www.google.com","http://www.ibnlive.com"};
final MyWebView mwv = new MyWebView(this);
mwv.setWebViewClient(new myweb());
new Thread(new Runnable(){
public void run(){
Log.d("runThread","runthread");
for(int i=0;i<2;i++){
openbrowser(url[i]);
}
}
private void openbrowser(String url) {
mwv.getSettings().setJavaScriptEnabled(true);
mwv.loadUrl(url);
Log.d("",""+url);
setContentView(mwv);
}
}).start();
}
public class MyWebView extends WebView{
public MyWebView(Context context) {
super(context);
}
}
public class myweb extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("LOADING");
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("PageStarted: " + url);
}
#Override
public void onPageFinished(WebView view, String url){
System.out.println("PageFinished: " + url);
}
}
}
///indented code <--remove this
It loads only the last URL.
You can use the below code to load one by one urls in the webview. This code just loads the urls one by one that you only see or cant see all the urls but you can see the last one.
public class WebViewsScreenActivity extends Activity {
private WebView mwebview;
int i =0;
private WebViewsScreenActivity _activity;
ProgressDialog _dilog;
private String[] Urls = {"http://www.google.com","http://www.gmail.com","http://www.yahoo.com"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_PROGRESS);
mwebview = new WebView(this);
setContentView(mwebview);
_activity = this;
mwebview.getSettings().setJavaScriptEnabled(true);
mwebview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
if(checkInternetConnection(_activity)){
if(savedInstanceState==null)
mwebview.loadUrl(Urls[i]);
else
mwebview.restoreState(savedInstanceState);
}
else{
//showAlert "Unable to Connect Server"
}
mwebview.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int progress) {
if(mwebview.getVisibility()==View.VISIBLE)
{
WebViewsScreenActivity.this.setProgress(progress * 100);
}
}
});
mwebview.setWebViewClient(new HelloWebViewClient());
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode == KeyEvent.KEYCODE_BACK)
{
mwebview.goBack();
return true;
}
else
return super.onKeyUp(keyCode, event);
}
//To check whether network connection is available on device or not
private boolean checkInternetConnection(Activity _activity) {
ConnectivityManager conMgr = (ConnectivityManager) _activity.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected())
return true;
else
return false;
}//checkInternetConnection()
//HelloWebViewClient class for webview
private class HelloWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
Toast.makeText(getApplicationContext(), "Loading started...!"+Urls[i], Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "Loading done...!"+Urls[i], Toast.LENGTH_SHORT).show();
i++;
if(i<Urls.length)
view.loadUrl(Urls[i]);
}
} //HelloWebViewClient-class
}//AccountsScreenActivity-class
Add the permissions in manifeast file as below::
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.vl.agarwal"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".WebViewsScreenActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Try this one ...
int position=0;
textview.setText("page started");
browser.loadUrl("your first url");
browser.setWebChromeClient(new WebChromeClient()
{
public void onProgressChanged(WebView view, int progress)
{
if(progress == 100)
{
textview.setText("page finished");
if(position==0)
{
browser.loadUrl("your second url");
position=1;
textview.setText("page started");
}
if(position==1)
{
browser.loadUrl("your third url");
position=2;
textview.setText("page started");
}
}
}
});
you can also display Toast Instead of TextView..
I tried to simulate and came up with the following:
package com.mywebslider;
import android.app.Activity;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
public class WebSliderActivity extends Activity {
TextView number;
WebView mWebView;
CountDownTimer mTimer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
number = (TextView) findViewById(R.id.number);
mTimer=new CountDownTimer(15000, 1000) {
String[] myArray={"http://www.upc.nl/","http://www.google.com","http://www.quickspot.nl"};
int currentIndex=0;
public void onTick(long millisUntilFinished) {
number.setText("seconds remaining: " + millisUntilFinished / 1000);
}
//code comment start
// i think this part could be written better
// but it works!!!
public void onFinish() {
if (currentIndex<myArray.length) {
number.setText("done!");
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
} else {
currentIndex=0;
if (currentIndex<myArray.length)
number.setText("done!");
mWebView.loadUrl(myArray[currentIndex]);
currentIndex++;
mTimer.start();
}
mTimer.start();
}
//code comment end
};
mTimer.start();
mWebView = (WebView) findViewById(R.id.webview);
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.loadUrl("http://stackoverflow.com");
mWebView.setWebViewClient(new WebSliderWebViewClient(){
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(mWebView, url);
Toast.makeText(getApplicationContext(), "Done!", Toast.LENGTH_SHORT).show();
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(getApplicationContext(), "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class WebSliderWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}
Beside the fact this works, the array loop can be done better.
main.xml should read:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<WebView
android:id="#+id/webview"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
<TextView
android:id="#+id/number"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
/>
</LinearLayout>
The output will make a 50/50 screen.
One is for the WebView and the other half shows a counter in a TextView.
The problem is that you do not wait for onPageStarted() and onPageFinished to return anything. Instead your code just loads the urls one by one so fast that you only see the last one.
You need to modify your for() loop to wait for the onPagefinished() method to return before you load another page.
Try coding out the WebViewClient extension to notify your Activity when the loading is complete. I've attempted to modify your code to do just that:
package com.browser;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class Browser extends Activity {
private MyWebView mwv = null;
private MyWeb myweb = null;
private List<String> urls = null;
private String[] url = new String[] {"http://www.yahoo.com","http://www.google.com","http://www.ibnlive.com"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mwv = new MyWebView(this);
myweb = new MyWeb(this);
mwv.setWebViewClient(myweb);
urls = Arrays.asList(url);
loadNextUrl(null);
}
private loadNextUrl(String fromUrl) {
if (fromUrl == null) {
myweb.setOriginalUrl(urls.get(0));
mwv.loadUrl(urls.get(0));
} else {
if (urls.indexOf(fromUrl) == urls.size() - 1) return;
String newUrl = urls.get(urls.indexOf(fromUrl) + 1);
myweb.setOriginalUrl(newUrl);
mwv.loadUrl(newUrl);
}
}
public class MyWebView extends WebView{
public MyWebView(Context context) {
super(context);
}
}
public class MyWeb extends WebViewClient{
Browser activity = null;
// Prevent redirects from messing with URL array
String originalUrl = null;
public MyWeb(Browser activity) {
this.activity = activity;
}
public setOriginalUrl(String url) {
this.originalUrl = url;
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("LOADING");
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("PageStarted: " + url);
}
#Override
public void onPageFinished(WebView view, String url){
System.out.println("PageFinished: " + url);
activity.loadNextUrl(originalUrl);
}
}
}
You can use a queue to hold the urls that are to be loaded one after another.
Queue<String> mQueue = new LinkedList<String>();
...
#Override
public void onCreate(Bundle savedInstanceState) {
...
mQueue.add("http://url1");
mQueue.add("http://url2");
mQueue.add("http://urln");
...
String url = mQueue.remove();
mwv.loadurl(url);
}
...
public class myweb extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("LOADING");
return false;
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
System.out.println("PageStarted: " + url);
}
#Override
public void onPageFinished(WebView view, String url){
System.out.println("PageFinished: " + url);
String url = null;
url = mQueue.remove();
if (url != null) {
view.loadUrl(url);
}
}
}