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.asd.littleprincesbeauty.data.Task.java

@Override
public void setContentByLocalJSON(JSONObject js) {
    if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) {
        Log.w(TAG, "setContentByLocalJSON: nothing is avaiable");
    }//from ww w  .ja v  a2s. co m

    try {
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

        if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) {
            Log.e(TAG, "invalid type");
            return;
        }

        for (int i = 0; i < dataArray.length(); i++) {
            JSONObject data = dataArray.getJSONObject(i);
            if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                setName(data.getString(DataColumns.CONTENT));
                break;
            }
        }

    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
}

From source file:com.asd.littleprincesbeauty.data.Task.java

@Override
public JSONObject getLocalJSONFromContent() {
    String name = getName();//from  ww  w  .  java2s . com
    try {
        if (mMetaInfo == null) {
            // new task created from web
            if (name == null) {
                Log.w(TAG, "the note seems to be an empty one");
                return null;
            }

            JSONObject js = new JSONObject();
            JSONObject note = new JSONObject();
            JSONArray dataArray = new JSONArray();
            JSONObject data = new JSONObject();
            data.put(DataColumns.CONTENT, name);
            dataArray.put(data);
            js.put(GTaskStringUtils.META_HEAD_DATA, dataArray);
            note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
            js.put(GTaskStringUtils.META_HEAD_NOTE, note);
            return js;
        } else {
            // synced task
            JSONObject note = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
            JSONArray dataArray = mMetaInfo.getJSONArray(GTaskStringUtils.META_HEAD_DATA);

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) {
                    data.put(DataColumns.CONTENT, getName());
                    break;
                }
            }

            note.put(NoteColumns.TYPE, Notes.TYPE_NOTE);
            return mMetaInfo;
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return null;
    }
}

From source file:com.autburst.picture.server.PictureServer.java

public String[] getImageList(String id) throws Exception {
    HttpRequest request = new HttpRequest();
    String url = BASE_URL + "/" + id;

    Log.d(TAG, "getImageList - url: " + url);

    String response = request.get(url);

    if (response != null && !response.equals("null")) {
        //parse JSON
        JSONObject json = new JSONObject(response);

        JSONArray jsonArray = null;
        String singleFileName = null;
        try {//from ww w  . j  a va2 s .c  o m
            jsonArray = json.getJSONArray("files");
        } catch (JSONException e) {
            Log.e(TAG, "No JSONArray returned!");

            //get single filename
            singleFileName = json.getString("files");
        }

        if (jsonArray == null) {
            singleFileName = json.getString("files");
            Log.d(TAG, "getImageList - Server returned one file " + singleFileName);
            return new String[] { singleFileName };
        } else {
            String[] resultList = new String[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                resultList[i] = jsonArray.getString(i);
                Log.d(TAG, "getImageList - Server returned " + resultList[i]);
            }
            return resultList;
        }
    } else {
        Log.d(TAG, "getImageList - Server returned null images");
        return new String[0];
    }
}

From source file:com.iespuig.attendancemanager.StudentFetchr.java

public ArrayList<Student> fetchStudent(Classblock classBlock) {
    ArrayList<Student> items = new ArrayList<Student>();

    SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context);
    String schoolName = SP.getString(("schoolName"), "");
    String urlServer = SP.getString("urlServer", "");

    Format formatter = new SimpleDateFormat("ddMMyyyy");

    try {/*w w w  .  j a v  a2  s.co m*/
        String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_GET_STUDENTS)
                .appendQueryParameter("school", schoolName)
                .appendQueryParameter("login", User.getInstance().getLogin())
                .appendQueryParameter("password", User.getInstance().getPassword())
                .appendQueryParameter("idGroup", String.valueOf(classBlock.getIdGroup()))
                .appendQueryParameter("idClassBlock", String.valueOf(classBlock.getId()))
                .appendQueryParameter("date", formatter.format(classBlock.getDate())).build().toString();

        Log.i(TAG, "url: " + url);

        String data = AtmNet.getUrl(url);
        Log.i(TAG, "url: " + data);

        JSONObject jsonObject = new JSONObject(data);
        JSONArray jsonArray = new JSONArray(jsonObject.getString("data"));

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject row = jsonArray.getJSONObject(i);

            Student item = new Student();

            item.setId(row.getInt("id"));
            item.setFullname(row.getString("fullname"));
            item.setName(row.getString("name"));
            item.setSurname1(row.getString("surname1"));
            item.setSurname2(row.getString("surname2"));
            item.setMissType(0);
            item.setNotMaterial(false);
            item.setNetworkTransit(false);

            if (row.has("misses")) {
                JSONArray misses = row.getJSONArray("misses");
                for (int j = 0; j < misses.length(); j++) {
                    int miss = misses.getInt(j);
                    if (miss > NOT_MISS && miss <= EXPULSION) {
                        item.setMissType(miss);
                    }
                    if (miss == NOT_MATERIAL)
                        item.setNotMaterial(true);
                }
            }

            items.add(item);
        }
    } catch (IOException ioe) {
        Log.e(TAG, "Failed to fetch items", ioe);

    } catch (JSONException je) {
        Log.e(TAG, "Failed to parse JSON", je);
    }
    return items;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

Collection<PointOfInterest> fromFeatureCollection(JSONArray features) throws JSONException {
    ArrayList<PointOfInterest> pois = new ArrayList<PointOfInterest>(features.length());

    for (int i = 0; i < features.length(); i++) {
        pois.add(fromFeature(features.getJSONObject(i)));
    }/*from ww  w . j  a va  2 s .  c  o m*/

    return pois;
}

From source file:org.mapsforge.poi.exchange.GeoJsonPoiReader.java

Collection<PointOfInterest> fromGeometryCollection(JSONArray geometries) throws JSONException {
    ArrayList<PointOfInterest> pois = new ArrayList<PointOfInterest>(geometries.length());

    for (int i = 0; i < geometries.length(); i++) {
        pois.add(fromFeature(geometries.getJSONObject(i)));
    }/*from  ww  w . jav a  2s  .  co  m*/

    return pois;
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public List<Carrier> getTopOperators(double latitude, double longitude, int radius, int mcc, int limit)
        throws LibException {
    List<Carrier> carriers = new ArrayList<Carrier>();
    try {//w  w  w  .  j  a  va 2s .  c om
        String path = mHost + "/api/topop";

        TelephonyManager telephony = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
        String ccode = telephony.getNetworkCountryIso();
        URL request = TopOperatorsRequest.getURL(path, mApiKey, latitude, longitude, radius, mcc, limit, ccode);
        HttpURLConnection connection = (HttpURLConnection) request.openConnection();
        connection.connect();
        verifyConnectionResponse(connection);
        String topResponseString = readString(connection);
        LoggerUtil.logToFile(LoggerUtil.Level.DEBUG, TAG, "getTopOperators", request.toString());

        //HttpClient mHttpClient = HttpUtils.createHttpClient();
        //HttpResponse topResponse = mHttpClient.execute(topRequest);
        //verifyResponse(topResponse);
        if (topResponseString.length() > 2) {
            SharedPreferences securePreferences = PreferenceKeys.getSecurePreferences(mContext);
            securePreferences.edit().putString(PreferenceKeys.Miscellaneous.TOPOP_RESPONSE, topResponseString)
                    .commit();
            securePreferences.edit()
                    .putString(PreferenceKeys.Miscellaneous.TOPOP_LAT, Double.toString(latitude)).commit();
            securePreferences.edit()
                    .putString(PreferenceKeys.Miscellaneous.TOPOP_LNG, Double.toString(longitude)).commit();
        }

        JSONArray operators = new JSONObject(topResponseString).getJSONArray("operators");
        for (int i = 0; i < operators.length(); i++) {
            Carrier carrier = new Carrier(operators.getJSONObject(i));
            carrier.loadLogo(mContext);
            if (carrier != null)
                carriers.add(carrier);
        }
    } catch (IOException e) {
        throw new LibException(e);
    } catch (Exception e) {
        throw new LibException(e);
    }
    return carriers;
}

From source file:org.restcomm.app.utillib.Reporters.WebReporter.WebReporter.java

public static String geocode(Context context, double latitude, double longitude) {
    String addressString = String.format("%.4f, %.4f", latitude, longitude);
    try {//from   ww w  .  j  a  v a2  s .co m
        String apiKey = Global.getApiKey(context);
        String server = Global.getApiUrl(context);
        String url = server + "/api/osm/location?apiKey=" + apiKey + "&location=" + latitude + "&location="
                + longitude;
        String response = WebReporter.getHttpURLResponse(url, false);

        JSONObject json = null;
        JSONArray jsonArray = null;

        if (response == null)
            return addressString;

        try {
            jsonArray = new JSONArray(response);
        } catch (JSONException e) {
            return addressString;
        }
        try {
            for (int i = 0; i < jsonArray.length(); i++) {
                json = jsonArray.getJSONObject(i);
                if (json.has("error")) {
                    String error = json.getString("error");
                    return null;
                } else {
                    addressString = "";
                    json = json.getJSONObject("address");
                    String number = "";
                    if (json.has("house_number")) {
                        number = json.getString("house_number");
                        addressString += number + " ";
                    }
                    String road = json.getString("road");
                    addressString += road;// + suburb;
                    return addressString;
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
    }

    return addressString;
}

From source file:fr.arnaudguyon.xmltojsonlib.XmlToJson.java

private void formatArray(JSONArray array, StringBuilder builder, String indent) {
    builder.append("[\n");

    for (int i = 0; i < array.length(); ++i) {
        Object element = array.opt(i);
        if (element instanceof JSONObject) {
            JSONObject child = (JSONObject) element;
            builder.append(indent);/*from  ww w.ja v  a2  s.c o  m*/
            builder.append(mIndentationPattern);
            builder.append("{\n");
            format(child, builder, indent + mIndentationPattern);
            builder.append(indent);
            builder.append(mIndentationPattern);
            builder.append("}");
        } else if (element instanceof JSONArray) {
            JSONArray child = (JSONArray) element;
            formatArray(child, builder, indent + mIndentationPattern);
        } else {
            formatValue(element, builder);
        }
        if (i < array.length() - 1) {
            builder.append(",");
        }
        builder.append("\n");
    }
    builder.append(indent);
    builder.append("]");
}

From source file:org.openmrs.mobile.listeners.visit.FindVisitsByPatientUUIDListener.java

@Override
public void onResponse(JSONObject response) {
    mLogger.d(response.toString());// ww w  . j  a  va2 s .c om

    try {
        JSONArray visitResultJSON = response.getJSONArray(BaseManager.RESULTS_KEY);
        if (visitResultJSON.length() > 0) {
            for (int i = 0; i < visitResultJSON.length(); i++) {
                Visit visit = VisitMapper.map(visitResultJSON.getJSONObject(i));
                long visitId = visitDAO.getVisitsIDByUUID(visit.getUuid());

                if (visitId > 0) {
                    visitDAO.updateVisit(visit, visitId, mPatientID);
                } else {
                    visitDAO.saveVisit(visit, mPatientID);
                }
            }
        }
    } catch (JSONException e) {
        mErrorOccurred = true;
        mLogger.d(e.toString());
    } finally {
        updateData();
    }
}