Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call javascript function from Java

I develop an app using PhoneGap. I got a service which is in background and is coded natively (the service and the phone gap app is in the same project). Unfortunatly, I want to call a javascript function from this service. So I searched on the Web and founded something interesting : create a class extending Plugin and do some treatment in it. Then I found this :

this.ctx.sendJavascript("myJavascriptFunction");

I tested with this code, but something wrong happened :

java.lang.NullPointerException

Here is how I tested :

class c = new class();
c.execute("myFunction",null,null);

In the class c, the execute method is like this :

public PluginResult execute(String action, JSONArray args, String callbackId) {
if (action.equals("myFunction")){
    Log.d(TAG,"start actions to do");
    this.ctx.sendJavascript("nameOfFunctionToLaunch");
    Log.d(TAG,"end actions to do");
    return new PluginResult(PluginResult.Status.OK);
}
}

When the app start, I have the first

Log.d(TAG,"start actions to do");

How can I solve this problem ?

like image 414
Erwan Avatar asked Sep 29 '26 06:09

Erwan


1 Answers

Finally I found the solution : in fact the NullPointerException was on ctx. To fix it, I setup the Context value of my object c like this :

c.setContext(use_An_Object_Of_Type_PhonegapActivity);

To get the object, I grab it from the AppActivity in this method :

public class CloudPhoneAppActivity extends DroidGap {
private class NoScaleWebViewClient extends GapViewClient {

    public NoScaleWebViewClient(DroidGap ctx) {
        super(ctx);
        myApp.ctx = ctx;
    }

    public void onScaleChanged(WebView view, float oldScale, float newScale) {
        Log.d("NoScaleWebViewClient", "Scale changed: " + String.valueOf(oldScale) + " => " + String.valueOf(newScale));
    }
}
/** other stuff after**/ 
}

So finally here is the solution :

class c = new class();
c.setContext(myApp.ctx);
c.execute("myFunction",null,null);

There is no change to do in the execute method which is describe before. But be careful of how you call the javascript function.

Erwan

like image 197
Erwan Avatar answered Sep 30 '26 19:09

Erwan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!