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:com.tinyhydra.botd.GoogleOperations.java

public static List<JavaShop> GetShops(Handler handler, Location currentLocation, String placesApiKey) {
    // Use google places to get all the shops within '500' (I believe meters is the default measurement they use)
    // make a list of JavaShops and pass it to the ListView adapter
    List<JavaShop> shopList = new ArrayList<JavaShop>();
    try {/*from w  ww .  j av a  2  s.  c o m*/
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        int accuracy = Math.round(currentLocation.getAccuracy());
        if (accuracy < 500)
            accuracy = 500;
        request.setURI(URI.create("https://maps.googleapis.com/maps/api/place/search/json?location="
                + currentLocation.getLatitude() + "," + currentLocation.getLongitude() + "&radius=" + accuracy
                + "&types=" + URLEncoder.encode("cafe|restaurant|food", "UTF-8")
                + "&keyword=coffee&sensor=true&key=" + placesApiKey));
        HttpResponse response = client.execute(request);
        BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }

        JSONObject predictions = new JSONObject(sb.toString());
        // Google passes back a status string. if we screw up, it won't say "OK". Alert the user.
        String jstatus = predictions.getString("status");
        if (jstatus.equals("ZERO_RESULTS")) {
            Utils.PostToastMessageToHandler(handler, "No shops found in your area.", Toast.LENGTH_SHORT);
            return shopList;
        } else if (!jstatus.equals("OK")) {
            Utils.PostToastMessageToHandler(handler, "Error retrieving local shops.", Toast.LENGTH_SHORT);
            return shopList;
        }

        // This section may fail if there's no results, but we'll just display an empty list.
        //TODO: alert the user and cancel the dialog if this fails
        JSONArray ja = new JSONArray(predictions.getString("results"));

        for (int i = 0; i < ja.length(); i++) {
            JSONObject jo = (JSONObject) ja.get(i);
            shopList.add(new JavaShop(jo.getString("name"), jo.getString("id"), "", jo.getString("reference"),
                    jo.getString("vicinity")));
        }
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return shopList;
}

From source file:com.hackathon.gavin.string.parser.MyAccountParser.java

public static ArrayList convertToArrayList(JSONArray orginalData) {
    ArrayList<String> allElements = new ArrayList<String>();
    for (int i = 0; i < orginalData.length(); i++) {
        try {//from w ww. ja  v  a  2  s. c  o m
            JSONObject obj = orginalData.getJSONObject(i);
            allElements.add(Integer.toString(obj.getInt("id")));
            allElements.add(Integer.toString(obj.getInt("units")));
            allElements.add(obj.getString("instrument"));
            allElements.add(String.valueOf(obj.getDouble("price")));
            System.out.println(allElements);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return allElements;
}

From source file:org.openhab.habdroid.model.OpenHABWidget.java

public OpenHABWidget(OpenHABWidget parent, JSONObject widgetJson) {
    this.parent = parent;
    this.children = new ArrayList<OpenHABWidget>();
    this.mappings = new ArrayList<OpenHABWidgetMapping>();
    try {//from  w ww .j a v  a2 s  .  co m
        if (widgetJson.has("item")) {
            this.setItem(new OpenHABItem(widgetJson.getJSONObject("item")));
        }
        if (widgetJson.has("linkedPage")) {
            this.setLinkedPage(new OpenHABLinkedPage(widgetJson.getJSONObject("linkedPage")));
        }
        if (widgetJson.has("mappings")) {
            JSONArray mappingsJsonArray = widgetJson.getJSONArray("mappings");
            for (int i = 0; i < mappingsJsonArray.length(); i++) {
                JSONObject mappingObject = mappingsJsonArray.getJSONObject(i);
                OpenHABWidgetMapping mapping = new OpenHABWidgetMapping(mappingObject.getString("command"),
                        mappingObject.getString("label"));
                mappings.add(mapping);
            }
        }
        if (widgetJson.has("type"))
            this.setType(widgetJson.getString("type"));
        if (widgetJson.has("widgetId"))
            this.setId(widgetJson.getString("widgetId"));
        if (widgetJson.has("label"))
            this.setLabel(widgetJson.getString("label"));
        if (widgetJson.has("icon"))
            this.setIcon(widgetJson.getString("icon"));
        if (widgetJson.has("url"))
            this.setUrl(widgetJson.getString("url"));
        if (widgetJson.has("minValue"))
            this.setMinValue((float) widgetJson.getDouble("minValue"));
        if (widgetJson.has("maxValue"))
            this.setMaxValue((float) widgetJson.getDouble("maxValue"));
        if (widgetJson.has("step"))
            this.setStep((float) widgetJson.getDouble("step"));
        if (widgetJson.has("refresh"))
            this.setRefresh(widgetJson.getInt("refresh"));
        if (widgetJson.has("period"))
            this.setPeriod(widgetJson.getString("period"));
        if (widgetJson.has("service"))
            this.setService(widgetJson.getString("service"));
        if (widgetJson.has("height"))
            this.setHeight(widgetJson.getInt("height"));
        if (widgetJson.has("iconcolor"))
            this.setIconColor(widgetJson.getString("iconcolor"));
        if (widgetJson.has("labelcolor"))
            this.setLabelColor(widgetJson.getString("labelcolor"));
        if (widgetJson.has("valuecolor"))
            this.setValueColor(widgetJson.getString("valuecolor"));
        if (widgetJson.has("encoding"))
            this.setEncoding(widgetJson.getString("encoding"));
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (widgetJson.has("widgets")) {
        try {
            JSONArray childWidgetJsonArray = widgetJson.getJSONArray("widgets");
            for (int i = 0; i < childWidgetJsonArray.length(); i++) {
                new OpenHABWidget(this, childWidgetJsonArray.getJSONObject(i));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    this.parent.addChildWidget(this);
}

From source file:com.appjma.appdeployer.service.Parser.java

public void parseApps(JSONObject json) throws JSONException {
    JSONArray items = JSONHelper.getJSONArrayOrEmtpy(json, "items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        parseApp(null, item);/*from  w  ww  .java  2 s  . c  o m*/
    }
    String nextToken = JSONHelper.getStrinOrNull(json, "next_token");
    mParserResult.setAppsNextToken(nextToken);
}

From source file:com.appjma.appdeployer.service.Parser.java

public void parseAppVersions(String appId, JSONObject json) throws JSONException {
    JSONArray items = JSONHelper.getJSONArrayOrEmtpy(json, "items");
    for (int i = 0; i < items.length(); i++) {
        JSONObject item = items.getJSONObject(i);
        parseAppVersion(appId, item);//from ww w . j a va 2s.c om
    }
}

From source file:de.jaetzold.philips.hue.HueBridgeComm.java

List<JSONObject> request(RM method, String fullPath, String json) throws IOException {
    final URL url = new URL(baseUrl, fullPath);
    log.fine("Request to " + method + " " + url + (json != null && json.length() > 0 ? ": " + json : ""));
    final URLConnection connection = url.openConnection();
    if (connection instanceof HttpURLConnection) {
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        httpConnection.setRequestMethod(method.name());
        if (json != null && json.length() > 0) {
            if (method == RM.GET || method == RM.DELETE) {
                throw new HueCommException("Will not send json content for request method " + method);
            }//ww w  . ja  v a  2 s  . co  m
            httpConnection.setDoOutput(true);
            httpConnection.getOutputStream().write(json.getBytes(REQUEST_CHARSET));
        }
    } else {
        throw new IllegalStateException("The current baseUrl \"" + baseUrl + "\" is not http?");
    }

    final BufferedReader reader = new BufferedReader(
            new InputStreamReader(connection.getInputStream(), REQUEST_CHARSET));
    StringBuilder builder = new StringBuilder();
    String line;
    while ((line = reader.readLine()) != null) {
        builder.append(line).append('\n');
    }
    log.fine("Response from " + method + " " + url + ": " + builder);
    final String jsonString = builder.toString();
    List<JSONObject> result = new ArrayList<>();
    if (jsonString.trim().startsWith("{")) {
        result.add(new JSONObject(jsonString));
    } else {
        final JSONArray array = new JSONArray(jsonString);
        for (int i = 0; i < array.length(); i++) {
            result.add(array.getJSONObject(i));
        }
    }
    return result;
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

private static void addHeadersToRequest(URLConnection connection, JSONObject headers) {
    try {/*from w  w w .java  2 s . c o  m*/
        for (Iterator<?> iter = headers.keys(); iter.hasNext();) {
            String headerKey = iter.next().toString();
            JSONArray headerValues = headers.optJSONArray(headerKey);
            if (headerValues == null) {
                headerValues = new JSONArray();
                headerValues.put(headers.getString(headerKey));
            }
            connection.setRequestProperty(headerKey, headerValues.getString(0));
            for (int i = 1; i < headerValues.length(); ++i) {
                connection.addRequestProperty(headerKey, headerValues.getString(i));
            }
        }
    } catch (JSONException e1) {
        // No headers to be manipulated!
    }
}

From source file:com.percolatestudio.cordova.fileupload.PSFileUpload.java

/**
 * Convenience method to read a parameter from the list of JSON args.
 * @param args                      the args passed to the Plugin
 * @param position          the position to retrieve the arg from
 * @param defaultString the default to be used if the arg does not exist
 * @return String with the retrieved value
 *//*from   w  ww  .j a v  a2 s .  com*/
private static String getArgument(JSONArray args, int position, String defaultString) {
    String arg = defaultString;
    if (args.length() > position) {
        arg = args.optString(position);
        if (arg == null || "null".equals(arg)) {
            arg = defaultString;
        }
    }
    return arg;
}

From source file:com.escapeir.server.Connect.java

@Override
protected Boolean doInBackground(Boolean... params) {
    HttpPost httppost = null;//from   www .j a v a2s .  c  om
    // setOrGet = true is set user
    // setOrGet = false is Get user
    setOrGet = params[0];
    String urlExecute = "", urlSet = "http://escapeir.uphero.com/setUser.php",
            urlGet = "http://escapeir.uphero.com/getUser.php";
    String result = "";
    InputStream is = null;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        if (setOrGet) {
            httppost = new HttpPost(urlSet);

            final ArrayList<NameValuePair> insertUser = new ArrayList<NameValuePair>();
            insertUser.add(new BasicNameValuePair("user", EscapeIRApplication.USER_NAME));
            insertUser.add(new BasicNameValuePair("time", EscapeIRApplication.USER_TIME));
            httppost.setEntity(new UrlEncodedFormEntity(insertUser));

        } else {
            httppost = new HttpPost(urlGet);

        }
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        Log.i("Connect", "Connect");
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error in http connection " + e.toString());
    }
    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result = sb.toString();

        Log.i(EscapeIRApplication.TAG, "resultado");
        Log.i(EscapeIRApplication.TAG, result);
    } catch (Exception e) {
        Log.e(EscapeIRApplication.TAG, "Error converting result " + e.toString());
    }
    // parse json data
    if (setOrGet) {
        // return if is set user
        return true;
    } else {
        try {
            JSONArray jArray = new JSONArray(result);
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject json_data = jArray.getJSONObject(i);
                EscapeIRApplication.usersServer
                        .add(new User(json_data.getString("user"), json_data.getString("time")));
                Log.i(EscapeIRApplication.TAG,
                        "time: " + json_data.getString("time") + ", name: " + json_data.getString("user"));
            }
        } catch (JSONException e) {
            Log.e(EscapeIRApplication.TAG, "Error parsing data " + e.toString());
        }
    }
    return true;
}

From source file:com.neuron.trafikanten.dataProviders.trafikanten.TrafikantenRealtime.java

@Override
public void run() {
    try {//from  ww  w.  j a va 2  s  .c o m
        final String urlString = Trafikanten.getApiUrl() + "/reisrest/realtime/GetAllDepartures/" + stationId;
        Log.i(TAG, "Loading realtime data : " + urlString);

        final StreamWithTime streamWithTime = HelperFunctions.executeHttpRequest(context,
                new HttpGet(urlString), true);
        ThreadHandleTimeData(streamWithTime.timeDifference);

        /*
         * Parse json
         */
        //long perfSTART = System.currentTimeMillis();
        //Log.i(TAG,"PERF : Getting realtime data");
        final JSONArray jsonArray = new JSONArray(HelperFunctions.InputStreamToString(streamWithTime.stream));
        final int arraySize = jsonArray.length();
        for (int i = 0; i < arraySize; i++) {
            final JSONObject json = jsonArray.getJSONObject(i);
            RealtimeData realtimeData = new RealtimeData();
            try {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedDepartureTime"));
            } catch (org.json.JSONException e) {
                realtimeData.expectedDeparture = HelperFunctions
                        .jsonToDate(json.getString("ExpectedArrivalTime"));
            }

            try {
                realtimeData.lineId = json.getInt("LineRef");
            } catch (org.json.JSONException e) {
                realtimeData.lineId = -1;
            }

            try {
                realtimeData.vehicleMode = json.getInt("VehicleMode");
            } catch (org.json.JSONException e) {
                realtimeData.vehicleMode = 0; // default = bus
            }

            try {
                realtimeData.destination = json.getString("DestinationName");
            } catch (org.json.JSONException e) {
                realtimeData.destination = "Ukjent";
            }

            try {
                realtimeData.departurePlatform = json.getString("DeparturePlatformName");
                if (realtimeData.departurePlatform.equals("null")) {
                    realtimeData.departurePlatform = "";
                }

            } catch (org.json.JSONException e) {
                realtimeData.departurePlatform = "";
            }

            try {
                realtimeData.realtime = json.getBoolean("Monitored");
            } catch (org.json.JSONException e) {
                realtimeData.realtime = false;
            }
            try {
                realtimeData.lineName = json.getString("PublishedLineName");
            } catch (org.json.JSONException e) {
                realtimeData.lineName = "";
            }

            try {
                if (json.has("InCongestion")) {
                    realtimeData.inCongestion = json.getBoolean("InCongestion");
                }
            } catch (org.json.JSONException e) {
                // can happen when incongestion is empty string.
            }

            try {
                if (json.has("VehicleFeatureRef")) {
                    realtimeData.lowFloor = json.getString("VehicleFeatureRef").equals("lowFloor");
                }
            } catch (org.json.JSONException e) {
                // lowfloor = false by default
            }

            try {
                if (json.has("TrainBlockPart") && !json.isNull("TrainBlockPart")) {
                    JSONObject trainBlockPart = json.getJSONObject("TrainBlockPart");
                    if (trainBlockPart.has("NumberOfBlockParts")) {
                        realtimeData.numberOfBlockParts = trainBlockPart.getInt("NumberOfBlockParts");
                    }
                }
            } catch (org.json.JSONException e) {
                // trainblockpart is initialized by default
            }

            ThreadHandlePostData(realtimeData);
        }

        //Log.i(TAG,"PERF : Parsing web request took " + ((System.currentTimeMillis() - perfSTART)) + "ms");

    } catch (Exception e) {
        if (e.getClass() == InterruptedException.class) {
            ThreadHandlePostExecute(null);
            return;
        }
        ThreadHandlePostExecute(e);
        return;
    }
    ThreadHandlePostExecute(null);
}