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:at.alladin.rmbt.android.util.GetMapOptionsInfoTask.java

/**
 * /*w w w  .  j  av  a2s  .  co  m*/
 */
@Override
protected void onPostExecute(final JSONObject result) {
    if (serverConn.hasError())
        hasError = true;
    else if (result != null) {
        try {
            final JSONObject mapSettingsObject = result.getJSONObject("mapfilter");

            // /

            // ////////////////////////////////////////////////////
            // MAP / CHOOSE

            final JSONArray mapTypeArray = mapSettingsObject.getJSONArray("mapTypes");

            //                Log.d(DEBUG_TAG, mapTypeArray.toString(4));

            // /

            final ArrayList<MapListSection> mapListSectionList = new ArrayList<MapListSection>();

            for (int cnt = 0; cnt < mapTypeArray.length(); cnt++) {

                final JSONObject t = mapTypeArray.getJSONObject(cnt);

                final String sectionTitle = t.getString("title");

                final JSONArray objectOptionsArray = t.getJSONArray("options");

                // /

                final List<MapListEntry> mapListEntryList = new ArrayList<MapListEntry>();

                for (int cnt2 = 0; cnt2 < objectOptionsArray.length(); cnt2++) {

                    final JSONObject s = objectOptionsArray.getJSONObject(cnt2);

                    final String entryTitle = s.getString("title");
                    final String entrySummary = s.getString("summary");
                    final String value = s.getString("map_options");
                    final String overlayType = s.getString("overlay_type");

                    final MapListEntry mapListEntry = new MapListEntry(entryTitle, entrySummary);

                    mapListEntry.setKey("map_options");
                    mapListEntry.setValue(value);
                    mapListEntry.setOverlayType(overlayType);

                    mapListEntryList.add(mapListEntry);
                }

                final MapListSection mapListSection = new MapListSection(sectionTitle, mapListEntryList);
                mapListSectionList.add(mapListSection);
            }

            // ////////////////////////////////////////////////////
            // MAP / FILTER

            final JSONObject mapFiltersObject = mapSettingsObject.getJSONObject("mapFilters");

            final HashMap<String, List<MapListSection>> mapFilterListSectionListHash = new HashMap<String, List<MapListSection>>();

            //                Log.d(DEBUG_TAG, mapFilterArray.toString(4));

            for (final String typeKey : new String[] { "mobile", "wifi", "browser" }) {
                final JSONArray mapFilterArray = mapFiltersObject.getJSONArray(typeKey);
                final List<MapListSection> mapFilterListSectionList = new ArrayList<MapListSection>();
                mapFilterListSectionListHash.put(typeKey, mapFilterListSectionList);

                // add map appearance option (satellite, no satellite)
                final MapListSection appearanceSection = new MapListSection(
                        activity.getString(R.string.map_appearance_header),
                        Arrays.asList(
                                new MapListEntry(activity.getString(R.string.map_appearance_nosat_title),
                                        activity.getString(R.string.map_appearance_nosat_summary), true,
                                        MapProperties.MAP_SAT_KEY, MapProperties.MAP_NOSAT_VALUE, true),
                                new MapListEntry(activity.getString(R.string.map_appearance_sat_title),
                                        activity.getString(R.string.map_appearance_sat_summary),
                                        MapProperties.MAP_SAT_KEY, MapProperties.MAP_SAT_VALUE)));

                mapFilterListSectionList.add(appearanceSection);

                // add overlay option (heatmap, points)
                final MapListSection overlaySection = new MapListSection(
                        activity.getString(R.string.map_overlay_header),
                        Arrays.asList(
                                new MapListEntry(
                                        activity.getString(R.string.map_overlay_auto_title),
                                        activity.getString(R.string.map_overlay_auto_summary), true,
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.AUTO.name(), true),
                                new MapListEntry(activity.getString(R.string.map_overlay_heatmap_title),
                                        activity.getString(R.string.map_overlay_heatmap_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.HEATMAP.name()),
                                new MapListEntry(activity.getString(R.string.map_overlay_points_title),
                                        activity.getString(R.string.map_overlay_points_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.POINTS.name()),
                                new MapListEntry(activity.getString(R.string.map_overlay_regions_title),
                                        activity.getString(R.string.map_overlay_regions_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.REGIONS.name()),
                                new MapListEntry(activity.getString(R.string.map_overlay_municipality_title),
                                        activity.getString(R.string.map_overlay_municipality_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.MUNICIPALITY.name()),
                                new MapListEntry(activity.getString(R.string.map_overlay_settlements_title),
                                        activity.getString(R.string.map_overlay_settlements_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.SETTLEMENTS.name()),
                                new MapListEntry(activity.getString(R.string.map_overlay_whitespots_title),
                                        activity.getString(R.string.map_overlay_whitespots_summary),
                                        MapProperties.MAP_OVERLAY_KEY, MapOverlay.WHITESPOTS.name())));

                mapFilterListSectionList.add(overlaySection);

                // add other filter options

                for (int cnt = 0; cnt < mapFilterArray.length(); cnt++) {

                    final JSONObject t = mapFilterArray.getJSONObject(cnt);

                    final String sectionTitle = t.getString("title");

                    final JSONArray objectOptionsArray = t.getJSONArray("options");

                    // /

                    final List<MapListEntry> mapListEntryList = new ArrayList<MapListEntry>();

                    boolean haveDefault = false;

                    for (int cnt2 = 0; cnt2 < objectOptionsArray.length(); cnt2++) {

                        final JSONObject s = objectOptionsArray.getJSONObject(cnt2);

                        final String entryTitle = s.getString("title");
                        final String entrySummary = s.getString("summary");
                        final boolean entryDefault = s.optBoolean("default", false);

                        s.remove("title");
                        s.remove("summary");
                        s.remove("default");

                        //

                        final MapListEntry mapListEntry = new MapListEntry(entryTitle, entrySummary);

                        //

                        final JSONArray sArray = s.names();

                        if (sArray != null && sArray.length() > 0) {

                            final String key = sArray.getString(0);

                            mapListEntry.setKey(key);
                            mapListEntry.setValue(s.getString(key));
                        }

                        mapListEntry.setChecked(entryDefault && !haveDefault);
                        mapListEntry.setDefault(entryDefault);
                        if (entryDefault)
                            haveDefault = true;

                        // /

                        mapListEntryList.add(mapListEntry);
                    }

                    if (!haveDefault && mapListEntryList.size() > 0) {
                        final MapListEntry first = mapListEntryList.get(0);
                        first.setChecked(true); // set first if we had no default
                        first.setDefault(true);
                    }

                    final MapListSection mapListSection = new MapListSection(sectionTitle, mapListEntryList);
                    mapFilterListSectionList.add(mapListSection);
                }
            }

            // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            // map type
            final MapListEntry entry = mapListSectionList.get(0).getMapListEntryList().get(0);

            activity.setCurrentMapType(entry);

            activity.setMapTypeListSectionList(mapListSectionList);
            activity.setMapFilterListSectionListMap(mapFilterListSectionListHash);

        } catch (final JSONException e) {
            e.printStackTrace();
        }

    } else
        Log.i(DEBUG_TAG, "LEERE LISTE");

    if (endTaskListener != null) {
        final JSONArray array = new JSONArray();
        array.put(result);
        endTaskListener.taskEnded(array);
    }
}

From source file:com.apecat.shoppingadvisor.scan.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//from   w  w  w  . j  av a  2 s  .  c o m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e);
    }

    Collection<String> newTexts = new ArrayList<String>();
    maybeAddText(title, newTexts);
    maybeAddTextSeries(authors, newTexts);
    maybeAddText(pages == null || pages.isEmpty() ? null : pages + "pp.", newTexts);

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}

From source file:com.chess.genesis.net.GenesisNotifier.java

private void NewMove(final JSONObject json) {
    try {/*from  w w w  . j av a  2 s.  c  o m*/
        final JSONArray ids = json.getJSONArray("gameids");

        for (int i = 0, len = ids.length(); i < len; i++) {
            if (error)
                return;
            net.game_status(ids.getString(i));
            net.run();

            lock++;
        }
        // Save sync time
        final PrefEdit pref = new PrefEdit(this);
        pref.putLong(R.array.pf_lastgamesync, json.getLong("time"));
        pref.commit();
    } catch (final JSONException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.wso2.carbon.connector.integration.test.livechat.LivechatConnectorIntegrationTest.java

/**
 * Negative test case for createTicket method .
 *//*  w  w  w  .ja  v  a 2  s  .  co  m*/
@Test(groups = { "wso2.esb" }, description = "livechat {createTicket} integration test with negative case.")
public void testCreateTicketWithNegativeCase() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:createTicket");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_createTicket_negative.json");

    JSONArray esbErrorsArray = esbRestResponse.getBody().getJSONArray("error");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/tickets";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "POST", apiRequestHeadersMap,
            "api_createTicket_negative.json");

    JSONArray apiErrorsArray = apiRestResponse.getBody().getJSONArray("error");

    Assert.assertEquals(apiRestResponse.getHttpStatusCode(), esbRestResponse.getHttpStatusCode());
    Assert.assertEquals(apiErrorsArray.getString(0), esbErrorsArray.getString(0));
}

From source file:org.wso2.carbon.connector.integration.test.livechat.LivechatConnectorIntegrationTest.java

/**
 * Negative test case for listTickets method .
 *///ww  w.  java 2s  .com
@Test(groups = { "wso2.esb" }, description = "livechat {listTickets} integration test with negative case.")
public void testListTicketsWithNegativeCase() throws IOException, JSONException {

    esbRequestHeadersMap.put("Action", "urn:listTickets");
    RestResponse<JSONObject> esbRestResponse = sendJsonRestRequest(proxyUrl, "POST", esbRequestHeadersMap,
            "esb_listTickets_negative.json");

    JSONArray esbErrorsArray = esbRestResponse.getBody().getJSONArray("errors");

    String apiEndPoint = connectorProperties.getProperty("apiUrl") + "/tickets?order=INVALID";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndPoint, "GET", apiRequestHeadersMap);

    JSONArray apiErrorsArray = apiRestResponse.getBody().getJSONArray("errors");

    Assert.assertEquals(apiRestResponse.getHttpStatusCode(), esbRestResponse.getHttpStatusCode());
    Assert.assertEquals(apiErrorsArray.getString(0), esbErrorsArray.getString(0));
}

From source file:com.facebook.config.ConfigAccessor.java

public List<String> getStringList(String key) throws ConfigException {
    JSONArray items;
    List<String> result = new ArrayList<>();

    try {/*from  ww w .j a  v a  2  s  . c  om*/
        items = jsonObject.getJSONArray(key);

        for (int i = 0; i < items.length(); i++) {
            result.add(items.getString(i));
        }
    } catch (JSONException e) {
        throw new ConfigException("unable to parse string list for key " + key, e);
    }

    return result;
}

From source file:au.id.tmm.anewreader.model.Model.java

/**
 * Constructs an Item object from a JSON object retrieved from the api.
 *///  w w  w  .j av a 2s.  c  o m
private Item getItemFromJson(JSONObject itemJsonObject, ReadStatus readStatus, Account parentAccount)
        throws JSONException, IOException {
    Pattern idPattern = Pattern.compile("^tag:google\\.com,2005:reader/item/(.*)$");
    Matcher matcher = idPattern.matcher(itemJsonObject.getString("id"));
    String id;
    if (matcher.find()) {
        id = matcher.group(1);
    } else {
        throw new ApiParseException();
    }

    String title = itemJsonObject.getString("title");
    String canonicalLink = itemJsonObject.getJSONArray("canonical").getJSONObject(0).getString("href");
    String alternateLink = itemJsonObject.getJSONArray("alternate").getJSONObject(0).getString("href");

    Date publishedTimestamp = new Date(Long.parseLong(itemJsonObject.getString("published")));
    Date updatedTimestamp = new Date(Long.parseLong(itemJsonObject.getString("updated")));
    Date crawlTimestamp = new Date(Long.parseLong(itemJsonObject.getString("crawlTimeMsec")));

    String summary = itemJsonObject.getJSONObject("summary").getString("content");
    String author = itemJsonObject.getString("author");

    Set<Category> categories = new TreeSet<Category>();

    JSONArray categoriesArray = itemJsonObject.getJSONArray("categories");

    for (int i = 0; i < categoriesArray.length(); i++) {
        if (categoriesArray.getString(i).matches("\\^user/-/label/(.*)$")) {

            String currentId = categoriesArray.getString(i);

            if (this.categories.containsKey(currentId)) {
                categories.add(this.categories.get(currentId));
            } else {
                // The category associated with the item is not in our categories array. This
                // problem should be fixed when this class is refactored as mentioned above.
                // For the moment, we simply throw a RuntimeException.
                throw new RuntimeException();
            }
        }
    }

    JSONObject originJsonObject = itemJsonObject.getJSONObject("origin");

    Subscription parentSubscription;
    String streamId = this.extractSubscriptionId(originJsonObject.getString("streamId"));
    if (this.subscriptions.containsKey(streamId)) {
        parentSubscription = this.subscriptions.get(streamId);
    } else {
        this.getSubscriptions();
        if (this.subscriptions.containsKey(streamId)) {
            parentSubscription = this.subscriptions.get(streamId);
        } else {
            // The subscription associated with the item is not in our subscriptions array. This
            // problem should be fixed when this class is refactored as mentioned above.
            // For the moment, we simply throw a RuntimeException.
            throw new RuntimeException();
        }

    }

    return new Item(id, title, canonicalLink, alternateLink, publishedTimestamp, updatedTimestamp,
            crawlTimestamp, summary, author, categories, parentSubscription, readStatus);
}

From source file:com.miz.apis.trakt.Movie.java

public Movie(JSONObject summaryJson) {
    try {//from   w ww  . ja  v a 2 s  . co  m
        mTitle = summaryJson.getString("title");
        mYear = summaryJson.getInt("year");
        mReleased = summaryJson.getLong("released");
        mUrl = summaryJson.getString("url");
        mOverview = summaryJson.getString("overview");
        mTagline = summaryJson.getString("tagline");
        mRuntime = summaryJson.getInt("runtime");
        mCertification = summaryJson.getString("certification");
        mTmdbId = summaryJson.getInt("tmdb_id");
        mImdbId = summaryJson.getString("imdb_id");
        mPoster = summaryJson.getString("poster");
        mFanart = summaryJson.getJSONObject("images").getString("fanart");
        mRating = summaryJson.getJSONObject("ratings").getInt("percentage");

        JSONArray genres = summaryJson.getJSONArray("genres");
        for (int i = 0; i < genres.length(); i++)
            mGenres.add(genres.getString(i));

    } catch (JSONException e) {
    }
}

From source file:fr.bmartel.android.fadecandy.model.FadecandyConfig.java

public FadecandyConfig(JSONObject config) {

    try {/*  ww w .j a v a 2  s.  c  om*/

        if (config.has(Constants.CONFIG_LISTEN) && config.has(Constants.CONFIG_VERBOSE)
                && config.has(Constants.CONFIG_COLOR) && config.has(Constants.CONFIG_DEVICES)) {

            JSONArray listen = config.getJSONArray(Constants.CONFIG_LISTEN);

            if (listen.length() > 1) {
                mHost = listen.getString(0);
                mPort = listen.getInt(1);
            }

            mVerbose = config.getBoolean(Constants.CONFIG_VERBOSE);

            mFcColor = new FadecandyColor(config.getJSONObject(Constants.CONFIG_COLOR));

            JSONArray fcDeviceArr = config.getJSONArray(Constants.CONFIG_DEVICES);

            for (int i = 0; i < fcDeviceArr.length(); i++) {
                mFcDevices.add(new FadecandyDevice((JSONObject) fcDeviceArr.get(i)));
            }
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

}

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

/**
 * Merge those keys not found in this object from specified object.
 *
 * @param obj The other object to be merged.
 *///w  ww. j ava  2s  . c  o m
void mergeData(JsoMap obj) {
    if (obj == null) {
        return;
    }

    JSONArray names = obj.names();
    if (names == null) {
        return;
    }

    for (int i = 0; i < names.length(); i++) {
        try {
            String name = names.getString(i);
            try {
                if (!super.has(name)) {
                    super.put(name, obj.getObject(name));
                }
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
        } catch (JSONException e) {
            // Ignored.
        }
    }
}