Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing value from activity to Android webview for Javascript method

I'm trying to pass an array from my activity to javascript method in html file located in Assets dir.

I'm using JavascriptInterface passing my int array like JSONArray:

public class JavaScriptInterface {

        Context mContext;       
        JavaScriptInterface(Context c) {

            mContext = c;

        }

        @JavascriptInterface
        public JSONArray getValues() {

            String values = "[100,133,'',120,122,132,133]";

            JSONArray jsonarr = null;

            try {

                jsonarr = new JSONArray(values);

            }

            catch(JSONException e) {

                e.printStackTrace();
            }

            return jsonarr;
        }


    }

In javascript method, I take the values thus:

    var data = JSON.parse(js.getValues());

Now, I'm testing my project on different devices and AVD:

the code works fine on Samsung Note 2 (JB 4.2.1) and on AVD with target Google APIs (API level 8) while on Asus Nexus 7 (JB 4.2.2) and others AVD with JB 4.2 the code stops working returns an Web Console error:

03-25 16:35:12.809: E/Web Console(11352): Uncaught SyntaxError: Unexpected token o at file:///android_asset/data/test.html:1

I need these values for represent a chart using a Javascript library.

In addition, I modified the file proguard-project.txt denying the javascript code obfuscation:

keepclassmembers class fqcn.of.javascript.interface.for.webview {
   public *;
}
-keep public class com.XXX.XXX.DataReportActivity$JavaScriptInterface
-keep public class * implements com.XXX.XXX.DataReportActivity$JavaScriptInterface
-keep classmembers class com.XXX.XXX.DataReportActivity$JavaScriptInterface {
    <fields>;
    <methods>;
}
-keepattributes JavascriptInterface

does anyone have any idea about solve it?

please, any help is welcome!

like image 900
SkyNet_citizen Avatar asked Oct 04 '22 14:10

SkyNet_citizen


1 Answers

Change your Javascript Interface to return a String. JSON.parse is expecting a string, not a JSON object.

@JavascriptInterface
    public String getValues() {
        String values = "[100,133,'',120,122,132,133]";
        return values;
    }

The values string might need to be in quotes for the javascript function to be able to parse it too. In other words:

return "'" + values + "'";
like image 168
tim.paetz Avatar answered Oct 13 '22 10:10

tim.paetz