If you're a cordova developer, you may be facing this issue. Read how to execute a callback in java twice.

If you have a loop or something that needs that a callback be execute more than once (for example a download progress that is being executed on java) you may noticed that the callbacks, after of being executed one time, doesn't work anymore.

This issue is well known :

callbacks.success("somejson"); // Succesfully executed in javascript

// something else 
Boolean something = true;

// bla bla bla code !

callbacks.success("anotherJSON!!!"); // This will be never executed!

The callbacks for some reason, doesn't get executed because you are not keeping the callback (the function is ready and doesn't need to be executed anymore).

You can easily solve this problem using the following code :

PluginResult resultA = new PluginResult(PluginResult.Status.OK, "myfirstJSONResponse");
resultA.setKeepCallback(true);
callbacks.sendPluginResult(resultA);

// Some more code

Boolean something = true;

// bla bla bla code


PluginResult resultB = new PluginResult(PluginResult.Status.OK, "secondJSONResponse");
resultB.setKeepCallback(true);
callbacks.sendPluginResult(resultB);

Instead of use our callbacks , we will return a plugin result, you don't need to import anything (cordova needs to be imported obviously).

You need to use the previous example if your code is not async , if you need to execute a callback in async mode, you need first return something but without response like this :

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
   // Execute an asynchronous task
   cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            // Then you're allowed to execute more than twice a callback.
            PluginResult resultA = new PluginResult(PluginResult.Status.OK, "myfirstJSONResponse");
            resultA.setKeepCallback(true);
            callbacks.sendPluginResult(resultA);

            // Some more code

            Boolean something = true;

            // bla bla bla code


            PluginResult resultB = new PluginResult(PluginResult.Status.OK, "secondJSONResponse");
            resultB.setKeepCallback(true);
            callbacks.sendPluginResult(resultB);       
        }
   });



  PluginResult pluginResult = new  PluginResult(PluginResult.Status.NO_RESULT); 
  pluginResult.setKeepCallback(true); // Keep callback

  return true;
}

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors