Example usage for org.apache.cordova PluginResult PluginResult

List of usage examples for org.apache.cordova PluginResult PluginResult

Introduction

In this page you can find the example usage for org.apache.cordova PluginResult PluginResult.

Prototype

public PluginResult(Status status, List<PluginResult> multipartMessages) 

Source Link

Usage

From source file:com.ideateam.plugin.DownloadDB.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 * //w  ww.j ava  2 s .  c  o  m
 * @param action
 *            The action to execute.
 * @param args
 *            JSONArry of arguments for the plugin.
 * @param callbackContext
 *            The callback context from which we were invoked.
 */
@SuppressLint("NewApi")
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("downloadDB")) {

        activity = this.cordova.getActivity();

        JSONObject obj = new JSONObject(args.getString(0));
        dbName = obj.getString("nameDB");
        url = obj.getString("url");
        Log.d(TAG, "!!! download zip DB from url: " + url);

        zipPath = activity.getApplicationContext().getFilesDir().getPath();
        zipPath = zipPath.substring(0, zipPath.lastIndexOf("/")) + "/databases";

        Log.d(TAG, ".. !!! DB path: " + zipPath);

        this.callbackContext = callbackContext;
        isDownloaded = false;

        URL uri;
        try {
            uri = new URL(url);

            HttpURLConnection httpConnection = (HttpURLConnection) uri.openConnection();
            httpConnection.setDoInput(true);
            httpConnection.setDoOutput(true);
            httpConnection.setRequestMethod("GET");
            httpConnection.connect();
            if (httpConnection.getResponseCode() != 200) {
                Log.d(TAG, "..callbackContext.error ");
                callbackContext.error("Zip don't exists");
                ((CordovaActivity) this.cordova.getActivity())
                        .sendJavascript("UART.system.Helper.downloadDB('error')");
                Log.d(TAG, "..callbackContext.error ");
                callbackContext.error("Zip don't exists");
                ((CordovaActivity) this.cordova.getActivity())
                        .sendJavascript("UART.system.Helper.downloadDB('error')");

            } else {
                DownloadFile();

            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    } else if (action.equals("removeDB")) {

        cordova.getActivity().runOnUiThread(new Runnable() {

            public void run() {

                Log.d(TAG, "... removeDB name " + dbName);

                try {
                    JSONObject obj = new JSONObject(args.getString(0));

                    String dbName = obj.getString("nameDB");

                    DeviceDB dDB = GetDeviceDB(dbName);

                    int deletedRows = dDB.master_db.delete("Databases", "name='" + dbName + "'", null);
                    dDB.master_db.close();

                    File file = new File(dDB.cordovaDBPath + dDB.cordovaDBName);
                    Boolean isDeleted = file.delete();

                    Log.d(TAG, "..removeDB path " + dDB.cordovaDBPath + dDB.cordovaDBName + " isDeleted "
                            + isDeleted + " del rows " + deletedRows);

                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.OK, args.optString(0)));

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        });
    }

    else if (action.equals("sizeDB")) {

        cordova.getActivity().runOnUiThread(new Runnable() {

            JSONObject obj = new JSONObject(args.getString(0));
            String dbName = obj.getString("nameDB");

            DeviceDB dDB = GetDeviceDB(dbName);
            File file = new File(dDB.cordovaDBPath + dDB.cordovaDBName);

            public void run() {

                Log.d(TAG, ".. sizeDB dbName " + dbName);
                try {
                    CallbackResult(true, "" + file.length());
                    callbackContext.success("" + file.length());
                } catch (Exception e) {
                    //   Log.d(TAG, e.getMessage());

                }

            }
        });
    } else {
        return false;
    }
    Log.d(TAG, "..return from plugin");
    return true;
}

From source file:com.ideateam.plugin.DownloadDB.java

License:Apache License

private void CallbackResult(Boolean success, String msg) {

    Log.d(TAG, " ..CallbackResult " + success + "  " + msg);
    final CordovaActivity activity = (CordovaActivity) this.cordova.getActivity();

    if (success) {
        //activity.sendJavascript("UART.system.Helper.downloadDB('ok')");
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, msg));
    } else {//from  w  w w. java2 s .c om
        //activity.sendJavascript("UART.system.Helper.downloadDB('error')");
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, msg));
    }

}

From source file:com.ideateam.plugin.Emailer.java

License:Apache License

/**
* Executes the request and returns PluginResult.
*
* @param action            The action to execute.
* @param args              JSONArry of arguments for the plugin.
* @param callbackContext   The callback context from which we were invoked.
*//*from  w ww . jav a2  s. c o  m*/
@SuppressLint("NewApi")
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("emailer")) {

        if (!isOnline()) {
            Log.d(TAG, ".. no internet connetion");
            callbackContext
                    .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "No Internet Connection"));

        } else {

            JSONObject obj = new JSONObject(args.getString(0));

            String mail = obj.getString("mail");
            String subject = obj.getString("subject");
            String text = obj.getString("text");
            String attachFile = obj.getString("fileName");

            SendEmail(mail, subject, text, attachFile);

            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Mail sended"));
        }

    } else {
        return false;
    }
    return true;
}

From source file:com.ideateam.plugin.Version.java

License:Apache License

void CancelHandelr() {
    myTask.cancel(false);//ww  w .  j a  va2s.c  o  m
    callbackContext.success("db imported");
    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "Canceled"));
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

private void getUserProperty(final String key, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            UserPropertyService userPropertyService = InbeaconManager.getInstance().getUserPropertyService();
            if (userPropertyService.hasProperty(key)) {
                String val = userPropertyService.getPropertyString(key, null);
                if (val != null) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, val));
                    return;
                }/*from   w  w w  .ja  v a 2 s  .c  o m*/
                Long lval = userPropertyService.getPropertyLong(key, Long.MIN_VALUE);
                if (lval != Long.MIN_VALUE) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, lval));
                    return;
                }
                // must be double
                Double dval = userPropertyService.getPropertyDouble(key);
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, dval.floatValue()));
                return;
            }
            callbackContext.error("Property does not exist");
        }
    });
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

private void getPPID(final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            String ppid = InbeaconManager.getInstance().getPPID();
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, ppid));
        }/*from  ww  w.  jav a 2  s. c o  m*/
    });
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

private void hasTag(final String key, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {
            UserPropertyService userPropertyService = InbeaconManager.getInstance().getUserPropertyService();
            callbackContext.sendPluginResult(
                    new PluginResult(PluginResult.Status.OK, userPropertyService.hasTag(key)));
        }// w w  w. j  a v  a  2  s .c  om
    });
}

From source file:com.inbeacon.cordova.CordovaInbeaconManager.java

License:Apache License

/**
 * Send a new plugin result back to JavaScript, without closing callback
 *
 * @param data InBeacon event result containing message and extras
 */// w w w .  jav  a  2 s  . c  o m
private void sendUpdate(JSONObject data) {
    if (this.eventCallbackContext != null) {
        PluginResult result = new PluginResult(PluginResult.Status.OK, data);
        result.setKeepCallback(true);
        this.eventCallbackContext.sendPluginResult(result);
    }
}

From source file:com.initialxy.cordova.themeablebrowser.InAppChromeClient.java

License:Apache License

/**
 * Tell the client to display a prompt dialog to the user.
 * If the client returns true, WebView will assume that the client will
 * handle the prompt dialog and call the appropriate JsPromptResult method.
 *
 * The prompt bridge provided for the ThemeableBrowser is capable of executing any
 * oustanding callback belonging to the ThemeableBrowser plugin. Care has been
 * taken that other callbacks cannot be triggered, and that no other code
 * execution is possible./* w  w w  .j  ava2  s.c  o  m*/
 *
 * To trigger the bridge, the prompt default value should be of the form:
 *
 * gap-iab://<callbackId>
 *
 * where <callbackId> is the string id of the callback to trigger (something
 * like "ThemeableBrowser0123456789")
 *
 * If present, the prompt message is expected to be a JSON-encoded value to
 * pass to the callback. A JSON_EXCEPTION is returned if the JSON is invalid.
 *
 * @param view
 * @param url
 * @param message
 * @param defaultValue
 * @param result
 */
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue,
        JsPromptResult result) {
    // See if the prompt string uses the 'gap-iab' protocol. If so, the remainder should be the id of a callback to execute.
    if (defaultValue != null && defaultValue.startsWith("gap")) {
        if (defaultValue.startsWith("gap-iab://")) {
            PluginResult scriptResult;
            String scriptCallbackId = defaultValue.substring(10);
            if (scriptCallbackId.startsWith("ThemeableBrowser")) {
                if (message == null || message.length() == 0) {
                    scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray());
                } else {
                    try {
                        scriptResult = new PluginResult(PluginResult.Status.OK, new JSONArray(message));
                    } catch (JSONException e) {
                        scriptResult = new PluginResult(PluginResult.Status.JSON_EXCEPTION, e.getMessage());
                    }
                }
                this.webView.sendPluginResult(scriptResult, scriptCallbackId);
                result.confirm("");
                return true;
            }
        } else {
            // Anything else with a gap: prefix should get this message
            LOG.w(LOG_TAG, "ThemeableBrowser does not support Cordova API calls: " + url + " " + defaultValue);
            result.cancel();
            return true;
        }
    }
    return false;
}

From source file:com.initialxy.cordova.themeablebrowser.ThemeableBrowser.java

License:Apache License

/**
 * Executes the request and returns PluginResult.
 *
 * @param action          The action to execute.
 * @param args            The exec() arguments, wrapped with some Cordova helpers.
 * @param callbackContext The callback context used when calling back into JavaScript.
 * @return/*from   w ww . jav  a2s.  c om*/
 * @throws JSONException
 */
public boolean execute(String action, CordovaArgs args, final CallbackContext callbackContext)
        throws JSONException {
    if (action.equals("open")) {
        this.callbackContext = callbackContext;
        final String url = args.getString(0);
        String t = args.optString(1);
        if (t == null || t.equals("") || t.equals(NULL)) {
            t = SELF;
        }
        final String target = t;
        final Options features = parseFeature(args.optString(2));
        customSchema = features.customSchema;

        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String result = "";
                // SELF
                if (SELF.equals(target)) {
                    /* This code exists for compatibility between 3.x and 4.x versions of Cordova.
                     * Previously the Config class had a static method, isUrlWhitelisted(). That
                     * responsibility has been moved to the plugins, with an aggregating method in
                     * PluginManager.
                     */
                    Boolean shouldAllowNavigation = null;
                    if (url.startsWith("javascript:")) {
                        shouldAllowNavigation = true;
                    }
                    if (shouldAllowNavigation == null) {
                        shouldAllowNavigation = new Whitelist().isUrlWhiteListed(url);
                    }
                    if (shouldAllowNavigation == null) {
                        try {
                            Method gpm = webView.getClass().getMethod("getPluginManager");
                            PluginManager pm = (PluginManager) gpm.invoke(webView);
                            Method san = pm.getClass().getMethod("shouldAllowNavigation", String.class);
                            shouldAllowNavigation = (Boolean) san.invoke(pm, url);
                        } catch (NoSuchMethodException e) {
                        } catch (IllegalAccessException e) {
                        } catch (InvocationTargetException e) {
                        }
                    }
                    // load in webview
                    if (Boolean.TRUE.equals(shouldAllowNavigation)) {
                        webView.loadUrl(url);
                    }
                    //Load the dialer
                    else if (url.startsWith(WebView.SCHEME_TEL)) {
                        try {
                            Intent intent = new Intent(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse(url));
                            cordova.getActivity().startActivity(intent);
                        } catch (android.content.ActivityNotFoundException e) {
                            emitError(ERR_CRITICAL, String.format("Error dialing %s: %s", url, e.toString()));
                        }
                    }
                    // load in ThemeableBrowser
                    else {
                        result = showWebPage(url, features);
                    }
                }
                // SYSTEM
                else if (SYSTEM.equals(target)) {
                    result = openExternal(url);
                }
                // BLANK - or anything else
                else {
                    result = showWebPage(url, features);
                }

                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, result);
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        });
    } else if (action.equals("close")) {
        closeDialog();
    } else if (action.equals("injectScriptCode")) {
        String jsWrapper = null;
        if (args.getBoolean(1)) {
            jsWrapper = String.format("prompt(JSON.stringify([eval(%%s)]), 'gap-iab://%s')",
                    callbackContext.getCallbackId());
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectScriptFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('script'); c.src = %%s; c.onload = function() { prompt('', 'gap-iab://%s'); }; d.body.appendChild(c); })(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('script'); c.src = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleCode")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('style'); c.innerHTML = %%s; d.body.appendChild(c); prompt('', 'gap-iab://%s');})(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('style'); c.innerHTML = %s; d.body.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("injectStyleFile")) {
        String jsWrapper;
        if (args.getBoolean(1)) {
            jsWrapper = String.format(
                    "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %%s; d.head.appendChild(c); prompt('', 'gap-iab://%s');})(document)",
                    callbackContext.getCallbackId());
        } else {
            jsWrapper = "(function(d) { var c = d.createElement('link'); c.rel='stylesheet'; c.type='text/css'; c.href = %s; d.head.appendChild(c); })(document)";
        }
        injectDeferredObject(args.getString(0), jsWrapper);
    } else if (action.equals("show")) {
        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.show();
            }
        });
        PluginResult pluginResult = new PluginResult(PluginResult.Status.OK);
        pluginResult.setKeepCallback(true);
        this.callbackContext.sendPluginResult(pluginResult);
    } else if (action.equals("reload")) {
        if (inAppWebView != null) {
            this.cordova.getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    inAppWebView.reload();
                }
            });
        }
    } else {
        return false;
    }
    return true;
}