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:org.aksw.simba.cetus.fox.FoxBasedTypeSearcher.java

protected void parseType(JSONObject entity, TypedNamedEntity ne, List<ExtendedTypedNamedEntity> surfaceForms)
        throws Exception {
    try {/*from www .  j av  a2  s.com*/

        if (entity != null && entity.has("means") && entity.has("beginIndex") && entity.has("ann:body")) {

            String uri = entity.getString("means");
            String body = entity.getString("ann:body");
            Object begin = entity.get("beginIndex");
            Object typeObject = entity.get("@type");
            String types[];
            if (typeObject instanceof JSONArray) {
                JSONArray typeArray = (JSONArray) typeObject;
                types = new String[typeArray.length()];
                for (int i = 0; i < types.length; ++i) {
                    types[i] = typeArray.getString(i);
                }
            } else {
                types = new String[] { typeObject.toString() };
            }
            URLDecoder.decode(uri, "UTF-8");
            if (begin instanceof JSONArray) {
                // for all indices
                for (int i = 0; i < ((JSONArray) begin).length(); ++i) {
                    addTypeIfOverlapping(ne, Integer.valueOf(((JSONArray) begin).getString(i)), body.length(),
                            types);
                }
            } else if (begin instanceof String) {
                addTypeIfOverlapping(ne, Integer.valueOf((String) begin), body.length(), types);
            } else if (LOGGER.isDebugEnabled())
                LOGGER.debug("Couldn't find index");
        }
    } catch (Exception e) {
        LOGGER.error("Got an Exception while parsing the response of FOX.", e);
        throw new Exception("Got an Exception while parsing the response of FOX.", e);
    }
}

From source file:com.android.dialer.omni.clients.OsmApi.java

/**
 * Fetches and returns Places by sending the provided request
 * @param request the JSON request//from w  ww . ja v a 2 s.  co  m
 * @return the list of matching places
 * @throws IOException
 * @throws JSONException
 */
private List<Place> getPlaces(String request) throws IOException, JSONException {
    List<Place> places = new ArrayList<Place>();
    // Post and parse request
    JSONObject obj = PlaceUtil.postJsonRequest(mProviderUrl, "data=" + URLEncoder.encode(request));
    JSONArray elements = obj.getJSONArray("elements");

    for (int i = 0; i < elements.length(); i++) {
        JSONObject element = elements.getJSONObject(i);

        Place place = new Place();
        place.setLatitude(element.getDouble("lat"));
        place.setLongitude(element.getDouble("lon"));

        JSONObject tags = element.getJSONObject("tags");
        JSONArray tagNames = tags.names();

        for (int j = 0; j < tagNames.length(); j++) {
            String tagName = tagNames.getString(j);
            String tagValue = tags.getString(tagName);

            // TODO: TAG_PHONE can contain multiple numbers "number1;number2"
            putTag(place, tagName, tagValue);
        }

        places.add(place);
    }
    return places;
}

From source file:com.norman0406.slimgress.API.Plext.Markup.java

public static Markup createByJSON(JSONArray json) throws JSONException {
    if (json.length() != 2) {
        Log.e("Markup", "invalid array size");
        return null;
    }/*  w  ww.  j  av  a  2 s.  c o m*/

    JSONObject markupObj = json.getJSONObject(1);

    Markup newMarkup = null;

    String markupString = json.getString(0);
    if (markupString.equals("SECURE"))
        newMarkup = new MarkupSecure(markupObj);
    else if (markupString.equals("SENDER"))
        newMarkup = new MarkupSender(markupObj);
    else if (markupString.equals("PLAYER"))
        newMarkup = new MarkupPlayer(markupObj);
    else if (markupString.equals("AT_PLAYER"))
        newMarkup = new MarkupATPlayer(markupObj);
    else if (markupString.equals("PORTAL"))
        newMarkup = new MarkupPortal(markupObj);
    else if (markupString.equals("TEXT"))
        newMarkup = new MarkupText(markupObj);
    else
        Log.w("Markup", "unknown markup type: " + markupString);

    return newMarkup;
}

From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java

public boolean execute(String action, JSONArray data, CallbackContext callbackContext) throws JSONException {
    Log.d(TAG, "$ " + action + "()");

    Boolean result = false;// ww  w  .j  a  va2  s.c  om

    if (BackgroundGeolocationService.ACTION_START.equalsIgnoreCase(action)) {
        result = true;
        if (!isStarting) {
            this.start(callbackContext);
        } else {
            callbackContext.error("- Waiting for previous start action to complete");
        }
    } else if (BackgroundGeolocationService.ACTION_STOP.equalsIgnoreCase(action)) {
        // No implementation to stop background-tasks with Android.  Just say "success"
        result = true;
        this.stop();
        callbackContext.success(0);
    } else if (ACTION_FINISH.equalsIgnoreCase(action)) {
        result = true;
        callbackContext.success();
    } else if (ACTION_ERROR.equalsIgnoreCase(action)) {
        result = true;
        this.onError(data.getString(1));
        callbackContext.success();
    } else if (ACTION_CONFIGURE.equalsIgnoreCase(action)) {
        result = true;
        configure(data.getJSONObject(0), callbackContext);
    } else if (ACTION_ADD_LOCATION_LISTENER.equalsIgnoreCase(action)) {
        result = true;
        addLocationListener(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_CHANGE_PACE.equalsIgnoreCase(action)) {
        result = true;
        if (!isEnabled) {
            Log.w(TAG, "- Cannot change pace while disabled");
            callbackContext.error("Cannot #changePace while disabled");
        } else {
            changePace(callbackContext, data);
        }
    } else if (BackgroundGeolocationService.ACTION_SET_CONFIG.equalsIgnoreCase(action)) {
        result = true;
        JSONObject config = data.getJSONObject(0);
        setConfig(config);
        callbackContext.success();
    } else if (ACTION_GET_STATE.equalsIgnoreCase(action)) {
        result = true;
        JSONObject state = this.getState();
        PluginResult response = new PluginResult(PluginResult.Status.OK, state);
        response.setKeepCallback(false);
        callbackContext.sendPluginResult(response);
    } else if (ACTION_ADD_MOTION_CHANGE_LISTENER.equalsIgnoreCase(action)) {
        result = true;
        this.addMotionChangeListener(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_GET_LOCATIONS.equalsIgnoreCase(action)) {
        result = true;
        getLocations(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_SYNC.equalsIgnoreCase(action)) {
        result = true;
        sync(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_GET_ODOMETER.equalsIgnoreCase(action)) {
        result = true;
        getOdometer(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_RESET_ODOMETER.equalsIgnoreCase(action)) {
        result = true;
        resetOdometer(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_ADD_GEOFENCE.equalsIgnoreCase(action)) {
        result = true;
        addGeofence(callbackContext, data.getJSONObject(0));
    } else if (BackgroundGeolocationService.ACTION_ADD_GEOFENCES.equalsIgnoreCase(action)) {
        result = true;
        addGeofences(callbackContext, data.getJSONArray(0));
    } else if (BackgroundGeolocationService.ACTION_REMOVE_GEOFENCE.equalsIgnoreCase(action)) {
        result = removeGeofence(data.getString(0));
        if (result) {
            callbackContext.success();
        } else {
            callbackContext.error("Failed to add geofence");
        }
    } else if (BackgroundGeolocationService.ACTION_REMOVE_GEOFENCES.equalsIgnoreCase(action)) {
        result = removeGeofences();
        if (result) {
            callbackContext.success();
        } else {
            callbackContext.error("Failed to add geofence");
        }
    } else if (BackgroundGeolocationService.ACTION_ON_GEOFENCE.equalsIgnoreCase(action)) {
        result = true;
        addGeofenceListener(callbackContext);
    } else if (BackgroundGeolocationService.ACTION_GET_GEOFENCES.equalsIgnoreCase(action)) {
        result = true;
        getGeofences(callbackContext);
    } else if (ACTION_PLAY_SOUND.equalsIgnoreCase(action)) {
        result = true;
        playSound(data.getInt(0));
        callbackContext.success();
    } else if (BackgroundGeolocationService.ACTION_GET_CURRENT_POSITION.equalsIgnoreCase(action)) {
        result = true;
        JSONObject options = data.getJSONObject(0);
        getCurrentPosition(callbackContext, options);
    } else if (BackgroundGeolocationService.ACTION_BEGIN_BACKGROUND_TASK.equalsIgnoreCase(action)) {
        // Android doesn't do background-tasks.  This is an iOS thing.  Just return a number.
        result = true;
        callbackContext.success(1);
    } else if (BackgroundGeolocationService.ACTION_CLEAR_DATABASE.equalsIgnoreCase(action)) {
        result = true;
        clearDatabase(callbackContext);
    } else if (ACTION_ADD_HTTP_LISTENER.equalsIgnoreCase(action)) {
        result = true;
        addHttpListener(callbackContext);
    } else if (ACTION_GET_LOG.equalsIgnoreCase(action)) {
        result = true;
        getLog(callbackContext);
    } else if (ACTION_EMAIL_LOG.equalsIgnoreCase(action)) {
        result = true;
        emailLog(callbackContext, data.getString(0));
    } else if (BackgroundGeolocationService.ACTION_INSERT_LOCATION.equalsIgnoreCase(action)) {
        result = true;
        insertLocation(data.getJSONObject(0), callbackContext);
    } else if (BackgroundGeolocationService.ACTION_GET_COUNT.equalsIgnoreCase(action)) {
        result = true;
        getCount(callbackContext);
    }
    return result;
}

From source file:com.amitshekhar.utils.PrefHelper.java

public static UpdateRowResponse updateRow(Context context, String tableName,
        List<RowDataRequest> rowDataRequests) {
    UpdateRowResponse updateRowResponse = new UpdateRowResponse();

    if (tableName == null) {
        return updateRowResponse;
    }/*from ww  w .j av a2s .  co m*/

    RowDataRequest rowDataKey = rowDataRequests.get(0);
    RowDataRequest rowDataValue = rowDataRequests.get(1);

    String key = rowDataKey.value;
    String value = rowDataValue.value;
    String dataType = rowDataValue.dataType;

    if (Constants.NULL.equals(value)) {
        value = null;
    }

    SharedPreferences preferences = context.getSharedPreferences(tableName, Context.MODE_PRIVATE);

    try {
        switch (dataType) {
        case DataType.TEXT:
            preferences.edit().putString(key, value).apply();
            updateRowResponse.isSuccessful = true;
            break;
        case DataType.INTEGER:
            preferences.edit().putInt(key, Integer.valueOf(value)).apply();
            updateRowResponse.isSuccessful = true;
            break;
        case DataType.LONG:
            preferences.edit().putLong(key, Long.valueOf(value)).apply();
            updateRowResponse.isSuccessful = true;
            break;
        case DataType.FLOAT:
            preferences.edit().putFloat(key, Float.valueOf(value)).apply();
            updateRowResponse.isSuccessful = true;
            break;
        case DataType.BOOLEAN:
            preferences.edit().putBoolean(key, Boolean.valueOf(value)).apply();
            updateRowResponse.isSuccessful = true;
            break;
        case DataType.STRING_SET:
            JSONArray jsonArray = new JSONArray(value);
            Set<String> stringSet = new HashSet<>();
            for (int i = 0; i < jsonArray.length(); i++) {
                stringSet.add(jsonArray.getString(i));
            }
            preferences.edit().putStringSet(key, stringSet).apply();
            updateRowResponse.isSuccessful = true;
            break;
        default:
            preferences.edit().putString(key, value).apply();
            updateRowResponse.isSuccessful = true;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return updateRowResponse;
}

From source file:com.android.i18n.addressinput.JsoMapTest.java

public void testGetKeys() throws Exception {
    JsoMap map = JsoMap.buildJsoMap(VALID_JSON);
    JSONArray keys = map.getKeys();
    assertNotNull(keys);/*from w  w w  .  j  av  a2s  .co  m*/
    assertEquals(3, keys.length());
    Set<String> keySet = new HashSet<String>(keys.length());
    for (int i = 0; i < keys.length(); i++) {
        keySet.add(keys.getString(i));
    }
    assertEquals(new HashSet<String>(Arrays.asList("a", "c", "d")), keySet);
}

From source file:com.phonegap.ContactAccessorSdk5.java

/**
 * Take the search criteria passed into the method and create a SQL WHERE clause.
 * @param fields the properties to search against
 * @param searchTerm the string to search for
 * @return an object containing the selection and selection args
 */// w  w w.  j a v  a2s . c o  m
private WhereOptions buildWhereClause(JSONArray fields, String searchTerm) {

    ArrayList<String> where = new ArrayList<String>();
    ArrayList<String> whereArgs = new ArrayList<String>();

    WhereOptions options = new WhereOptions();

    /*
     * Special case for when the user wants all the contacts
     */
    if ("%".equals(searchTerm)) {
        options.setWhere("(" + ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? )");
        options.setWhereArgs(new String[] { searchTerm });
        return options;
    }

    String key;
    try {
        //Log.d(LOG_TAG, "How many fields do we have = " + fields.length());
        for (int i = 0; i < fields.length(); i++) {
            key = fields.getString(i);

            if (key.startsWith("displayName")) {
                where.add("(" + dbMap.get(key) + " LIKE ? )");
                whereArgs.add(searchTerm);
            } else if (key.startsWith("name")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("nickname")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("phoneNumbers")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("emails")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("addresses")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("ims")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("organizations")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
            }
            //            else if (key.startsWith("birthday")) {
            //               where.add("(" + dbMap.get(key) + " LIKE ? AND " 
            //                     + ContactsContract.Data.MIMETYPE + " = ? )");                           
            //            }
            else if (key.startsWith("note")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE);
            } else if (key.startsWith("urls")) {
                where.add("(" + dbMap.get(key) + " LIKE ? AND " + ContactsContract.Data.MIMETYPE + " = ? )");
                whereArgs.add(searchTerm);
                whereArgs.add(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }

    // Creating the where string
    StringBuffer selection = new StringBuffer();
    for (int i = 0; i < where.size(); i++) {
        selection.append(where.get(i));
        if (i != (where.size() - 1)) {
            selection.append(" OR ");
        }
    }
    options.setWhere(selection.toString());

    // Creating the where args array
    String[] selectionArgs = new String[whereArgs.size()];
    for (int i = 0; i < whereArgs.size(); i++) {
        selectionArgs[i] = whereArgs.get(i);
    }
    options.setWhereArgs(selectionArgs);

    return options;
}

From source file:com.ponysdk.generator.PropertiesDictionnaryGenerator.java

@SuppressWarnings("unchecked")
private void generateDictionnary() throws FileNotFoundException, JSONException {
    log.info("Generating " + fileName);

    final String pathToFile = srcGeneratedDirectory + "/" + GeneratorHelper.getDirectoryFromPackage(packageName)
            + "/";

    final TokenGenerator tokenGenerator = new TokenGenerator();

    final FileReader fileReader = new FileReader("src-core/main/resources/spec/propertiesDictionnary.json");
    final JSONTokener tokener = new JSONTokener(fileReader);

    final CodeWriter writer = new CodeWriter();
    writer.addLine("package " + packageName + ";");
    writer.addNewLine();//from   w w w. j a v  a2 s  .com
    writer.addLine("public interface " + fileName + " {");
    writer.indentBlock();

    final JSONObject dico = new JSONObject(tokener);
    final Iterator<String> domainKeys = dico.sortedKeys();
    while (domainKeys.hasNext()) {
        // Domain
        final String domainKey = domainKeys.next();
        writer.addLine("public interface " + domainKey.toUpperCase() + " {");
        writer.indentBlock();

        final JSONObject domain = dico.getJSONObject(domainKey);
        final Iterator<String> keys = domain.sortedKeys();
        while (keys.hasNext()) {
            final String key = keys.next();
            final String keyUpper = GeneratorHelper.toUpperUnderscore(key);
            final JSONArray values = domain.getJSONArray(key);
            if (verbose)
                writer.addLine("public static final String " + keyUpper + " = \"" + key + "\";");
            else
                writer.addLine("public static final String " + keyUpper + " = \"" + tokenGenerator.nextToken()
                        + "\";");

            if (values.length() > 0) {
                writer.addLine("public interface " + keyUpper + "_" + " {");
                writer.indentBlock();
                for (int i = 0; i < values.length(); i++) {
                    if (verbose)
                        writer.addLine("public static final String "
                                + GeneratorHelper.toUpperUnderscore(values.getString(i)) + " = \""
                                + values.getString(i) + "\";");
                    else
                        writer.addLine("public static final String "
                                + GeneratorHelper.toUpperUnderscore(values.getString(i)) + " = \""
                                + tokenGenerator.nextToken() + "\";");
                }
                writer.unindentBlock();
                writer.addLine("}");
            }
        }

        writer.unindentBlock();
        writer.addLine("}");
        writer.addNewLine();
    }

    writer.unindentBlock();
    writer.addLine("}");

    final File file = new File(pathToFile);
    if (!file.exists())
        file.mkdirs();

    writer.saveToFile(pathToFile + fileName + ".java");
}

From source file:com.cpp255.bookbarcode.DouBanBookInfoXmlParser.java

public String parseJSONArraytoString(JSONArray array) {
    StringBuffer str = new StringBuffer();
    for (int i = 0; i < array.length(); i++) {
        try {/*from w  w  w .j  a  v a  2  s. co m*/
            str = str.append(array.getString(i)).append(" ");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return str.toString();
}

From source file:com.draekko.traypreferences.TraySharedPreferencesImpl.java

@Nullable
public Set<String> getStringSet(String key, @Nullable Set<String> defValues) {

    if (key == null || key.isEmpty()) {
        throw new IllegalArgumentException("invalid key parameter!");
    }/*w w  w .  j  a  v  a2 s.com*/

    Set<String> newVal = null;
    JSONObject jsonObject;

    String val = appPreferences.getString(key, null);
    if (val == null || val.isEmpty()) {
        return defValues;
    }

    newVal = new HashSet<>();
    try {
        jsonObject = new JSONObject(val);
        JSONArray stringset = jsonObject.getJSONArray("stringset");
        for (int loop = 0; loop < stringset.length(); loop++) {
            String data = stringset.getString(loop);
            newVal.add(data);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        return defValues;
    }
    return newVal;
}