Android app: how to load url in WebView from another class?
I am new to Android and Java application programming. I want my application to use a WebView to display whatever it needs. User can click on HTML button or link to send request to my Android Java class, for example to show another page.
So I have my main class loading the Webview like this:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/html/status01.html");
In public class JavaScriptInterface
I want the function to load a different url:
public void showOffers() {
WebView myWebView = (WebView) ((Activity) mContext).findViewById(R.id.webview);
myWebView.loadUrl("file:///android_asset/html/offers.html");
}
But that won't compile because: Activity cannot be resolved to a type
How can I access the WebView from my JavaScriptInterface class to load a different url?
source to share
Define the class JavaScriptInterface
as an inner class of yours Activity
and store the reference WebView
as a member variable of yours Activity
.
Since inner classes can access the member variables of the class in which they are defined, you can change your code to this:
MyWebActivity extends Activity{
private WebView myWebView;
protected void onCreate(Bundle bundle){
myWebView = (WebView) findViewById(R.id.webview);
myWebView.addJavascriptInterface(new JavaScriptInterface(), "Android");
myWebView.setWebViewClient(new WebViewClient());
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("file:///android_asset/html/status01.html");
}
private class JavaScriptInterface{
JavaScriptInterface(){
}
public void showOffers() {
myWebView.loadUrl("file:///android_asset/html/offers.html");
}
}
}
source to share