Tuesday, June 26, 2012

Phonegap plugin. Fixed an issue of not getting a callback in Js after this.success() called from Plugin class

I was facing a weird problem on developing a plugin for Phonegap on Android. After the the execution of native Java function, i was not able to give back the success or failure message to JS file.

The following is how my Plugin class looks like.
public class MyPlugin extends Plugin {
  @Override
  public PluginResult execute(String action, JSONArray data, String callbackId) {
        
        this.callbackId = callbackId;
        
        /* .. some code ... */

        StartMyAsyncThread();
        
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        return pr;
    }
        
    
    public void resultOfAsyncThread(String message){
        
        PluginResult pr = new PluginResult(PluginResult.Status.OK, message);
        this.success(pr, this.callbackId)
    }
    
}


From the execute class, if I returned Status.OK instead of Status.NO_RESULT, I was able to get the call to success_callback function in javascript file. But, from the asynchronous thread, if I called this.success(), I was not getting the call to success_callback function in javascript.

This was crucial as it is the only way i can get the result of native calls to the javascript.

After hours of trial and error and googling, I got the fix. I added the call  pr.setKeepCallback(true); after creating the PluginResult object. And everything seems to be going fine.

This is how my modified code looks now.

public class MyPlugin extends Plugin {

  @Override
  public PluginResult execute(String action, JSONArray data, String callbackId) {
        
        this.callbackId = callbackId;
        
        /* .. some code ... */

        StartMyAsyncThread();
        
        PluginResult pr = new PluginResult(PluginResult.Status.NO_RESULT);
        pr.setKeepCallback(true);
        return pr;
    }
        
    
    public void resultOfAsyncThread(String message){
        
        PluginResult pr = new PluginResult(PluginResult.Status.OK, message);
        pr.setKeepCallback(true);
        this.success(pr, this.callbackId)
    }
    
}


I got the fix from this stackoverflow post.

No comments:

Post a Comment