Issue
This is a function to get long url from short url such as goo.gl, bit.ly ...
private String expandUrl(String shortUrl) {
String finalURL = "";
webView.loadUrl(shortUrl);
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
finalURL = webView.getUrl();
}
});
return finalURL;
}
I want to store webView.getUrl()
to a String call finalURL
so that I can use it later, but it get error
error: local variable finalURL is accessed from within inner class; needs to be declared final
what is my mistake?
Solution
If finalURL variable is the member variable of the outer class, then it is possible for you to save the webView.getUrl() to finalURL for later purposes like parsing but if finalURL is a local variable, then its not possible unless you make it as an array object and final variable. Use below code. instead of using plain finalURL, use finalURL[0] to store and parse later.
final String[] finalURL = {""};
String url1 = "goo.gl/RvoAZH";
webView.loadUrl(url1);
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
System.out.println(webView.getUrl()); // whatever way to debug
finalURL[0] = webView.getUrl();
}
});
Here in the below example you could see the value of local variable localVar being changed by the method(anonyMethod) inside the anonymous object from "" to a
public class Check {
public void method() {
final String[] localVar = {""};
new Object() {
public void anonyMethod() {
System.out.println(localVar[0]); // sure
localVar[0] = "a"; // nope
}
}.anonyMethod();
System.out.println(localVar[0]);
}
public static void main(String[] args)
{
Check ck = new Check();
ck.method();
}
}
Edit 1 Can you also post some more your code.
Edit 2 Added my own sample code.
Answered By - Sam
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.