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:cgeo.geocaching.connector.gc.GCParser.java

private static List<LogEntry> parseLogs(final boolean friends, String rawResponse) {
    final List<LogEntry> logs = new ArrayList<LogEntry>();

    // for non logged in users the log book is not shown
    if (StringUtils.isBlank(rawResponse)) {
        return logs;
    }//w ww  . j  ava  2s  . c om

    try {
        final JSONObject resp = new JSONObject(rawResponse);
        if (!resp.getString("status").equals("success")) {
            Log.e("GCParser.loadLogsFromDetails: status is " + resp.getString("status"));
            return null;
        }

        final JSONArray data = resp.getJSONArray("data");

        for (int index = 0; index < data.length(); index++) {
            final JSONObject entry = data.getJSONObject(index);

            // FIXME: use the "LogType" field instead of the "LogTypeImage" one.
            final String logIconNameExt = entry.optString("LogTypeImage", ".gif");
            final String logIconName = logIconNameExt.substring(0, logIconNameExt.length() - 4);

            long date = 0;
            try {
                date = GCLogin.parseGcCustomDate(entry.getString("Visited")).getTime();
            } catch (final ParseException e) {
                Log.e("GCParser.loadLogsFromDetails: failed to parse log date.");
            }

            // TODO: we should update our log data structure to be able to record
            // proper coordinates, and make them clickable. In the meantime, it is
            // better to integrate those coordinates into the text rather than not
            // display them at all.
            final String latLon = entry.getString("LatLonString");
            final String logText = (StringUtils.isEmpty(latLon) ? "" : (latLon + "<br/><br/>"))
                    + TextUtils.removeControlCharacters(entry.getString("LogText"));
            final LogEntry logDone = new LogEntry(
                    TextUtils.removeControlCharacters(entry.getString("UserName")), date,
                    LogType.getByIconName(logIconName), logText);
            logDone.found = entry.getInt("GeocacheFindCount");
            logDone.friend = friends;

            final JSONArray images = entry.getJSONArray("Images");
            for (int i = 0; i < images.length(); i++) {
                final JSONObject image = images.getJSONObject(i);
                final String url = "http://imgcdn.geocaching.com/cache/log/large/"
                        + image.getString("FileName");
                final String title = TextUtils.removeControlCharacters(image.getString("Name"));
                final Image logImage = new Image(url, title);
                logDone.addLogImage(logImage);
            }

            logs.add(logDone);
        }
    } catch (final JSONException e) {
        // failed to parse logs
        Log.w("GCParser.loadLogsFromDetails: Failed to parse cache logs", e);
    }

    return logs;
}

From source file:com.github.cambierr.lorawanpacket.semtech.PushData.java

public PushData(byte[] _randoms, ByteBuffer _raw) throws MalformedPacketException {
    super(_randoms, PacketType.PUSH_DATA);
    _raw.order(ByteOrder.LITTLE_ENDIAN);

    if (_raw.remaining() < 8) {
        throw new MalformedPacketException("too short");
    }/*from w  w  w. jav a 2  s.  c o  m*/

    gatewayEui = new byte[8];
    _raw.get(gatewayEui);

    byte[] json = new byte[_raw.remaining()];
    _raw.get(json);
    JSONObject jo;

    try {
        jo = new JSONObject(new String(json));
    } catch (JSONException ex) {
        throw new MalformedPacketException("malformed json");
    }

    stats = new ArrayList<>();
    rxpks = new ArrayList<>();

    if (jo.has("rxpk")) {
        if (!jo.get("rxpk").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (rxpk)");
        }
        JSONArray rxpk = jo.getJSONArray("rxpk");

        for (int i = 0; i < rxpk.length(); i++) {
            rxpks.add(new Rxpk(rxpk.getJSONObject(i)));
        }
    }

    if (jo.has("stat")) {
        if (!jo.get("stat").getClass().equals(JSONArray.class)) {
            throw new MalformedPacketException("malformed json (stat)");
        }
        JSONArray stat = jo.getJSONArray("stat");

        for (int i = 0; i < stat.length(); i++) {
            stats.add(new Stat(stat.getJSONObject(i)));
        }
    }

}

From source file:com.jjoseba.podemosquotes.model.JSONReader.java

public ArrayList<Quote> parse() {
    String contentsJson = readJSONFile();
    HashMap<String, QuoteAuthor> authors = new HashMap<>();
    ArrayList<Quote> quotes = new ArrayList<>();

    try {/*from   ww  w . j  a v a2  s .c  o m*/
        JSONObject json = new JSONObject(contentsJson);
        JSONArray authorsArray = json.getJSONArray("authors");
        for (int i = 0; i < authorsArray.length(); ++i) {
            JSONObject auth = (JSONObject) authorsArray.get(i);
            QuoteAuthor author = new QuoteAuthor();
            author.setName(auth.getString("name"));
            author.setImagePath(auth.getString("image"));
            author.setPosition(auth.getString("position"));

            authors.put(auth.getString("id"), author);
        }

        JSONArray quotesArray = json.getJSONArray("quotes");
        for (int i = 0; i < quotesArray.length(); ++i) {
            JSONObject q = (JSONObject) quotesArray.get(i);
            Quote quote = new Quote();
            quote.setQuote(q.getString("quote"));
            quote.setSoundPath(q.getString("sound"));
            quote.setAuthor(authors.get(q.getString("author")));
            quotes.add(quote);
        }

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

From source file:com.doylestowncoder.plugin.mobileaccessibility.MobileAccessibility.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {/*from www .  j a v  a2 s.  c o  m*/
        if (action.equals("isScreenReaderRunning")) {
            isScreenReaderRunning(callbackContext);
            return true;
        } else if (action.equals("isClosedCaptioningEnabled")) {
            isClosedCaptioningEnabled(callbackContext);
            return true;
        } else if (action.equals("isTouchExplorationEnabled")) {
            isTouchExplorationEnabled(callbackContext);
            return true;
        } else if (action.equals("postNotification")) {
            if (args.length() > 1) {
                String string = args.getString(1);
                if (!string.isEmpty()) {
                    announceForAccessibility(string, callbackContext);
                }
            }
            return true;
        } else if (action.equals("getTextZoom")) {
            getTextZoom(callbackContext);
            return true;
        } else if (action.equals("setTextZoom")) {
            if (args.length() > 0) {
                double textZoom = args.getDouble(0);
                if (textZoom > 0) {
                    setTextZoom(textZoom, callbackContext);
                }
            }
            return true;
        } else if (action.equals("updateTextZoom")) {
            updateTextZoom(callbackContext);
            return true;
        } else if (action.equals("start")) {
            start(callbackContext);
            return true;
        } else if (action.equals("stop")) {
            stop();
            return true;
        }
    } catch (JSONException e) {
        e.printStackTrace();
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
    }
    return false;
}

From source file:net.olejon.mdapp.LvhCategoriesAdapter.java

@Override
public void onBindViewHolder(CategoryViewHolder viewHolder, int i) {
    try {/*from   w  w w. java2  s  . c om*/
        final JSONObject categoriesJsonObject = mCategories.getJSONObject(i);

        viewHolder.card.setCardBackgroundColor(Color.parseColor(mColor));

        switch (mIcon) {
        case "lvh_urgent": {
            viewHolder.icon.setImageResource(R.drawable.ic_favorite_white_24dp);
            break;
        }
        case "lvh_symptoms": {
            viewHolder.icon.setImageResource(R.drawable.ic_stethoscope);
            break;
        }
        case "lvh_injuries": {
            viewHolder.icon.setImageResource(R.drawable.ic_healing_white_24dp);
            break;
        }
        case "lvh_administrative": {
            viewHolder.icon.setImageResource(R.drawable.ic_my_library_books_white_24dp);
            break;
        }
        }

        viewHolder.title.setText(categoriesJsonObject.getString("title"));

        viewHolder.categories.removeAllViews();

        final JSONArray itemsJsonArray = categoriesJsonObject.getJSONArray("items");

        for (int f = 0; f < itemsJsonArray.length(); f++) {
            final JSONObject categoryJsonObject = itemsJsonArray.getJSONObject(f);

            final String name = categoryJsonObject.getString("name");
            final String uri = categoryJsonObject.getString("uri");

            TextView textView = (TextView) mLayoutInflater
                    .inflate(R.layout.activity_lvh_categories_card_categories_item, null);
            textView.setText(name);

            textView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(mContext, MainWebViewActivity.class);
                    intent.putExtra("title", name);
                    intent.putExtra("uri", uri);
                    mContext.startActivity(intent);
                }
            });

            viewHolder.categories.addView(textView);
        }

        animateView(viewHolder.card, i);
    } catch (Exception e) {
        Log.e("LvhCategoriesAdapter", Log.getStackTraceString(e));
    }
}

From source file:app.com.example.android.sunshine.ForecastFragment.java

/**
 * Take the String representing the complete forecast in JSON Format and
 * pull out the data we need to construct the Strings needed for the wireframes.
 *
 * Fortunately parsing is easy:  constructor takes the JSON string and converts it
 * into an Object hierarchy for us./*from  w w  w  . j  a  v a2 s. co m*/
 */
private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException {

    // These are the names of the JSON objects that need to be extracted.
    final String OWM_LIST = "list";
    final String OWM_WEATHER = "weather";
    final String OWM_TEMPERATURE = "temp";
    final String OWM_MAX = "max";
    final String OWM_MIN = "min";
    final String OWM_DATETIME = "dt";
    final String OWM_DESCRIPTION = "main";

    JSONObject forecastJson = new JSONObject(forecastJsonStr);
    JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);

    String[] resultStrs = new String[numDays];
    for (int i = 0; i < weatherArray.length(); i++) {
        // For now, using the format "Day, description, hi/low"
        String day;
        String description;
        String highAndLow;

        // Get the JSON object representing the day
        JSONObject dayForecast = weatherArray.getJSONObject(i);

        // The date/time is returned as a long.  We need to convert that
        // into something human-readable, since most people won't read "1400356800" as
        // "this saturday".
        long dateTime = dayForecast.getLong(OWM_DATETIME);
        day = getReadableDateString(dateTime);

        // description is in a child array called "weather", which is 1 element long.
        JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        description = weatherObject.getString(OWM_DESCRIPTION);

        // Temperatures are in a child object called "temp".  Try not to name variables
        // "temp" when working with temperature.  It confuses everybody.
        JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
        double high = temperatureObject.getDouble(OWM_MAX);
        double low = temperatureObject.getDouble(OWM_MIN);

        highAndLow = formatHighLows(high, low);
        resultStrs[i] = day + " - " + description + " - " + highAndLow;
    }

    return resultStrs;
}

From source file:com.mikecorrigan.trainscorekeeper.Game.java

public boolean read(final Context context) {
    Log.vc(VERBOSE, TAG, "read: context=" + context);

    String path = context.getFilesDir() + File.separator + SAVED_FILE;
    File file = new File(path);

    JSONObject jsonRoot = JsonUtils.readFromFile(file);
    if (jsonRoot == null) {
        Log.e(TAG, "read: failed to read root");
        return false;
    }/*from   ww  w . j a v a  2  s  . co m*/

    scoreEvents.clear();
    lastScoreEvent = 0;

    try {
        spec = jsonRoot.getString(JsonSpec.GAME_SPEC);
        JSONArray jsonScoreEvents = jsonRoot.getJSONArray(JsonSpec.SCORES_KEY);

        for (int i = 0; i < jsonScoreEvents.length(); i++) {
            JSONObject jsonScoreEvent = jsonScoreEvents.getJSONObject(i);
            ScoreEvent scoreEvent = new ScoreEvent(jsonScoreEvent);
            scoreEvents.add(scoreEvent);

            notifyEnabled(scoreEvent.getPlayerId(), true);
        }
    } catch (JSONException e) {
        Log.th(TAG, e, "read: parse failed");
        return false;
    }

    lastScoreEvent = scoreEvents.size();

    notifyListeners();

    return true;
}

From source file:com.mikecorrigan.trainscorekeeper.Game.java

public boolean write(final Context context) {
    Log.vc(VERBOSE, TAG, "write: context=" + context);

    // Ignore any undo events.
    List<ScoreEvent> temp = scoreEvents = scoreEvents.subList(0, lastScoreEvent);

    // Convert the list of events to a JSON array, then convert to a string.
    String string = null;/*from  www . j  a  v a  2s  . c om*/
    try {
        JSONArray jsonScoreEvents = new JSONArray();
        for (ScoreEvent scoreEvent : temp) {
            JSONObject jsonScoreEvent = scoreEvent.toJson();
            if (jsonScoreEvent == null) {
                Log.w(TAG, "write: skipping score event");
                continue;
            }

            jsonScoreEvents.put(jsonScoreEvents.length(), jsonScoreEvent);
        }

        JSONObject jsonRoot = new JSONObject();
        jsonRoot.put(JsonSpec.SCORES_KEY, jsonScoreEvents);
        jsonRoot.put(JsonSpec.GAME_SPEC, spec);

        string = jsonRoot.toString();
    } catch (JSONException e) {
        Log.th(TAG, e, "write: failed");
        return false;
    }

    // Write the string into a file.
    if (string != null) {
        String path = context.getFilesDir() + File.separator + SAVED_FILE;
        File file = new File(path);
        FileUtils.writeStringToFile(file, string);
    }

    return true;
}

From source file:com.ecml.RecentSongsActivity.java

private void loadFileList() {
    filelist = new ArrayList<FileUri>();
    SharedPreferences settings = getSharedPreferences("midisheetmusic.recentFiles", 0);
    String recentFilesString = settings.getString("recentFiles", null);
    if (recentFilesString == null) {
        return;/*from w  w w.j a v  a2  s  .  c  o m*/
    }
    try {
        JSONArray jsonArray = new JSONArray(recentFilesString);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject obj = jsonArray.getJSONObject(i);
            FileUri file = FileUri.fromJson(obj, this);
            if (file != null) {
                filelist.add(file);
            }
        }
    } catch (Exception e) {
    }
}

From source file:org.jboss.aerogear.cordova.push.PushPlugin.java

private List<String> convert(String categories) throws JSONException {
    List<String> categoryList = null;
    if (categories != null) {
        categoryList = new ArrayList<String>();
        final JSONArray jsonArray = new JSONArray(categories);
        for (int i = 0; i < jsonArray.length(); i++) {
            categoryList.add(jsonArray.getString(i));
        }/*from  www. ja  va  2  s.c om*/
    }
    return categoryList;
}