Say I have two variables, x and y and I want to pass them from MyActivity to JavaScript. Here's my code:
public class myNewActivity extends Activity {
double x;
double y;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new);
// get extras passed from another activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
x = extras.getDouble("x");
y = extras.getDouble("y");
}
WebView webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient());
//webView.loadUrl("javascript:setX('"+x+"')");
//webView.loadUrl("javascript:setY('"+y+"')");
webView.loadUrl("file:///android_asset/index.html");
}
I was trying something with the two commented lines but was just crashing the app. This is the JavaScript:
var x, y;
function init(){
// ... here I need the values of X and Y
}
function setX(ex) {
x = ex;
}
function setY(ey) {
y = ey
}
loadUrlfor your js after the page has loaded (inonPageCompleted()). Instead of implementingsetXandsetY, just provide asetXY-- one less call.loadData().