Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

In this page you can find the example usage for org.json JSONArray getString.

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:com.maya.portAuthority.googleMaps.LocationTracker.java

private static List<String> makeList(JSONArray array) throws JSONException {
    List<String> output = new ArrayList<String>();
    for (int i = 0; i < array.length(); i++) {
        output.add(array.getString(i));
    }// w  w  w  .  j av  a 2s . c o  m
    return output;
}

From source file:com.rasrin.locale.formatter.plugin.LocaleFormatter.java

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

    try {/*from   w w  w  .  ja  va2  s .co  m*/

        if (action.equals("formatCurrency")) {

            if (args.length() < 3) {
                callbackContext.error("Expected 3 arguments.");
                return false;
            }

            String ilocale = args.getString(0);
            long amount = args.getLong(1);
            boolean debug = args.getBoolean(2);
            Locale locale = new Locale("en", "US");
            if (ilocale != null && ilocale.length() <= 5) {
                if (ilocale.indexOf('-') > 0) {
                    String[] parts = ilocale.split("-");
                    locale = new Locale(parts[0], parts[1]);
                }
            }

            NumberFormat formatter = NumberFormat.getCurrencyInstance(locale);
            String moneyString = formatter.format(amount);

            if (debug) {
                System.out.println("Called with locale: " + ilocale + " & amount: " + amount
                        + ". Formatted string is: " + moneyString);
            }

            callbackContext.success(moneyString);

            return true;

        } else {
            callbackContext.error("Unsupported operation");
            return false;
        }

    } catch (Exception ex) {
        callbackContext.error("Something went wrong: " + ex.getMessage());
        return false;
    }

}

From source file:plugin.geolocation.GeoBroker.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action       The action to execute.
 * @param args       JSONArry of arguments for the plugin.
 * @param callbackContext   The callback id used when calling back into JavaScript.
 * @return          True if the action was valid, or false if not.
 *///from   w ww.j  a  v a  2s .  c  o m
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    if (locationManager == null) {
        locationManager = (LocationManager) this.cordova.getActivity()
                .getSystemService(Context.LOCATION_SERVICE);
    }
    if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
            || locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        if (networkListener == null) {
            networkListener = new NetworkListener(locationManager, this);
        }
        if (gpsListener == null) {
            gpsListener = new GPSListener(locationManager, this);
        }

        if (action.equals("getLocation")) {
            boolean enableHighAccuracy = args.getBoolean(0);
            int maximumAge = args.getInt(1);
            String provider = (enableHighAccuracy
                    && locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
                            ? LocationManager.GPS_PROVIDER
                            : LocationManager.NETWORK_PROVIDER;
            Location last = this.locationManager.getLastKnownLocation(provider);
            // Check if we can use lastKnownLocation to get a quick reading and use less battery
            if (last != null && (System.currentTimeMillis() - last.getTime()) <= maximumAge) {
                PluginResult result = new PluginResult(PluginResult.Status.OK, this.returnLocationJSON(last));
                callbackContext.sendPluginResult(result);
            } else {
                this.getCurrentLocation(callbackContext, enableHighAccuracy, args.optInt(2, 60000));
            }
        } else if (action.equals("addWatch")) {
            String id = args.getString(0);
            boolean enableHighAccuracy = args.getBoolean(1);
            this.addWatch(id, callbackContext, enableHighAccuracy);
        } else if (action.equals("clearWatch")) {
            String id = args.getString(0);
            this.clearWatch(id);
        } else {
            return false;
        }
    } else {
        PluginResult.Status status = PluginResult.Status.NO_RESULT;
        String message = "Location API is not available for this device.";
        PluginResult result = new PluginResult(status, message);
        callbackContext.sendPluginResult(result);
    }
    return true;
}

From source file:com.justone.android.main.MainActivity.java

private ArrayList<ArrayList<String>> loadData(String viewName, String data) throws JSONException {

    viewName = "data";
    JSONObject jsonOb = new JSONObject(data);
    ArrayList<ArrayList<String>> tempResult = new ArrayList<ArrayList<String>>();
    try {//w  w w  . j  a  v  a2 s .  co m
        String viewData = jsonOb.getString(viewName);
        JSONArray jsonArray = new JSONArray(viewData);

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONArray tempJson = (JSONArray) jsonArray.opt(i);
            ArrayList<String> tempArray = new ArrayList<String>();
            tempArray.add(String.valueOf(nameToIdMap(tempJson.getString(0))));
            tempArray.add(String.valueOf(tempJson.getString(1)));
            tempArray.add(String.valueOf(tempJson.getString(2)));
            tempResult.add(tempArray);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    String id = jsonOb.getString("id");
    ArrayList<String> tempArray = new ArrayList<String>();
    tempArray.add(String.valueOf(nameToIdMap(jsonOb.getString("type") + "_id")));
    tempArray.add(id);
    tempArray.add("text");
    tempResult.add(tempArray);

    return tempResult;

}

From source file:com.panduka.weatherforecast.utils.DataResolver.java

/**
 * Extract Flags details from JSON array object
 *
 * @param jsonArray Flags details JSON array object
 * @return returns a String array of flags data
 *///ww w.  j a  v  a 2s  . com
private String[] createStringArray(JSONArray jsonArray) throws JSONException {
    ArrayList<String> dataArr = new ArrayList<>();
    for (int i = 0; i < jsonArray.length(); i++) {
        dataArr.add(jsonArray.getString(i));
    }
    return dataArr.toArray(new String[dataArr.size()]);
}

From source file:org.inspira.polivoto.threading.LittleServant.java

@Override
public void run() {
    try {/*from  w  w  w .ja  v a2s.c  o  m*/
        LogProvider.logMessage("Little Servant", "El capturista ya se report bienene");
        IOHandler ioHandler = new IOHandler(new DataInputStream(sock.getInputStream()),
                new DataOutputStream(sock.getOutputStream()));
        byte[] chunk = ioHandler.handleIncommingMessage();

        JSONObject json = new JSONObject(new String(accionesDeCliente.decrypt(chunk)));
        switch (json.getInt("content")) {
        case 1:
            this.ioHandler = ioHandler;
            boleta = json.getString("boleta");
            perfil = json.getString("perfil");

            // Recibimos la boleta del participante. Para llegar a ste punto
            // la boleta previamente est ya validada. Aqu hay oportunidad de
            // crecimiento al agregar tal vez algo para asegurarse de que no se
            // puede iniciar el proceso desde ste punto...
            /**
             * Consulta preguntas para participante *
             */
            int resp;
            JSONArray preguntasParticipante = accionesDeCliente.consultaPreguntasParticipante(boleta);
            tituloVotacion = accionesDeCliente.pideTituloDeVotacion();
            if (preguntasParticipante.length() > 0) {
                /**
                 * Consulta opciones para preguntas de participante *
                 */
                for (int i = 0; i < preguntasParticipante.length(); i++) {
                    title = preguntasParticipante.getString(i);
                    JSONArray jarr = accionesDeCliente.consultaOpcionesPreguntaParticipante(title);
                    opciones = new String[jarr.length()];
                    for (int k = 0; k < opciones.length; k++) {
                        opciones[k] = jarr.getString(k);
                    }
                    papeletas.put(i + 1, new InfoPapeleta(title, opciones));
                    launchPapeleta(papeletas.get(i + 1));
                }
            } else {
                resp = 24;
                System.out.println("El participante ha votado");
                ioHandler.writeInt(resp);
                sock.close();
            }
            break;
        case 2:
            sock.close();
            break;
        case 3:
            ioHandler = ioHandler;
            boleta = json.getString("boleta");
            perfil = json.getString("perfil");
            break;
        }
    } catch (IOException | JSONException | BadPaddingException | InvalidKeyException | IllegalBlockSizeException
            | NoSuchPaddingException | NoSuchAlgorithmException e) {
        e.printStackTrace();
        LogProvider.logMessage("M O R T O S ", "Sadly we came here");
        try {
            ioHandler.writeInt(-1);
        } catch (NullPointerException | IOException e1) {
            e1.printStackTrace();
        }
    }
}

From source file:se.leap.bitmaskclient.Provider.java

protected boolean hasEIP() {
    try {//from ww  w .  j  a  va  2s.  c  om
        JSONArray services = definition.getJSONArray(API_TERM_SERVICES); // returns ["openvpn"]
        for (int i = 0; i < API_EIP_TYPES.length + 1; i++) {
            try {
                // Walk the EIP types array looking for matches in provider's service definitions
                if (Arrays.asList(API_EIP_TYPES).contains(services.getString(i)))
                    return true;
            } catch (NullPointerException e) {
                e.printStackTrace();
                return false;
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return false;
            }
        }
    } catch (Exception e) {
        // TODO: handle exception
    }
    return false;
}

From source file:com.example.huma.al_malzma.helper.JsonHelper.java

/**
 * Creates a String array out of a json array.
 *
 * @param json The String containing the json array.
 * @return An array with the extracted strings or an
 * empty String array if an exception occurred.
 *///from w w w.  j a  va  2s.c om
public static String[] jsonArrayToStringArray(String json) {
    try {
        JSONArray jsonArray = new JSONArray(json);
        String[] stringArray = new String[jsonArray.length()];
        for (int i = 0; i < jsonArray.length(); i++) {
            stringArray[i] = jsonArray.getString(i);
        }
        return stringArray;
    } catch (JSONException e) {
        Log.e(TAG, "Error during Json processing: ", e);
    }
    return new String[0];
}

From source file:org.cgiar.ilri.odk.pull.backend.services.DeleteFormDataService.java

/**
 * This method is called whenever the service is called. The service might have already been up
 *  when called/*from   w  w w .j a  v  a 2  s  .  c o  m*/
 *
 * @param intent The intent used to call the service
 */
@Override
protected void onHandleIntent(Intent intent) {
    String formName = intent.getStringExtra(KEY_FORM_NAME);
    if (formName != null) {
        List<String> pulledFiles = new ArrayList<String>();
        //get list of ODK Pull files for this form from the server
        try {
            String jsonString = DataHandler.sendDataToServer(this, null,
                    DataHandler.URI_FETCH_FORM_FILE_NAMES + URLEncoder.encode(formName, "UTF-8"));
            JSONArray fileNames = new JSONObject(jsonString).getJSONArray("files");
            for (int index = 0; index < fileNames.length(); index++) {
                if (fileNames.getString(index).equals(Form.DEFAULT_CSV_FILE_NAME)) {
                    pulledFiles.add(fileNames.getString(index) + Form.SUFFIX_CSV);
                } else {
                    pulledFiles.add(fileNames.getString(index) + Form.SUFFIX_CSV);
                    pulledFiles.add(fileNames.getString(index) + Form.SUFFIX_CSV + Form.SUFFIX_IMPORTED);
                    pulledFiles.add(fileNames.getString(index) + Form.SUFFIX_DB);
                    pulledFiles.add(fileNames.getString(index) + Form.SUFFIX_DB + Form.SUFFIX_JOURNAL);
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //delete files that might have been pulled using the normal way
        File formDir = new File(Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX);
        if (formDir.exists() && formDir.exists()) {
            for (int index = 0; index < pulledFiles.size(); index++) {
                File file = new File(Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX
                        + File.separator + pulledFiles.get(index));
                if (file.exists()) {
                    file.delete();
                    Log.i(TAG, "Deleted " + file.getPath());
                } else {
                    Log.w(TAG, file.getPath() + " does not exist. Not deleting anything");
                }
            }
        } else {
            Log.w(TAG, formDir.getPath() + " does not exist. Not deleting anything");
        }
        //delete files that might have been pushed using adb
        File adbFormDir = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_")
                + Form.EXTERNAL_ITEM_SET_SUFFIX);
        if (adbFormDir.exists() && adbFormDir.exists()) {
            for (int index = 0; index < pulledFiles.size(); index++) {
                File file = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_")
                        + Form.EXTERNAL_ITEM_SET_SUFFIX + File.separator + pulledFiles.get(index));
                if (file.exists()) {
                    file.delete();
                    Log.i(TAG, "Deleted " + file.getPath());
                } else {
                    Log.w(TAG, file.getPath() + " does not exist. Not deleting anything");
                }
            }
        } else {
            Log.w(TAG, adbFormDir.getPath() + " does not exist. Not deleting anything");
        }
        DataHandler.deleteFormData(this, formName);
        String deletedFilesString = "";
        for (int i = 0; i < pulledFiles.size(); i++) {
            deletedFilesString = deletedFilesString + "\n - " + pulledFiles.get(i);
        }
        updateNotification(formName, getString(R.string.deleted_external_data_for_form),
                getString(R.string.the_following_files_were_deleted) + deletedFilesString);
    } else {
        Log.w(TAG, "The provided form name is null");
    }
}

From source file:org.loklak.api.learning.ConsoleLearning.java

@Override
public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization user,
        final JSONObjectWithDefault permissions) throws APIException {
    JSONObject json = new JSONObject(true).put("accepted", true);

    // unauthenticated users are rejected
    if (user.getIdentity().isAnonymous()) {
        json.put("accepted", false);
        json.put("reject-reason", "you must be logged in");
        return json;
    }//from w  ww  .ja  v a2  s .  c  o m
    String client = user.getIdentity().getClient();

    // to categorize the rule, we use project names and tags. Both can be omitted, in that case the project
    // is named "default" and the tag list is empty. Both methods can later be used to retrieve subsets of the
    // rule set
    String project = post.get("project", "default");
    String[] tagsl = post.get("tags", "").split(",");
    JSONArray tags = new JSONArray();
    for (String t : tagsl)
        tags.put(t);
    json.put("project", project);
    json.put("tags", tags);

    // parameters
    String action = post.get("action", "");
    if (action.length() == 0) {
        json.put("accepted", false);
        json.put("reject-reason",
                "you must submit a parameter 'action' containing either the word 'list', 'test', 'learn' or 'delete'");
        return json;
    }
    json.put("action", action);

    if (action.equals("list")) {
        Set<String> projectnames = DAO.susi.getRulesetNames(client);
        JSONObject projects = new JSONObject(true);
        for (String p : projectnames) {
            try {
                JsonTray t = DAO.susi.getRuleset(client, p);
                projects.put(p, t.toJSON().getJSONObject("console"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        json.put("projects", projects);
    } else {
        String name = post.get("name", "");
        if (name.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "you must submit a parameter 'name' containing the rule name");
            return json;
        }
        json.put("name", name);

        if (action.equals("delete")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.remove(name);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "deletion the console rule causes an error: " + e.getMessage());
            }
            return json;
        }

        String serviceURL = post.get("url", ""); // i.e. url=http://api.loklak.org/api/console.json?q=SELECT%20*%20FROM%20wikigeodata%20WHERE%20place='$query$';
        if (serviceURL.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "url parameter required");
            return json;
        }
        if (!serviceURL.contains("$query$")) {
            json.put("accepted", false);
            json.put("reject-reason", "the url must contain a string $query$");
            return json;
        }

        String test = post.get("test", "");
        if (test.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "a testquery parameter is required");
            return json;
        }

        // now test the api call
        byte[] serviceResponse = null;
        try {
            serviceResponse = ConsoleService.loadData(serviceURL, test);
        } catch (Exception e) {
            json.put("accepted", false);
            json.put("reject-reason", "the console test load resulted in an error: " + e.getMessage());
            return json;
        }

        // try to find the correct jsonPath automatically
        JSONArray path_computed = new JSONArray();
        Object serviceObject = null;
        try {
            serviceObject = new JSONObject(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
        } catch (JSONException e) {
        }
        if (serviceObject != null && ((JSONObject) serviceObject).length() > 0) {
            for (String s : ((JSONObject) serviceObject).keySet()) {
                if (((JSONObject) serviceObject).get(s) instanceof JSONArray)
                    path_computed.put("$." + s);
            }
        } else {
            try {
                serviceObject = new JSONArray(new JSONTokener(new ByteArrayInputStream(serviceResponse)));
            } catch (JSONException e) {
            }
            if (serviceObject != null && ((JSONArray) serviceObject).length() > 0) {
                path_computed.put("$");
            }
        }

        String path = post.get("path", "");
        if (path.length() == 0) {
            if (path_computed.length() == 1) {
                path = path_computed.getString(0);
            } else {
                json.put("accepted", false);
                json.put("reject-reason",
                        "a data parameter containing the jsonpath to the data object is required. "
                                + (path_computed.length() < 1 ? ""
                                        : "Suggested paths: " + path_computed.toString(0)));
                return json;
            }
        }

        JSONArray data = ConsoleService
                .parseJSONPath(new JSONTokener(new ByteArrayInputStream(serviceResponse)), path);
        if (data == null || data.length() == 0) {
            json.put("accepted", false);
            json.put("reject-reason", "the jsonPath from data object did not recognize an array object");
            return json;
        }

        // find out the attributes in the data object
        Set<String> a = new LinkedHashSet<>();
        for (int i = 0; i < data.length(); i++)
            a.addAll(data.getJSONObject(i).keySet());
        for (int i = 0; i < data.length(); i++) {
            Set<String> doa = data.getJSONObject(i).keySet();
            Iterator<String> j = a.iterator();
            while (j.hasNext())
                if (!doa.contains(j.next()))
                    j.remove();
        }
        JSONArray attributes = new JSONArray();
        for (String s : a)
            attributes.put(s);
        json.put("path_computed", path_computed);

        // construct a new rule
        JSONObject consolerule = new JSONObject(true);
        consolerule.put("example", "http://127.0.0.1:4000/susi/console.json?q=%22SELECT%20*%20FROM%20" + name
                + "%20WHERE%20query=%27" + test + "%27;%22");
        consolerule.put("url", serviceURL);
        consolerule.put("test", test);
        consolerule.put("parser", "json");
        consolerule.put("path", path);
        consolerule.put("attributes", attributes);
        //consolerule.put("author", user.getIdentity().getName());
        //consolerule.put("license", "provided by " + user.getIdentity().getName() + ", licensed as public domain");
        json.put("console", new JSONObject().put(name, consolerule));

        // testing was successful, now decide which action to take: report or store
        if (action.equals("test")) {
            json.put("data", data);
            return json;
        }

        if (action.equals("learn")) {
            try {
                JsonTray tray = DAO.susi.getRuleset(client, project);
                if (!tray.has("console"))
                    tray.put("console", new JSONObject(), true);
                JSONObject console = tray.getJSONObject("console");
                console.put(name, consolerule);
                tray.commit();
            } catch (IOException e) {
                e.printStackTrace();
                json.put("accepted", false);
                json.put("reject-reason", "storing the console rule causes an error: " + e.getMessage());
            }
            return json;
        }
    }

    // fail case
    json.put("accepted", false);
    json.put("reject-reason", "no valid action given");
    return json;
}