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.capriza.plugins.Notification.java

License:Apache License

/**
 * Builds and shows a native Android confirm dialog with given title, message, buttons.
 * This dialog only shows up to 3 buttons.  Any labels after that will be ignored.
 * The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
 *
 * @param message           The message the dialog should display
 * @param title             The title of the dialog
 * @param buttonLabels      A comma separated list of button labels (Up to 3 buttons)
 * @param callbackContext   The callback context.
 *///w w  w  . j  a  v a2  s  .c o  m
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels,
        final CallbackContext callbackContext) {
    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable(true);

            // First button
            if (buttonLabels.length() > 0) {
                try {
                    dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on first button.");
                }
            }

            // Second button
            if (buttonLabels.length() > 1) {
                try {
                    dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on second button.");
                }
            }

            // Third button
            if (buttonLabels.length() > 2) {
                try {
                    dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on third button.");
                }
            }
            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
                }
            });

            changeTextDirection(dlg);
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.capriza.plugins.Notification.java

License:Apache License

/**
 * Builds and shows a native Android prompt dialog with given title, message, buttons.
 * This dialog only shows up to 3 buttons.  Any labels after that will be ignored.
 * The following results are returned to the JavaScript callback identified by callbackId:
 *     buttonIndex         Index number of the button selected
 *     input1            The text entered in the prompt dialog box
 *
 * @param message           The message the dialog should display
 * @param title             The title of the dialog
 * @param buttonLabels      A comma separated list of button labels (Up to 3 buttons)
 * @param callbackContext   The callback context.
 *//*from   w  w w.  j av  a2 s . c  o  m*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels,
        final String defaultText, final CallbackContext callbackContext) {

    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            final EditText promptInput = new EditText(cordova.getActivity());
            promptInput.setHint(defaultText);
            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setMessage(message);
            dlg.setTitle(title);
            dlg.setCancelable(true);

            dlg.setView(promptInput);

            final JSONObject result = new JSONObject();

            // First button
            if (buttonLabels.length() > 0) {
                try {
                    dlg.setNegativeButton(buttonLabels.getString(0), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 1);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                LOG.d(LOG_TAG, "JSONException on first button.", e);
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on first button.");
                }
            }

            // Second button
            if (buttonLabels.length() > 1) {
                try {
                    dlg.setNeutralButton(buttonLabels.getString(1), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 2);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                LOG.d(LOG_TAG, "JSONException on second button.", e);
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on second button.");
                }
            }

            // Third button
            if (buttonLabels.length() > 2) {
                try {
                    dlg.setPositiveButton(buttonLabels.getString(2), new AlertDialog.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            try {
                                result.put("buttonIndex", 3);
                                result.put("input1",
                                        promptInput.getText().toString().trim().length() == 0 ? defaultText
                                                : promptInput.getText());
                            } catch (JSONException e) {
                                LOG.d(LOG_TAG, "JSONException on third button.", e);
                            }
                            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                        }
                    });
                } catch (JSONException e) {
                    LOG.d(LOG_TAG, "JSONException on third button.");
                }
            }
            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    try {
                        result.put("buttonIndex", 0);
                        result.put("input1", promptInput.getText().toString().trim().length() == 0 ? defaultText
                                : promptInput.getText());
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
                }
            });

            changeTextDirection(dlg);
        };
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.capriza.plugins.Notification.java

License:Apache License

/**
Show list of items.//  www  .j  ava 2s .  c  om
Custom by Bar
*/
public synchronized void list(final String title, final JSONArray buttonLabels,
        final CallbackContext callbackContext) {
    final CordovaInterface cordova = this.cordova;

    Runnable runnable = new Runnable() {
        public void run() {
            AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
            dlg.setTitle(title);
            dlg.setCancelable(true);

            final String[] items = new String[buttonLabels.length()];

            for (int i = 0; i < buttonLabels.length(); i++) {
                try {
                    items[i] = buttonLabels.getString(i);
                } catch (JSONException e) {
                }
            }

            dlg.setItems(items, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, which + 1));
                }
            });

            dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
                public void onCancel(DialogInterface dialog) {
                    dialog.dismiss();
                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.OK, items.length + 1));
                }
            });

            dlg.create();
            dlg.show();
        }
    };
    this.cordova.getActivity().runOnUiThread(runnable);
}

From source file:com.clevertap.cordova.CleverTapPlugin.java

@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    Log.d(LOG_TAG, "handling action " + action);

    boolean haveError = false;
    String errorMsg = "unhandled CleverTapPlugin action";

    PluginResult result = null;/*from w  ww. j av a 2 s.  c o  m*/

    if (!checkCleverTapInitialized()) {
        result = new PluginResult(PluginResult.Status.ERROR, "CleverTap API not initialized");
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("registerPush")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    // not required for Android here but handle as its in the JS interface
    else if (action.equals("setPushTokenAsString")) {
        result = new PluginResult(PluginResult.Status.NO_RESULT);
        result.setKeepCallback(true);
        callbackContext.sendPluginResult(result);
        return true;
    }

    else if (action.equals("setDebugLevel")) {
        int level = (args.length() == 1 ? args.getInt(0) : -1);
        if (level >= 0) {
            CleverTapAPI.setDebugLevel(level);
            result = new PluginResult(PluginResult.Status.NO_RESULT);
            result.setKeepCallback(true);
            callbackContext.sendPluginResult(result);
            return true;
        }

    }

    else if (action.equals("enablePersonalization")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                cleverTap.enablePersonalization();
                PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;

    }

    else if (action.equals("recordEventWithName")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("recordEventWithNameAndProps")) {
        String eventName = null;
        JSONObject jsonProps;
        HashMap<String, Object> _props = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                eventName = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "eventName cannot be null";
            }
            if (!args.isNull(1)) {
                jsonProps = args.getJSONObject(1);
                try {
                    _props = toMap(jsonProps);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing event properties";
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _eventName = eventName;
            final HashMap<String, Object> props = _props;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.event.push(_eventName, props);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("recordChargedEventWithDetailsAndItems")) {
        JSONObject jsonDetails;
        JSONArray jsonItems;
        HashMap<String, Object> _details = null;
        ArrayList<HashMap<String, Object>> _items = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                jsonDetails = args.getJSONObject(0);
                try {
                    _details = toMap(jsonDetails);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
            if (!args.isNull(1)) {
                jsonItems = args.getJSONArray(1);
                try {
                    _items = toArrayListOfStringObjectMaps(jsonItems);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "Arg cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final HashMap<String, Object> details = _details;
            final ArrayList<HashMap<String, Object>> items = _items;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        cleverTap.event.push(CleverTapAPI.CHARGED_EVENT, details, items);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (InvalidEventNameException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;
        }
    }

    else if (action.equals("eventGetFirstTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double first = cleverTap.event.getFirstTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) first);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetLastTime")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    double lastTime = cleverTap.event.getLastTime(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, (float) lastTime);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetOccurrences")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    int num = cleverTap.event.getCount(eventName);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, num);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("eventGetDetails")) {
        final String eventName = (args.length() == 1 ? args.getString(0) : null);
        if (eventName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    EventDetail details = cleverTap.event.getDetails(eventName);
                    try {
                        JSONObject jsonDetails = CleverTapPlugin.eventDetailsToJSON(details);
                        PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    } catch (JSONException e) {
                        PluginResult _result = new PluginResult(PluginResult.Status.ERROR,
                                e.getLocalizedMessage());
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                }
            });
            return true;

        } else {
            errorMsg = "eventName cannot be null";
        }
    }

    else if (action.equals("getEventHistory")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                Map<String, EventDetail> history = cleverTap.event.getHistory();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.eventHistoryToJSON(history);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

    else if (action.equals("setLocation")) {
        Double lat = null;
        Double lon = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                lat = args.getDouble(0);
            } else {
                haveError = true;
                errorMsg = "lat cannot be null";
            }
            if (!args.isNull(1)) {
                lon = args.getDouble(1);
            } else {
                haveError = true;
                errorMsg = "lon cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final Location location = new Location("CleverTapPlugin");
            location.setLatitude(lat);
            location.setLongitude(lon);
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.updateLocation(location);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSet")) {
        JSONObject jsonProfile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonProfile = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonProfile = jsonProfile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    try {
                        HashMap<String, Object> profile = toMap(_jsonProfile);
                        String dob = (String) profile.get("DOB");
                        if (dob != null) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
                            try {
                                Date date = format.parse(dob);
                                profile.put("DOB", date);
                            } catch (ParseException e) {
                                profile.remove("DOB");
                                Log.d(LOG_TAG, "invalid DOB format in profileSet");
                            }
                        }

                        cleverTap.profile.push(profile);

                    } catch (Exception e) {
                        Log.d(LOG_TAG, "Error setting profile " + e.getLocalizedMessage());
                    }

                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });

            return true;
        }
    }

    else if (action.equals("profileSetGraphUser")) {
        JSONObject jsonGraphUser = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGraphUser = args.getJSONObject(0);
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final JSONObject _jsonGraphUser = jsonGraphUser;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.pushFacebookUser(_jsonGraphUser);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileSetGooglePlusUser")) {
        JSONObject jsonGooglePlusUser;
        HashMap<String, Object> _profile = null;

        if (args.length() == 1) {
            if (!args.isNull(0)) {
                jsonGooglePlusUser = args.getJSONObject(0);
                try {
                    _profile = toMapFromGooglePlusUser(jsonGooglePlusUser);
                } catch (JSONException e) {
                    haveError = true;
                    errorMsg = "Error parsing arg " + e.getLocalizedMessage();
                }
            } else {
                haveError = true;
                errorMsg = "profile cannot be null";
            }

        } else {
            haveError = true;
            errorMsg = "Expected 1 argument";
        }

        if (!haveError) {
            final HashMap<String, Object> profile = _profile;
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.push(profile);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileGetProperty")) {
        final String propertyName = (args.length() == 1 ? args.getString(0) : null);
        if (propertyName != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    PluginResult _result;
                    Object prop = cleverTap.profile.getProperty(propertyName);

                    if (prop instanceof JSONArray) {
                        JSONArray _prop = (JSONArray) prop;
                        _result = new PluginResult(PluginResult.Status.OK, _prop);

                    } else {
                        String _prop;
                        if (prop != null) {
                            _prop = prop.toString();
                        } else {
                            _prop = null;
                        }
                        _result = new PluginResult(PluginResult.Status.OK, _prop);
                    }

                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "propertyName cannot be null";
        }
    }

    else if (action.equals("profileGetCleverTapID")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                String CleverTapID = cleverTap.getCleverTapID();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, CleverTapID);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("profileRemoveValueForKey")) {
        final String key = (args.length() == 1 ? args.getString(0) : null);
        if (key != null) {
            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeValueForKey(key);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;

        } else {
            errorMsg = "property key cannot be null";
        }
    }

    else if (action.equals("profileSetMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.setMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.addMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    } else if (action.equals("profileRemoveMultiValues")) {
        String key = null;
        JSONArray values = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                values = args.getJSONArray(1);
                if (values == null) {
                    haveError = true;
                    errorMsg = "values cannot be null";
                }
            } else {
                haveError = true;
                errorMsg = "values cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final ArrayList<String> _values = new ArrayList<String>();
            try {
                for (int i = 0; i < values.length(); i++) {
                    _values.add(values.get(i).toString());
                }

                cordova.getThreadPool().execute(new Runnable() {
                    public void run() {
                        cleverTap.profile.removeMultiValuesForKey(_key, _values);
                        PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                        _result.setKeepCallback(true);
                        callbackContext.sendPluginResult(_result);
                    }
                });

                return true;

            } catch (Exception e) {
                // no-op
            }
        }
    }

    else if (action.equals("profileAddMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.addMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("profileRemoveMultiValue")) {
        String key = null;
        String value = null;

        if (args.length() == 2) {
            if (!args.isNull(0)) {
                key = args.getString(0);
            } else {
                haveError = true;
                errorMsg = "key cannot be null";
            }
            if (!args.isNull(1)) {
                value = args.getString(1);
            } else {
                haveError = true;
                errorMsg = "value cannot be null";
            }
        } else {
            haveError = true;
            errorMsg = "Expected 2 arguments";
        }

        if (!haveError) {
            final String _key = key;
            final String _value = value;

            cordova.getThreadPool().execute(new Runnable() {
                public void run() {
                    cleverTap.profile.removeMultiValueForKey(_key, _value);
                    PluginResult _result = new PluginResult(PluginResult.Status.NO_RESULT);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            });
            return true;
        }
    }

    else if (action.equals("sessionGetTimeElapsed")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getTimeElapsed();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetTotalVisits")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getTotalVisits();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetScreenCount")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int count = cleverTap.session.getScreenCount();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, count);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetPreviousVisitTime")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                int time = cleverTap.session.getPreviousVisitTime();
                PluginResult _result = new PluginResult(PluginResult.Status.OK, time);
                _result.setKeepCallback(true);
                callbackContext.sendPluginResult(_result);
            }
        });
        return true;
    }

    else if (action.equals("sessionGetUTMDetails")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                UTMDetail details = cleverTap.session.getUTMDetails();
                try {
                    JSONObject jsonDetails = CleverTapPlugin.utmDetailsToJSON(details);
                    PluginResult _result = new PluginResult(PluginResult.Status.OK, jsonDetails);
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                } catch (JSONException e) {
                    PluginResult _result = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                    _result.setKeepCallback(true);
                    callbackContext.sendPluginResult(_result);
                }
            }
        });
        return true;
    }

    result = new PluginResult(PluginResult.Status.ERROR, errorMsg);
    result.setKeepCallback(true);
    callbackContext.sendPluginResult(result);
    return true;
}

From source file:com.cloudant.sync.cordova.CloudantSyncPlugin.java

License:Open Source License

/**
 * Deletes an index//from  ww w. ja  va2 s. c  om
 * @param documentStoreName - The name of the DocumentStore
 * @param indexName - The name of the index to delete
 * @param callbackContext - The javascript callback to execute when complete or errored
 */
private void deleteIndexNamed(final String documentStoreName, final String indexName,
        final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        @Override
        public void run() {
            try {
                if (indexName == null) {
                    throw new Exception("indexName cannot be null");
                }

                DocumentStore ds = getDocumentStore(documentStoreName);
                ds.query().deleteIndex(indexName);
                PluginResult r = new PluginResult(PluginResult.Status.OK, true);
                callbackContext.sendPluginResult(r);
            } catch (Exception e) {
                callbackContext.error(e.getMessage());
            }
        }
    });
}

From source file:com.coloreight.plugin.clipboard.Clipboard.java

License:Open Source License

public void copy(final String text, final CallbackContext callbackContext) {
    cordova.getActivity().runOnUiThread(new Runnable() {
        public void run() {
            ClipboardManager clipboard = (ClipboardManager) cordova.getActivity()
                    .getSystemService(Context.CLIPBOARD_SERVICE);

            try {
                ClipData clip = ClipData.newPlainText("Public.Text", text);

                clipboard.setPrimaryClip(clip);

                callbackContext.success(text);
            } catch (Exception e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, e.toString()));
            }//from   ww  w .  jav  a2  s  .  co  m
        }
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

@Override
protected void pluginInitialize() {
    super.pluginInitialize();

    FacebookSdk.sdkInitialize(this.cordova.getActivity().getApplicationContext());

    fbCallbackManager = CallbackManager.Factory.create();

    LoginManager.getInstance().registerCallback(fbCallbackManager, new FacebookCallback<LoginResult>() {
        @Override/*  www . j  av a 2  s .  c  o  m*/
        public void onSuccess(LoginResult loginResult) {
            try {
                JSONObject json = new JSONObject();

                json.put("userId", loginResult.getAccessToken().getUserId());
                json.put("accessToken", loginResult.getAccessToken().getToken());
                json.put("hasWritePermissions",
                        loginResult.getAccessToken().getPermissions().contains("publish_actions"));

                PluginResult pluginResult = new PluginResult(PluginResult.Status.OK, json);

                Log.v(TAG, "Facebook SDK auth success -> sended data: " + json.toString());
                callbackContext.sendPluginResult(pluginResult);
            } catch (JSONException e) {
                PluginResult pluginResult = new PluginResult(PluginResult.Status.ERROR,
                        e.getLocalizedMessage());

                callbackContext.sendPluginResult(pluginResult);
            }
        }

        @Override
        public void onCancel() {
            Log.v(TAG, "Facebook auth canceled");

            callbackContext.error("Facebook auth cancelled");
        }

        @Override
        public void onError(FacebookException exception) {
            if (exception instanceof FacebookAuthorizationException) {
                if (AccessToken.getCurrentAccessToken() != null) {
                    LoginManager.getInstance().logOut();
                }
            }

            Log.v(TAG, "Facebook auth error -> message:" + exception.getLocalizedMessage());

            callbackContext.error("Facebook auth error -> message:" + exception.getLocalizedMessage());
        }
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void canUseTwitterSystemAccount(final CallbackContext callbackContext) {

    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;/*from   w  ww  . j  a v a  2  s.  c  o  m*/

            Account[] twitterAccounts = accountManager.getAccountsByType("com.twitter.android.auth.login");

            // Twitter doesn't allow to get user's tokens from native account which signed by custom app
            // therefore the method returns false

            //pluginResult = new PluginResult(PluginResult.Status.OK, (twitterAccounts.length > 0));

            pluginResult = new PluginResult(PluginResult.Status.OK, false);
            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void getTwitterSystemAccounts(final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;// www  .j  a v  a  2  s  .co m
            JSONObject json = new JSONObject();
            JSONArray accounts = new JSONArray();

            Account[] twitterAccounts = accountManager.getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        JSONObject account = new JSONObject();

                        account.put("userName", twitterAccounts[i].name);

                        accounts.put(account);

                        json.put("accounts", accounts);
                    }

                    pluginResult = new PluginResult(PluginResult.Status.OK, json);
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
            }

            pluginResult.setKeepCallback(true);
            callbackContext.sendPluginResult(pluginResult);
        }
    });
}

From source file:com.coloreight.plugin.socialAuth.SocialAuth.java

License:Open Source License

public void getTwitterSystemAccount(final String networkUserName, final CallbackContext callbackContext) {
    cordova.getThreadPool().execute(new Runnable() {
        public void run() {

            PluginResult pluginResult;/*from w  ww  .j  a v  a  2s  .  c o  m*/
            final JSONObject json = new JSONObject();
            final JSONObject account = new JSONObject();

            final Account[] twitterAccounts = accountManager
                    .getAccountsByType("com.twitter.android.auth.login");

            try {
                if (twitterAccounts.length > 0) {
                    json.put("granted", true);

                    for (int i = 0; i < twitterAccounts.length; i++) {
                        if (twitterAccounts[i].name.equals(networkUserName)) {
                            account.put("userName", twitterAccounts[i].name);

                            final Account twitterAccount = twitterAccounts[i];

                            accountManager.getAuthToken(twitterAccount, "com.twitter.android.oauth.token", null,
                                    false, new AccountManagerCallback<Bundle>() {
                                        @Override
                                        public void run(AccountManagerFuture<Bundle> accountManagerFuture) {
                                            try {
                                                Bundle bundle = accountManagerFuture.getResult();

                                                if (bundle.containsKey(AccountManager.KEY_INTENT)) {
                                                    Intent intent = bundle
                                                            .getParcelable(AccountManager.KEY_INTENT);

                                                    //clear the new task flag just in case, since a result is expected
                                                    int flags = intent.getFlags();
                                                    flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                    intent.setFlags(flags);

                                                    requestedTwitterAccountName = networkUserName;

                                                    cordova.getActivity().startActivityForResult(intent,
                                                            TWITTER_OAUTH_REQUEST);
                                                } else {
                                                    account.put("oauth_token",
                                                            bundle.getString(AccountManager.KEY_AUTHTOKEN));

                                                    accountManager.getAuthToken(twitterAccount,
                                                            "com.twitter.android.oauth.token.secret", null,
                                                            false, new AccountManagerCallback<Bundle>() {
                                                                @Override
                                                                public void run(
                                                                        AccountManagerFuture<Bundle> accountManagerFuture) {
                                                                    try {
                                                                        Bundle bundle = accountManagerFuture
                                                                                .getResult();

                                                                        if (bundle.containsKey(
                                                                                AccountManager.KEY_INTENT)) {
                                                                            Intent intent = bundle
                                                                                    .getParcelable(
                                                                                            AccountManager.KEY_INTENT);

                                                                            //clear the new task flag just in case, since a result is expected
                                                                            int flags = intent.getFlags();
                                                                            flags &= ~Intent.FLAG_ACTIVITY_NEW_TASK;
                                                                            intent.setFlags(flags);

                                                                            requestedTwitterAccountName = networkUserName;

                                                                            cordova.getActivity()
                                                                                    .startActivityForResult(
                                                                                            intent,
                                                                                            TWITTER_OAUTH_REQUEST);
                                                                        } else {
                                                                            account.put("oauth_token_secret",
                                                                                    bundle.getString(
                                                                                            AccountManager.KEY_AUTHTOKEN));

                                                                            json.put("data", account);

                                                                            Log.v(TAG, "Account data: "
                                                                                    + json.toString());

                                                                            PluginResult pluginResult = new PluginResult(
                                                                                    PluginResult.Status.OK,
                                                                                    json);
                                                                            pluginResult.setKeepCallback(true);
                                                                            callbackContext.sendPluginResult(
                                                                                    pluginResult);
                                                                        }

                                                                    } catch (Exception e) {
                                                                        PluginResult pluginResult = new PluginResult(
                                                                                PluginResult.Status.ERROR,
                                                                                e.getLocalizedMessage());
                                                                        pluginResult.setKeepCallback(true);
                                                                        callbackContext
                                                                                .sendPluginResult(pluginResult);
                                                                    }
                                                                }
                                                            }, null);
                                                }

                                            } catch (Exception e) {
                                                PluginResult pluginResult = new PluginResult(
                                                        PluginResult.Status.ERROR, e.getLocalizedMessage());
                                                pluginResult.setKeepCallback(true);
                                                callbackContext.sendPluginResult(pluginResult);
                                            }
                                        }
                                    }, null);
                        }
                    }
                } else {
                    json.put("code", "0");
                    json.put("message", "no have twitter accounts");

                    pluginResult = new PluginResult(PluginResult.Status.ERROR, json);
                    pluginResult.setKeepCallback(true);
                    callbackContext.sendPluginResult(pluginResult);
                }
            } catch (JSONException e) {
                pluginResult = new PluginResult(PluginResult.Status.ERROR, e.getLocalizedMessage());
                pluginResult.setKeepCallback(true);
                callbackContext.sendPluginResult(pluginResult);
            }
        }
    });
}