Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load URL consecutively one by one

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.

like image 762
sakura Avatar asked Mar 14 '11 10:03

sakura


6 Answers

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>
like image 145
Shankar Agarwal Avatar answered Nov 11 '22 10:11

Shankar Agarwal


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..

like image 5
Niranj Patel Avatar answered Nov 11 '22 12:11

Niranj Patel


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.

like image 3
HenryW Avatar answered Nov 11 '22 11:11

HenryW


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.

like image 2
Christian HC Avatar answered Nov 11 '22 12:11

Christian HC


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);
    }
}


}
like image 2
Anthony Atkinson Avatar answered Nov 11 '22 10:11

Anthony Atkinson


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);
        }
    }
}
like image 1
Ronnie Avatar answered Nov 11 '22 11:11

Ronnie