2

I want to get the url of the webview. However, the method calls before the page is done loading so it always returns with null. Any way around this? Thanks.

WebView webView = new WebView(this);
setContentView(webView);

webView.loadUrl(myURL);

//page is not done loading yet
String url = webView.getUrl(); //returns null
onepiece
  • 3,279
  • 8
  • 44
  • 63

2 Answers2

3

Try adding a WebViewClient and overriding the onPageFinished(...) method. I've never done it but something like this might work...

String theUrl;
WebView webView = new WebView(this);
setContentView(webView);

webview.setWebViewClient(new WebViewClient() {

    public void onPageFinished(WebView view, String url) {
        theUrl = url;
    }

});

webView.loadUrl(myURL);
Squonk
  • 48,735
  • 19
  • 103
  • 135
  • Is there a way to continually check the url? (Example: advancing to another activity when the url changes). – onepiece Dec 08 '12 at 00:44
  • According to the docs, `onPageFinished(...)` will be called every time the main frame of any web page has finished loading in the `WebView` object. The code is just an example and, as I said, not something I've used before. Try putting a `startActivity(...)` call in the `onPageFinished(...)` method instead of my example of `theUrl = url`. – Squonk Dec 08 '12 at 00:48
  • What do you put inside the startActivity? – onepiece Dec 08 '12 at 01:23
  • I don't know, what sort of `Activity` do you want to start? You do it the same way as starting any `Activity`. Create an `Intent` and pass it into `startActivity(...)` – Squonk Dec 08 '12 at 04:14
2

Create a subclass of WebViewClient which overrides onPageStarted(webView, url, favicon) and set it to your WebView (using setWebViewClient()).
You'll have the url of the page which is loading or displayed.

yDelouis
  • 2,094
  • 17
  • 18
  • So I would make a class CustomWebViewClient extends WebViewClient, then override onPageStarted? What would I put inside that method, and how exactly do I use setWebViewClient()? Thanks. – onepiece Dec 08 '12 at 01:10
  • I suggest you do the same things than in the post of Squonk but you override `onPageStarted` instead of `onPageFinished`. Doing this, your attribute `theUrl` will always contain the current url of the WebView – yDelouis Dec 08 '12 at 12:54