Reputation: 41
I went through all the posts shared in here, I still couldn't find my proper answer to run my code and make my app functional. I'll appreciate it if any of you who could help me on this issue.
I am calling bounded function getLocation() in tages as mentioned: . The getLocation function is bounded to MyHandler in Android as mentioned in below:
public class MainActivity extends Activity {
WebView webView;
private Handler mHandler = new Handler ();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface (new Object(){
public void getLocation(){
mHandler.post (new Runnable(){
public void run(){
String[] values = {"3.16802","101.71309"};
webView.loadUrl("javascript:setLocation("+values+")");
}
});
}
}, "MyHandler");
webView.loadUrl("file:///android_asset/example/quick-start-example.html");
}
}
The function setLocation in Android calls the method in JavaScrip as below, here we are passing the array into JS function:
function setLocation(val){
var lat = val[0];
var lng = val[1];
}
Please advice on this. Thank you.
Upvotes: 3
Views: 5119
Reputation: 283
Whenever you are passing object like Array or List in Javascript function then first, you need to convert that object into JSON format like below:
String[] values = {"3.16802","101.71309"};
webView.loadUrl("javascript:setLocation('"+new JSONArray(values)+"')");
And in Java script function again you have to parse that JSON format input like below:
function setLocation(input){
var value=JSON.parse(input);
var lat = value[0];
var lng = value[1];
}
Upvotes: 1
Reputation: 623
You should probably try this:
Gson gson = new Gson();
String data = gson.toJson(someArray);
Upvotes: 0
Reputation: 343
@JavascriptInterface
public String[] displayName() {
String ar[] = new String[2];
ar[0]= "name1";
ar[1] = "name2";
return ar;
}
or to get Data in js function
var t1 = Android.displayName();
Upvotes: 0
Reputation: 25
^above comment, you can use onPageFinished to execute the loadurl part once your page is done loading like this:
myWebView.setWebViewClient(new WebViewClient(){
public void onPageFinished(WebView view, String url){
myWebView.loadUrl("javascript:setLocation("+values+")");
}
});
Upvotes: 0
Reputation: 799
I don't think you can easily do a complex object like an Array. You are starting to get into JSON territory.
In fact, I found some sample code that uses JSON to accomplish this.
Problem: You want to push array data from Java to JavaScript and/or from JavaScript to Java http://androidcookbook.com/Recipe.seam?recipeId=4426&title=Exchanging%20Array%20Data%20between%20Java%20and%20JavaScript
Upvotes: 1