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:net.olejon.mdapp.InteractionsCardsActivity.java

private void search(final String string, boolean cache) {
    try {//w  w w.  ja va  2 s  . c o m
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        String apiUri = getString(R.string.project_website_uri) + "api/1/interactions/?search="
                + URLEncoder.encode(string.toLowerCase(), "utf-8");

        if (!cache)
            requestQueue.getCache().remove(apiUri);

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(apiUri, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                if (response.length() == 0) {
                    mSwipeRefreshLayout.setVisibility(View.GONE);
                    mNoInteractionsLayout.setVisibility(View.VISIBLE);
                } else {
                    if (mTools.isTablet()) {
                        int spanCount = (response.length() == 1) ? 1 : 2;

                        mRecyclerView.setLayoutManager(
                                new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL));
                    }

                    mRecyclerView.setAdapter(new InteractionsCardsAdapter(mContext, mProgressBar, response));

                    ContentValues contentValues = new ContentValues();
                    contentValues.put(InteractionsSQLiteHelper.COLUMN_STRING, string);

                    SQLiteDatabase sqLiteDatabase = new InteractionsSQLiteHelper(mContext)
                            .getWritableDatabase();

                    sqLiteDatabase.delete(InteractionsSQLiteHelper.TABLE, InteractionsSQLiteHelper.COLUMN_STRING
                            + " = " + mTools.sqe(string) + " COLLATE NOCASE", null);
                    sqLiteDatabase.insert(InteractionsSQLiteHelper.TABLE, null, contentValues);

                    sqLiteDatabase.close();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                mProgressBar.setVisibility(View.GONE);
                mSwipeRefreshLayout.setRefreshing(false);

                mTools.showToast(getString(R.string.interactions_cards_something_went_wrong), 1);

                finish();

                Log.e("InteractionsCards", error.toString());
            }
        });

        requestQueue.add(jsonArrayRequest);
    } catch (Exception e) {
        Log.e("InteractionsCards", Log.getStackTraceString(e));
    }
}

From source file:drusy.ui.panels.WifiStatePanel.java

public void addUsersForWifiId(int id, final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_WIFI_STATIONS.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting WiFi id", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override//from w  w  w. j  a va 2s .c  o  m
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            clearUsers();
            if (success == true) {
                final JSONArray usersList = obj.getJSONArray("result");

                for (int i = 0; i < usersList.length(); ++i) {
                    JSONObject user = usersList.getJSONObject(i);
                    final String hostname = user.getString("hostname");
                    final long txBytes = user.getLong("tx_rate");
                    final long rxBytes = user.getLong("rx_rate");
                    JSONObject host = user.getJSONObject("host");
                    final String host_type = host.getString("host_type");

                    addUser(host_type, hostname, txBytes, rxBytes);
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Wi-Fi State (get users)", msg);
            }

            if (updater != null) {
                updater.updated();
            }
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Wi-Fi State (get users)", ex.getMessage());

            if (updater != null) {
                updater.updated();
            }
        }
    });
}

From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java

public static List<TranslationInfo> toTranslationList(JSONArray jsonArray) throws Exception {
    final int length = jsonArray.length();
    final List<TranslationInfo> translations = new ArrayList<TranslationInfo>(length);
    for (int i = 0; i < length; ++i) {
        final JSONObject translationObject = jsonArray.getJSONObject(i);
        final String name = translationObject.getString("name");
        final String shortName = translationObject.getString("shortName");
        final String language = translationObject.getString("language");
        final String blobKey = translationObject.optString("blobKey", null);
        final int size = translationObject.getInt("size");
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(shortName) || TextUtils.isEmpty(language)
                || size <= 0) {/*from  www .  j  av a 2 s  . c  om*/
            throw new Exception("Illegal translation info.");
        }
        translations.add(new TranslationInfo(name, shortName, language, blobKey, size));
    }
    return translations;
}

From source file:net.zionsoft.obadiah.model.translations.TranslationHelper.java

public static void saveVerses(SQLiteDatabase db, String translationShortName, int bookIndex, int chapterIndex,
        JSONObject versesObject) throws Exception {
    final ContentValues versesValues = new ContentValues(4);
    versesValues.put(DatabaseHelper.COLUMN_BOOK_INDEX, bookIndex);
    versesValues.put(DatabaseHelper.COLUMN_CHAPTER_INDEX, chapterIndex);
    final JSONArray paragraphArray = versesObject.getJSONArray("verses");
    final int paragraphCount = paragraphArray.length();
    boolean hasNonEmptyVerse = false;
    for (int verseIndex = 0; verseIndex < paragraphCount; ++verseIndex) {
        versesValues.put(DatabaseHelper.COLUMN_VERSE_INDEX, verseIndex);

        final String verse = paragraphArray.getString(verseIndex);
        if (!hasNonEmptyVerse && !TextUtils.isEmpty(verse))
            hasNonEmptyVerse = true;/*from w  w  w.j a  v a2s.  c o m*/
        versesValues.put(DatabaseHelper.COLUMN_TEXT, verse);

        db.insert(translationShortName, null, versesValues);
    }
    if (!hasNonEmptyVerse) {
        throw new Exception(
                String.format("Empty chapter: %s %d-%d", translationShortName, bookIndex, chapterIndex));
    }
}

From source file:com.tweetlanes.android.App.java

public void updateTwitterAccountCount() {

    mAccounts.clear();//from   w ww .j  ava  2 s  .  c  o m

    long currentAccountId = mPreferences.getLong(SHARED_PREFERENCES_KEY_CURRENT_ACCOUNT_ID, -1);
    String accountIndices = mPreferences.getString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, null);
    if (accountIndices != null) {
        try {
            JSONArray jsonArray = new JSONArray(accountIndices);
            for (int i = 0; i < jsonArray.length(); i++) {
                Long id = jsonArray.getLong(i);

                String key = getAccountDescriptorKey(id);
                String jsonAsString = mPreferences.getString(key, null);
                if (jsonAsString != null) {
                    AccountDescriptor account = new AccountDescriptor(this, jsonAsString);
                    mAccounts.add(account);

                    if (currentAccountId != -1 && account.getId() == currentAccountId) {
                        mCurrentAccountIndex = i;
                    }
                }
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    if (mCurrentAccountIndex == null && mAccounts.size() > 0) {
        mCurrentAccountIndex = 0;
    }
}

From source file:com.tweetlanes.android.App.java

public void onPostSignIn(TwitterUser user, String oAuthToken, String oAuthSecret,
        SocialNetConstant.Type oSocialNetType) {

    if (user != null) {

        try {/*from   w  w  w  .ja v  a  2s  .co m*/

            final Editor edit = mPreferences.edit();
            String userIdAsString = Long.toString(user.getId());

            AccountDescriptor account = new AccountDescriptor(this, user, oAuthToken, oAuthSecret,
                    oSocialNetType);
            edit.putString(getAccountDescriptorKey(user.getId()), account.toString());

            String accountIndices = mPreferences.getString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, null);
            JSONArray jsonArray;

            if (accountIndices == null) {
                jsonArray = new JSONArray();
                jsonArray.put(0, user.getId());
                mAccounts.add(account);
            } else {
                jsonArray = new JSONArray(accountIndices);
                boolean exists = false;
                for (int i = 0; i < jsonArray.length(); i++) {
                    String c = jsonArray.getString(i);
                    if (c.compareTo(userIdAsString) == 0) {
                        exists = true;
                        mAccounts.set(i, account);
                        break;
                    }
                }

                if (exists == false) {
                    jsonArray.put(userIdAsString);
                    mAccounts.add(account);
                }
            }

            accountIndices = jsonArray.toString();
            edit.putString(SHARED_PREFERENCES_KEY_ACCOUNT_INDICES, accountIndices);

            edit.commit();

            setCurrentAccount(user.getId());

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        updateTwitterAccountCount();
        if (TwitterManager.get().getSocialNetType() == oSocialNetType) {
            TwitterManager.get().setOAuthTokenWithSecret(oAuthToken, oAuthSecret, true);
        } else {
            TwitterManager.initModule(oSocialNetType,
                    oSocialNetType == SocialNetConstant.Type.Twitter ? ConsumerKeyConstants.TWITTER_CONSUMER_KEY
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_KEY,
                    oSocialNetType == SocialNetConstant.Type.Twitter
                            ? ConsumerKeyConstants.TWITTER_CONSUMER_SECRET
                            : ConsumerKeyConstants.APPDOTNET_CONSUMER_SECRET,
                    oAuthToken, oAuthSecret, getCurrentAccountKey(), mConnectionStatusCallbacks);
        }
    }
}

From source file:de.dakror.virtualhub.data.Catalog.java

public Catalog(JSONObject o) {
    try {/* ww w.j  a  v  a  2  s  .c o  m*/
        name = o.getString("name");

        JSONArray sources = o.getJSONArray("sources");
        for (int i = 0; i < sources.length(); i++)
            this.sources.add(new File(sources.getString(i)));

        JSONArray tags = o.getJSONArray("tags");
        for (int i = 0; i < tags.length(); i++)
            this.tags.add(tags.getString(i));
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:tom.udacity.sample.sunrise.WeatherDataParser.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  . jav  a  2s  .  co m
 */
public String[] getWeatherDataFromJson(String forecastJsonStr, int numDays, String locationQuery)
        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:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java

public FindReplicaGroupPacket(JSONObject msg) throws JSONException {
    super(msg);/*from  w  w  w.j  av  a 2  s  . c om*/
    this.packetType = PaxosPacketType.FIND_REPLICA_GROUP;
    this.nodeID = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    JSONArray jsonGroup = null;
    if (msg.has(PaxosPacket.NodeIDKeys.GROUP.toString())) {
        jsonGroup = msg.getJSONArray(PaxosPacket.NodeIDKeys.GROUP.toString());
    }
    if (jsonGroup != null && jsonGroup.length() > 0) {
        this.group = new int[jsonGroup.length()];
        for (int i = 0; i < jsonGroup.length(); i++) {
            this.group[i] = Integer.valueOf(jsonGroup.getString(i));
        }
    } else
        this.group = null;
}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

public BayeuxMessage(String jsonMessage) throws JSONException {
    JSONTokener jsont = new JSONTokener(jsonMessage);
    JSONArray jsona = new JSONArray(jsont);
    // FIXME ? msg   .
    JSONObject jsono = jsona.getJSONObject(0);
    // channel /*from  w  ww  .  j  av a 2s  .  com*/
    channel = jsono.getString("channel");
    if (channel != null && channel.startsWith("/meta/")) {
        if ("/meta/handshake".equals(channel)) {
            // type 
            type = BayeuxMessage.HANDSHAKE_REQ;
            // version 
            version = jsono.getString("version");
            JSONArray jsonaSupportedConnectionTypes = jsono.getJSONArray("supportedConnectionTypes");
            supportedConnectionTypesList = new ArrayList<String>();
            // supportedConnectionTypes 
            for (int i = 0; i < jsonaSupportedConnectionTypes.length(); i++) {
                supportedConnectionTypesList.add(jsonaSupportedConnectionTypes.getString(i));
            }
            // Handshake req ?  mandatory ? ? ?.
        } else if ("/meta/connect".equals(channel)) {
            type = BayeuxMessage.CONNECT_REQ;
            clientId = jsono.getString("clientId");
            connectionType = jsono.getString("connectionType");
        } else if ("/meta/disconnect".equals(channel)) {
            type = BayeuxMessage.DISCONNECT_REQ;
            clientId = jsono.getString("clientId");
        } else if ("/meta/subscribe".equals(channel)) {
            type = BayeuxMessage.SUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        } else if ("/meta/unsubscribe".equals(channel)) {
            type = BayeuxMessage.UNSUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        }
    } else {
        type = BayeuxMessage.PUBLISH_REQ;
        data = jsono.getString("data");
    }
}