I am super new to android apps and I am trying to create an app that just loads a webpage when clicked.
I, however, keep getting an error that: can't find symbol variable URL
Here is my MainActivity code:
package com.example.logger;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void browser1(View view) {
Intent browserIntent=new Intent(Intent.ACTION_VIEW,url.parse("xxxxxxxxxxx"));
startActivity(browserIntent);
}
}
Kindly help with figuring out what I'm missing.
It should be Uri, not url
Intent browserIntent=new Intent(Intent.ACTION_VIEW,Uri.parse("xxxxxxx"));
Make sure you have import android.net.Uri on top.
Add permission In Manifests file
<uses-permission android:name="android.permission.INTERNET" />
Add this in xml file
<WebView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/webview"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
Add this in MainActivity
public class MainActivity extends AppCompatActivity {
ProgressDialog pd;
WebView wv;
String url="www.google .com";
private ImageView back3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_social_media);
back3 = (ImageView) findViewById(R.id.back3);
back3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
wv=(WebView)findViewById(R.id.webview);
pd = new ProgressDialog(SocialMedia.this);
pd.setCancelable(true);
pd.setMessage("Loading....");
// pd.setIcon(R.drawable.load);
// wv.getSettings().setLoadsImagesAutomatically(true);
wv.setWebViewClient(new MyBrowser(pd));
wv.getSettings().setJavaScriptEnabled(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.loadUrl(url);
}
public class MyBrowser extends WebViewClient{
ProgressDialog pd;
public MyBrowser(ProgressDialog pd) {
this.pd = pd;
pd.show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(url);
return super.shouldOverrideUrlLoading(view, request);
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if(pd.isShowing()){
pd.dismiss();
}
}
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(getApplicationContext(),"Error"+description,Toast.LENGTH_SHORT).show();
}
}
}
Related
I am trying to start an activity (Errorpage) when webview failed to load content.But there is no error during the build, but the app closes, while inernet is off. It was supposed to launh the Errorpage activity.
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import androidx.appcompat.app.AppCompatActivity;
public class smwebview extends AppCompatActivity {
private WebView webview;
private ProgressBar spinner;
String ShowOrHideWebViewInitialUse = "show";
private WebView mWebView; //added for back buton override
public boolean mShouldPause = false;
String fullurl;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_smwebview);
getIntent();
fullurl= getIntent().getStringExtra("full_url");
webview = (WebView) findViewById(R.id.webView_Latest);
webview.setWebViewClient(new CustomWebViewClient());
spinner = (ProgressBar)findViewById(R.id.progressBar2);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.getSettings().setAppCacheEnabled(true);
webview.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);// keep screen on
webview.loadUrl(fullurl);
private class CustomWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public void onLoadResource(WebView webview, String url) {
super.onLoadResource(webview, url);
if (url.contains("youtube.com")) mShouldPause = true;
}
public void onReceivedError(WebView webview, int errorCode, String description, String failingUrl) {
Intent intent7 = new Intent(smwebview.this,Errorpage.class);
startActivity(intent7);
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
public class WebViewClient extends android.webkit.WebViewClient {
#Override
public void onPageStarted(WebView webview, String url, Bitmap favicon) {
if (ShowOrHideWebViewInitialUse.equals("show")) {
webview.setVisibility(webview.INVISIBLE);
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
ShowOrHideWebViewInitialUse = "hide";
spinner.setVisibility(View.GONE);
view.setVisibility(webview.VISIBLE);
super.onPageFinished(view, url);
}
}
#Override
public void onResume()
{
super.onResume();
webview.onResume();
}
#Override
public void onPause() {
super.onPause();
if(mShouldPause){
webview.onPause();
}
mShouldPause = false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webview.canGoBack()) {
webview.goBack();
} else {
super.onBackPressed();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
If anybody have any idea Please help me. Also please comment your suggestions on the code/logic. (I am very new to android programming)
Internet if off. Its different scenario you must add check internet connection before load.
Or onRwleceiveError is different case. When you load wrong url or utl you entered is not working
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 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();
}
});
how can i open this url in web view in android
https://web150.secure-secure.co.uk/ftpeditor.net/core/homepage.php
try to use the chrome client:
vw = new MyWebView(this);
vw.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
vw.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
this is the completed code
package com.myapp;
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
public class MainActivity extends Activity {
WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("https://web150.secure-secure.co.uk/ftpeditor.net/core/homepage.php");
}
}
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);
}
}
}