Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.everit.json.schema.IntegrationTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }//from  ww  w . j a  v  a  2 s.  co m
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(IntegrationTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:com.phonegap.App.java

/**
 * Load the url into the webview./*from  ww w .j  av a 2 s  .c  o  m*/
 * 
 * @param url
 * @param props         Properties that can be passed in to the DroidGap activity (i.e. loadingDialog, wait, ...)
 * @throws JSONException 
 */
public void loadUrl(String url, JSONObject props) throws JSONException {
    System.out.println("App.loadUrl(" + url + "," + props + ")");
    int wait = 0;

    // If there are properties, then set them on the Activity
    if (props != null) {
        JSONArray keys = props.names();
        for (int i = 0; i < keys.length(); i++) {
            String key = keys.getString(i);
            if (key.equals("wait")) {
                wait = props.getInt(key);
            } else {
                Object value = props.get(key);
                if (value == null) {

                } else if (value.getClass().equals(String.class)) {
                    this.ctx.getIntent().putExtra(key, (String) value);
                } else if (value.getClass().equals(Boolean.class)) {
                    this.ctx.getIntent().putExtra(key, (Boolean) value);
                } else if (value.getClass().equals(Integer.class)) {
                    this.ctx.getIntent().putExtra(key, (Integer) value);
                }
            }
        }
    }

    // If wait property, then delay loading
    if (wait > 0) {
        ((DroidGap) this.ctx).loadUrl(url, wait);
    } else {
        ((DroidGap) this.ctx).loadUrl(url);
    }
}

From source file:com.dzt.uberclone.HomeFragment.java

private void showUberMarkers(String json) {
    try {//from  w  w  w .j av  a 2s .  c o m
        markers.clear();
        shortestTime = 0;
        JSONArray jsonArray = new JSONArray(json);
        nearbyUbers = jsonArray.length();
        ubercount = 0;
        if (nearbyUbers == 0) {
            displayNoUbersMessage();
        }
        for (int i = 0; i < nearbyUbers; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            double lat = jsonObject.getDouble("pos_lat");
            double lon = jsonObject.getDouble("pos_long");
            addUberMarker(lat, lon);
            getShortestTime(lat, lon);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.matrix.console.store.LoginStorage.java

/**
 * Return a list of HomeserverConnectionConfig.
 * @return a list of HomeserverConnectionConfig.
 *//*from   w  w w  . ja  v a2s  . com*/
public ArrayList<HomeserverConnectionConfig> getCredentialsList() {
    SharedPreferences prefs = mContext.getSharedPreferences(PREFS_LOGIN, Context.MODE_PRIVATE);

    String connectionConfigsString = prefs.getString(PREFS_KEY_CONNECTION_CONFIGS, null);

    Log.d(LOG_TAG, "Got connection json: " + connectionConfigsString);

    if (connectionConfigsString == null) {
        return new ArrayList<HomeserverConnectionConfig>();
    }

    try {

        JSONArray connectionConfigsStrings = new JSONArray(connectionConfigsString);

        ArrayList<HomeserverConnectionConfig> configList = new ArrayList<HomeserverConnectionConfig>(
                connectionConfigsStrings.length());

        for (int i = 0; i < connectionConfigsStrings.length(); i++) {
            configList.add(HomeserverConnectionConfig.fromJson(connectionConfigsStrings.getJSONObject(i)));
        }

        return configList;
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Failed to deserialize accounts " + e.getMessage(), e);
        throw new RuntimeException("Failed to deserialize accounts");
    }
}

From source file:com.krayzk9s.imgurholo.ui.CommentsFragment.java

private void addComments(JSONObject comments) {
    try {/*  w  ww.j  av  a 2  s  .  c om*/
        commentDataArray = new ArrayList<JSONParcelable>();
        JSONArray data = comments.getJSONArray("data");
        for (int i = 0; i < data.length(); i++) {
            JSONObject message = data.getJSONObject(i);
            JSONParcelable dataParcel = new JSONParcelable();
            dataParcel.setJSONObject(message);
            commentDataArray.add(dataParcel);
        }
        commentsAdapter.addAll(commentDataArray);
    } catch (JSONException e) {
        errorText.setVisibility(View.VISIBLE);
        errorText.setText("Error getting comments");
        Log.e("Error!", "adding messages" + e.toString());
    }
    mDrawerList.setAdapter(commentsAdapter);
    commentsAdapter.notifyDataSetChanged();
}

From source file:com.amazon.android.contentbrowser.helper.AuthHelper.java

/**
 * Retrieves the list of possible MVPD providers from the URL found at R.string.mvpd_url in
 * custom.xml and gives them to ContentBrowser.
 *//*from   ww  w. j  a  v  a  2s . com*/
public void setupMvpdList() {

    try {

        String mvpdUrl = mAppContext.getResources().getString(R.string.mvpd_url);

        // The user has no MVPD URL set up.
        if (mvpdUrl.equals(DEFAULT_MVPD_URL)) {
            Log.d(TAG, "MVPD feature not used.");
            return;
        }
        String jsonStr = NetworkUtils.getDataLocatedAtUrl(mvpdUrl);

        JSONObject json = new JSONObject(jsonStr);
        JSONArray mvpdWhiteList = json.getJSONArray(MVPD_WHITE_LIST);

        for (int i = 0; i < mvpdWhiteList.length(); i++) {

            JSONObject mvpdItem = mvpdWhiteList.getJSONObject(i);
            mContentBrowser.addPoweredByLogoUrlByName(mvpdItem.getString(PreferencesConstants.MVPD_LOGO_URL),
                    mvpdItem.getString(LOGGED_IN_IMAGE));
        }

    } catch (Exception e) {
        Log.e(TAG, "Get MVPD logo urls failed!!!", e);

    }
}

From source file:org.wso2.carbon.connector.integration.test.googleanalytics.GoogleanalyticsConnectorIntegrationTest.java

/**
 * Positive test case for createAccountUserLink method with mandatory parameters.
 *
 * @throws org.json.JSONException// w w w.  ja  va2 s.  co  m
 * @throws java.io.IOException
 */
@Test(groups = {
        "wso2.esb" }, description = "googleanalytics {createAccountUserLink} integration test with mandatory parameters.", dependsOnMethods = {
                "testListAccountSummariesWithMandatoryParameters" })
public void testCreateAccountUserLinkWithMandatoryParameters() throws IOException, JSONException {

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

    final JSONObject esbResponse = esbRestResponse.getBody();

    final String userLinkId = esbResponse.getString("id");
    connectorProperties.put("userLinkId", userLinkId);

    final String apiEndpoint = apiEndpointUrl + "/management/accounts/"
            + connectorProperties.getProperty("accountId") + "/entityUserLinks";
    RestResponse<JSONObject> apiRestResponse = sendJsonRestRequest(apiEndpoint, "GET", apiRequestHeadersMap);

    final JSONArray itemArray = apiRestResponse.getBody().getJSONArray("items");

    String id;
    String email = "";
    String permissions = "";
    String selfLink = "";
    for (int i = 0; i < itemArray.length(); i++) {
        id = itemArray.getJSONObject(i).getString("id");
        if (id.equals(userLinkId)) {
            permissions = itemArray.getJSONObject(i).getJSONObject("permissions").toString();
            email = itemArray.getJSONObject(i).getJSONObject("userRef").getString("email");
            selfLink = itemArray.getJSONObject(i).getString("selfLink");
            break;
        }
    }

    Assert.assertEquals(connectorProperties.getProperty("userLinkEmail"), email);
    Assert.assertEquals(esbResponse.getJSONObject("permissions").toString(), permissions);
    Assert.assertEquals(esbResponse.getString("selfLink"), selfLink);
}

From source file:org.wso2.carbon.connector.integration.test.googleanalytics.GoogleanalyticsConnectorIntegrationTest.java

/**
 * Positive test case for updateAccountUserLink method with mandatory parameters.
 *
 * @throws org.json.JSONException/*  w w  w.  j av  a 2  s.  c o m*/
 * @throws java.io.IOException
 */
@Test(groups = {
        "wso2.esb" }, description = "googleanalytics {updateAccountUserLink} integration test with mandatory parameters.", dependsOnMethods = {
                "testCreateAccountUserLinkWithMandatoryParameters",
                "testListAccountSummariesWithMandatoryParameters" })
public void testUpdateAccountUserLinkWithMandatoryParameters() throws IOException, JSONException {

    final String apiEndpoint = apiEndpointUrl + "/management/accounts/"
            + connectorProperties.getProperty("accountId") + "/entityUserLinks";
    RestResponse<JSONObject> apiRestResponseBefore = sendJsonRestRequest(apiEndpoint, "GET",
            apiRequestHeadersMap);
    final String userLinkId = connectorProperties.getProperty("userLinkId");
    final JSONArray itemArrayBefore = apiRestResponseBefore.getBody().getJSONArray("items");

    String id;
    String permissions = "";
    for (int i = 0; i < itemArrayBefore.length(); i++) {
        id = itemArrayBefore.getJSONObject(i).getString("id");
        if (id.equals(userLinkId)) {
            permissions = itemArrayBefore.getJSONObject(i).getJSONObject("permissions").toString();
            break;
        }
    }

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

    final JSONObject esbResponse = esbRestResponse.getBody();

    RestResponse<JSONObject> apiRestResponseAfter = sendJsonRestRequest(apiEndpoint, "GET",
            apiRequestHeadersMap);

    final JSONArray itemArrayAfter = apiRestResponseAfter.getBody().getJSONArray("items");

    String idAfter;
    String permissionsAfter = "";
    for (int i = 0; i < itemArrayAfter.length(); i++) {
        idAfter = itemArrayAfter.getJSONObject(i).getString("id");
        if (idAfter.equals(userLinkId)) {
            permissionsAfter = itemArrayAfter.getJSONObject(i).getJSONObject("permissions").toString();
            break;
        }
    }

    Assert.assertNotEquals(permissions, permissionsAfter);
    Assert.assertEquals(esbResponse.getJSONObject("permissions").toString(), permissionsAfter);
}

From source file:com.streaming.sweetplayer.fragment.TopFragment.java

private void getTopList() {
    JSONParser jsonParser = new JSONParser();
    JSONArray jsonArray;

    try {//from w  w  w . j a  va  2 s  .co  m
        JSONObject json = jsonParser.getJSONFromUrl(Config.TOP_URL);
        if (json != null) {
            jsonArray = json.getJSONArray(Config.SONGS_ITEM);
            int array_length = jsonArray.length();
            if (array_length > 0) {
                for (int i = 0; i < array_length; i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    map.put(Config.ID, jsonObject.getString(Config.ID));
                    map.put(Config.ARTIST, jsonObject.getString(Config.ARTIST));
                    map.put(Config.NAME, jsonObject.getString(Config.SONG));
                    map.put(Config.MP3, jsonObject.getString(Config.MP3));
                    map.put(Config.DURATION, jsonObject.getString(Config.DURATION));
                    map.put(Config.URL, jsonObject.getString(Config.URL));
                    map.put(Config.IMAGE, jsonObject.getString(Config.IMAGE));
                    mTopList.add(map);
                }
            } else {
                // Showing a message should be done in the UI thread.
                mActivity.runOnUiThread(new Runnable() {
                    public void run() {
                        Utils.showUserMessage(mActivity.getApplicationContext(),
                                mActivity.getString(R.string.search_empty));
                    }
                });
            }
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:org.indigo.cdmi.backend.radosgw.JsonResponseTranlator.java

/**
 * Maps names of profiles from prifilesNames JSON array to comma separated sequence of 
 * associated URIs./*from w w  w  . j  a  v  a2s.c  om*/
 * @param profilesNames JSON array of profiles' names
 */
private String profilesToUris(JSONArray profilesNames, String cdmiObjectType) {

    StringBuffer rv = new StringBuffer();

    log.debug("In profilesToURIs(): {}", profilesNames);

    for (int index = 0; index < profilesNames.length(); index++) {

        String profileName = profilesNames.getString(index);
        log.debug("Processed profile name: {}", profileName);
        String capabilityUri = profileToUri(profileName, cdmiObjectType);
        if (index > 0) {
            rv.append(", ");
        }
        rv.append(capabilityUri);

    } // for()

    return rv.toString();

}