Example usage for org.json JSONObject getString

List of usage examples for org.json JSONObject getString

Introduction

In this page you can find the example usage for org.json JSONObject getString.

Prototype

public String getString(String key) throws JSONException 

Source Link

Document

Get the string associated with a key.

Usage

From source file:face4j.response.LimitsResponseImpl.java

public LimitsResponseImpl(final String json) throws FaceClientException {
    super(json);//w  w  w. j  av  a  2s  . c o m

    try {
        // usage stats
        final JSONObject usage = response.getJSONObject("usage");
        namespaceRemaining = optInt(usage, "namespace_remaining");
        namespaceUsed = optInt(usage, "namespace_used");
        namespaceLimit = optInt(usage, "namespace_limit");
        restTimeString = usage.getString("reset_time_text");
        resetDate = new Date(usage.getLong("reset_time"));
        remaining = usage.getInt("remaining");
        used = usage.getInt("used");
        limit = usage.getInt("limit");
    }

    catch (JSONException jex) {
        logger.error("Error: ", jex);
        throw new FaceClientException(jex);
    }
}

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

public Rxpk(JSONObject _json) throws MalformedPacketException {

    /**//w  ww . jav a 2 s  .  c o m
     * tmst
     */
    if (!_json.has("tmst")) {
        throw new MalformedPacketException("missing tmst");
    } else {
        tmst = _json.getInt("tmst");
    }

    /**
     * time
     */
    if (!_json.has("time")) {
        throw new MalformedPacketException("missing time");
    } else {
        time = _json.getString("time");
    }

    /**
     * chan
     */
    if (!_json.has("chan")) {
        throw new MalformedPacketException("missing chan");
    } else {
        chan = _json.getInt("chan");
    }

    /**
     * rfch
     */
    if (!_json.has("rfch")) {
        throw new MalformedPacketException("missing rfch");
    } else {
        rfch = _json.getInt("rfch");
    }

    /**
     * freq
     */
    if (!_json.has("freq")) {
        throw new MalformedPacketException("missing freq");
    } else {
        freq = _json.getDouble("stat");
    }

    /**
     * stat
     */
    if (!_json.has("stat")) {
        throw new MalformedPacketException("missing stat");
    } else {
        stat = _json.getInt("stat");
        if (stat > 1 || stat < -1) {
            throw new MalformedPacketException("stat must be equal to -1, 0, or 1");
        }
    }

    /**
     * modu
     */
    if (!_json.has("modu")) {
        throw new MalformedPacketException("missing modu");
    } else {
        modu = Modulation.parse(_json.getString("modu"));
    }

    /**
     * datr
     */
    if (!_json.has("datr")) {
        throw new MalformedPacketException("missing datr");
    } else {
        switch (modu) {
        case FSK:
            datr = _json.getInt("datr");
            break;
        case LORA:
            datr = _json.getString("datr");
            break;
        }
    }

    /**
     * codr
     */
    if (!_json.has("codr")) {
        if (modu.equals(Modulation.FSK)) {
            codr = null;
        } else {
            throw new MalformedPacketException("missing codr");
        }
    } else {
        codr = _json.getString("codr");
    }

    /**
     * rssi
     */
    if (!_json.has("rssi")) {
        throw new MalformedPacketException("missing rssi");
    } else {
        rssi = _json.getInt("rssi");
    }

    /**
     * lsnr
     */
    if (!_json.has("lsnr")) {
        if (modu.equals(Modulation.FSK)) {
            lsnr = Double.MAX_VALUE;
        } else {
            throw new MalformedPacketException("missing lsnr");
        }
    } else {
        lsnr = _json.getDouble("lsnr");
    }

    /**
     * size
     */
    if (!_json.has("size")) {
        throw new MalformedPacketException("missing size");
    } else {
        size = _json.getInt("size");
    }

    /**
     * data
     */
    if (!_json.has("data")) {
        throw new MalformedPacketException("missing data");
    } else {
        byte[] raw;

        try {
            raw = Base64.getDecoder().decode(_json.getString("data"));
        } catch (IllegalArgumentException ex) {
            throw new MalformedPacketException("malformed data");
        }

        data = new PhyPayload(ByteBuffer.wrap(raw));
    }
}

From source file:org.pixmob.droidlink.sync.SyncAdapter.java

private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider,
        SyncResult syncResult, boolean fullSync) {
    // Prepare the query.
    final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?";
    final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE),
            String.valueOf(EventsContract.PENDING_DELETE_STATE) };

    // Get local data to sync.
    final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8);
    final Set<String> eventsToDelete = new HashSet<String>(4);
    Cursor c = null;//w  ww.j a v a  2  s. c  o m
    try {
        c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null);

        final int idIdx = c.getColumnIndexOrThrow(_ID);
        final int typeIdx = c.getColumnIndexOrThrow(TYPE);
        final int createdIdx = c.getColumnIndexOrThrow(CREATED);
        final int numberIdx = c.getColumnIndexOrThrow(NUMBER);
        final int nameIdx = c.getColumnIndexOrThrow(NAME);
        final int messageIdx = c.getColumnIndexOrThrow(MESSAGE);
        final int stateIdx = c.getColumnIndexOrThrow(STATE);

        while (c.moveToNext()) {
            final String eventId = c.getString(idIdx);
            final int eventState = c.getInt(stateIdx);

            if (EventsContract.PENDING_UPLOAD_STATE == eventState) {
                // This is a newly created event.
                final JSONObject event = new JSONObject();
                try {
                    event.put("deviceId", client.getDeviceId());
                    event.put("created", c.getLong(createdIdx));
                    event.put("type", c.getInt(typeIdx));
                    event.put("number", c.getString(numberIdx));
                    event.put("name", c.getString(nameIdx));
                    event.put("message", c.getString(messageIdx));
                } catch (JSONException e) {
                    Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e);
                    syncResult.stats.numSkippedEntries++;
                    continue;
                }
                eventsToUpload.put(eventId, event);
            } else if (EventsContract.PENDING_DELETE_STATE == eventState) {
                // The user wants this event to be deleted.
                eventsToDelete.add(eventId);
            }
        }
    } catch (RemoteException e) {
        Log.e(TAG, "Failed to get events: cannot sync", e);
        syncResult.stats.numIoExceptions++;
    } finally {
        if (c != null) {
            c.close();
            c = null;
        }
    }

    final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32);
    final ContentValues values = new ContentValues(8);

    if (eventsToDelete.isEmpty()) {
        Log.i(TAG, "No events to delete");
    } else {
        Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete");
    }

    // Delete events on the remote server.
    for (final String eventId : eventsToDelete) {
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Deleting event: " + eventId);
        }

        try {
            client.delete("/events/" + eventId);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        } catch (IOException e) {
            Log.e(TAG, "Event deletion error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    if (fullSync) {
        // Get all events from the remote server.
        final JSONArray events;
        if (DEVELOPER_MODE) {
            Log.d(TAG, "Fetching events from the remote server");
        }
        try {
            events = client.getAsArray("/events");
        } catch (IOException e) {
            Log.e(TAG, "Event listing error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }

        final int eventsLen = events != null ? events.length() : 0;
        if (eventsLen == 0) {
            Log.i(TAG, "No events from the remote server");
        } else {
            Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server");
        }

        // Build a collection with local event identifiers.
        // This collection will be used to identify which events have
        // been deleted on the remote server.
        final Set<String> localEventIds;
        try {
            c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?",
                    new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null);
            localEventIds = new HashSet<String>(c.getCount());

            final int idIdx = c.getColumnIndexOrThrow(_ID);
            while (c.moveToNext()) {
                final String eventId = c.getString(idIdx);
                localEventIds.add(eventId);
            }
        } catch (RemoteException e) {
            Log.e(TAG, "Failed to get events from local database", e);
            syncResult.stats.numIoExceptions++;
            return;
        } finally {
            if (c != null) {
                c.close();
                c = null;
            }
        }

        String newEventId = null;
        int newEventCount = 0;

        // Reconcile remote events with local events.
        for (int i = 0; i < eventsLen; ++i) {
            String eventId = null;
            try {
                final JSONObject event = events.getJSONObject(i);
                eventId = event.getString("id");

                // Check if this event exists in the local database.
                if (localEventIds.contains(eventId)) {
                    // Found the event: update it.
                    values.clear();
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Updating event in local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withExpectedCount(1).withValues(values).build());
                    syncResult.stats.numUpdates++;
                } else {
                    // The event was not found: insert it.
                    values.clear();
                    values.put(_ID, eventId);
                    values.put(DEVICE_ID, event.getString("deviceId"));
                    values.put(CREATED, event.getLong("created"));
                    values.put(TYPE, event.getInt("type"));
                    values.put(NUMBER, trimToNull(event.getString("number")));
                    values.put(NAME, trimToNull(event.getString("name")));
                    values.put(MESSAGE, trimToNull(event.getString("message")));
                    values.put(STATE, EventsContract.UPLOADED_STATE);

                    if (DEVELOPER_MODE) {
                        Log.d(TAG, "Adding event to local database: " + eventId);
                    }
                    batch.add(ContentProviderOperation
                            .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId))
                            .withValues(values).build());
                    syncResult.stats.numInserts++;

                    ++newEventCount;
                    if (newEventId == null) {
                        newEventId = eventId;
                    }
                }

                // This event now exists in the local database:
                // remove its identifier from this collection as we
                // don't want to delete it.
                localEventIds.remove(eventId);
            } catch (JSONException e) {
                Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e);
                syncResult.stats.numSkippedEntries++;
                continue;
            }
        }

        // The remaining event identifiers was removed on the remote
        // server: there are still present in the local database. These
        // events are now being deleted.
        for (final String eventId : localEventIds) {
            if (DEVELOPER_MODE) {
                Log.d(TAG, "Deleting event in local database: " + eventId);
            }
            batch.add(ContentProviderOperation
                    .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build());
            syncResult.stats.numDeletes++;
        }

        try {
            provider.applyBatch(batch);
        } catch (Exception e) {
            Log.e(TAG, "Database error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
        batch.clear();

        if (newEventCount > 1) {
            newEventId = null;
        }
        if (newEventCount != 0) {
            startSyncNotificationService(newEventCount, newEventId);
        }
    }

    final int numEventsToUpload = eventsToUpload.size();
    if (numEventsToUpload == 0) {
        Log.i(TAG, "No events to upload");
    } else {
        Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload");
    }

    // Send local events to the remote server.
    for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) {
        final String eventId = entry.getKey();

        if (DEVELOPER_MODE) {
            Log.d(TAG, "Uploading event: " + eventId);
        }

        final JSONObject event = entry.getValue();
        try {
            client.put("/events/" + eventId, event);

            if (DEVELOPER_MODE) {
                Log.d(TAG, "Updating event state to UPLOADED: " + eventId);
            }
            values.clear();
            values.put(STATE, EventsContract.UPLOADED_STATE);
            batch.add(ContentProviderOperation
                    .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values)
                    .withExpectedCount(1).build());
            syncResult.stats.numUpdates++;

            Log.i(TAG, "Event upload successful: " + eventId);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                Log.e(TAG, "Device not found: cannot sync", e);
                registerDevice();
            } else {
                Log.e(TAG, "Network error: cannot sync", e);
            }
            syncResult.stats.numIoExceptions++;
            return;
        } catch (IOException e) {
            Log.e(TAG, "Event upload error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        }
    }

    try {
        provider.applyBatch(batch);
    } catch (Exception e) {
        Log.w(TAG, "Database error: cannot sync", e);
        syncResult.stats.numIoExceptions++;
        return;
    }
    batch.clear();

    final SharedPreferences.Editor prefsEditor = prefs.edit();
    final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty();
    if (syncRequired) {
        // Generate an unique sync token: the server will send this token to
        // every devices. If this token is received on this device, the sync
        // will not start.
        final String syncToken = UUID.randomUUID().toString();
        prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken);
        Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);

        // Sync user devices.
        try {
            final JSONObject data = new JSONObject();
            data.put("token", syncToken);
            client.post("/devices/" + client.getDeviceId() + "/sync", data);
        } catch (NetworkClientException e) {
            if (e.getStatusCode() == 404) {
                registerDevice();
            }
        } catch (IOException e) {
            Log.e(TAG, "Device sync error: cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        } catch (AppEngineAuthenticationException e) {
            Log.e(TAG, "Authentication error: cannot sync", e);
            syncResult.stats.numAuthExceptions++;
            return;
        } catch (JSONException e) {
            Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e);
            syncResult.stats.numIoExceptions++;
            return;
        }
    }

    // Store sync time.
    prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis());
    Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor);
}

From source file:com.facebook.android.FBUtil.java

/**
 * Parse a server response into a JSON Object. This is a basic
 * implementation using org.json.JSONObject representation. More
 * sophisticated applications may wish to do their own parsing.
 *
 * The parsed JSON is checked for a variety of error fields and
 * a FacebookException is thrown if an error condition is set,
 * populated with the error message and error type or code if
 * available.//from  w  w  w .  ja  v a 2s . c o m
 *
 * @param response - string representation of the response
 * @return the response as a JSON Object
 * @throws JSONException - if the response is not valid JSON
 * @throws FacebookError - if an error condition is set
 */

public static JSONObject parseJson(String response) throws JSONException, FacebookError {
    // Edge case: when sending a POST request to /[post_id]/likes
    // the return value is 'true' or 'false'. Unfortunately
    // these values cause the JSONObject constructor to throw
    // an exception.
    if (response.equals("false")) {
        throw new FacebookError("request failed");
    }
    if (response.equals("true")) {
        response = "{value : true}";
    }
    JSONObject json = new JSONObject(response);

    // errors set by the server are not consistent
    // they depend on the method and endpoint
    if (json.has("error")) {
        JSONObject error = json.getJSONObject("error");
        throw new FacebookError(error.getString("message"), error.getString("type"), 0);
    }
    if (json.has("error_code") && json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"), "",
                Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_code")) {
        throw new FacebookError("request failed", "", Integer.parseInt(json.getString("error_code")));
    }
    if (json.has("error_msg")) {
        throw new FacebookError(json.getString("error_msg"));
    }
    if (json.has("error_reason")) {
        throw new FacebookError(json.getString("error_reason"));
    }
    return json;
}

From source file:com.clearner.youtube.PlaylistItem.java

public PlaylistItem(JSONObject jsonItem) throws JSONException {
    id = jsonItem.getString("id");
    final JSONObject snippet = jsonItem.getJSONObject("snippet");
    position = snippet.getInt("position");
    title = snippet.getString("title");
    description = snippet.getString("description");
    thumbnailUrl = snippet.getJSONObject("thumbnails").getJSONObject("medium").getString("url");
    videoId = snippet.getJSONObject("resourceId").getString("videoId");
}

From source file:se.anyro.tagtider.model.Station.java

public Station(JSONObject station) throws JSONException {
    id = station.getInt("id");
    name = station.getString("name");
    String lat, lng;//from  www .  ja  v  a  2  s .  com
    lat = station.getString("lat");
    lng = station.getString("lng");
    if (lat != null && lng != null) {
        location = new Location("Tgtider");
        try {
            location.setLatitude(Double.parseDouble(lat));
            location.setLongitude(Double.parseDouble(lng));
        } catch (NumberFormatException e) {
            location.setLatitude(0);
        }
    }
}

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

public boolean setContent(JSONObject js) {
    try {//from   w  ww. ja  v  a  2 s.  com
        JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) {
            Log.w(TAG, "cannot set system folder");
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) {
            // for folder we can only update the snnipet and type
            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;
        } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) {
            JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA);
            long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID;
            if (mIsCreate || mId != id) {
                mDiffNoteValues.put(NoteColumns.ID, id);
            }
            mId = id;

            long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0;
            if (mIsCreate || mAlertDate != alertDate) {
                mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate);
            }
            mAlertDate = alertDate;

            int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID)
                    : ResourceParser.getDefaultBgId(mContext);
            if (mIsCreate || mBgColorId != bgColorId) {
                mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId);
            }
            mBgColorId = bgColorId;

            long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mCreatedDate != createDate) {
                mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate);
            }
            mCreatedDate = createDate;

            int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT)
                    : 0;
            if (mIsCreate || mHasAttachment != hasAttachment) {
                mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment);
            }
            mHasAttachment = hasAttachment;

            long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE)
                    : System.currentTimeMillis();
            if (mIsCreate || mModifiedDate != modifiedDate) {
                mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate);
            }
            mModifiedDate = modifiedDate;

            long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0;
            if (mIsCreate || mParentId != parentId) {
                mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId);
            }
            mParentId = parentId;

            String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : "";
            if (mIsCreate || !mSnippet.equals(snippet)) {
                mDiffNoteValues.put(NoteColumns.SNIPPET, snippet);
            }
            mSnippet = snippet;

            int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE;
            if (mIsCreate || mType != type) {
                mDiffNoteValues.put(NoteColumns.TYPE, type);
            }
            mType = type;

            int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID)
                    : AppWidgetManager.INVALID_APPWIDGET_ID;
            if (mIsCreate || mWidgetId != widgetId) {
                mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId);
            }
            mWidgetId = widgetId;

            int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE)
                    : Notes.TYPE_WIDGET_INVALIDE;
            if (mIsCreate || mWidgetType != widgetType) {
                mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType);
            }
            mWidgetType = widgetType;

            long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID)
                    ? note.getLong(NoteColumns.ORIGIN_PARENT_ID)
                    : 0;
            if (mIsCreate || mOriginParent != originParent) {
                mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent);
            }
            mOriginParent = originParent;

            for (int i = 0; i < dataArray.length(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                SqlData sqlData = null;
                if (data.has(DataColumns.ID)) {
                    long dataId = data.getLong(DataColumns.ID);
                    for (SqlData temp : mDataList) {
                        if (dataId == temp.getId()) {
                            sqlData = temp;
                        }
                    }
                }

                if (sqlData == null) {
                    sqlData = new SqlData(mContext);
                    mDataList.add(sqlData);
                }

                sqlData.setContent(data);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return false;
    }
    return true;
}

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

public void update(final Updater updater) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output,
            "Getting Switch status", false);

    task.addListener(new HttpUtils.DownloadListener() {
        @Override// w  ww  .  j ava 2 s .  com
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

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

                for (int i = 0; i < switchStatusArray.length(); ++i) {
                    JSONObject switchStatus = switchStatusArray.getJSONObject(i);
                    String status = switchStatus.getString("link");
                    int id = switchStatus.getInt("id");

                    if (status.equals("up")) {
                        JSONArray switchMacArray = switchStatus.getJSONArray("mac_list");
                        JSONObject switchMac = switchMacArray.getJSONObject(i);
                        String hostname = switchMac.getString("hostname");
                        addUsersForSwitchIdAndHostname(id, hostname);
                    }
                }
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch status", msg);
            }

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

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch status", ex.getMessage());

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

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

public void addUsersForSwitchIdAndHostname(int id, final String hostname) {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    String statement = Config.FREEBOX_API_SWITCH_ID.replace("{id}", String.valueOf(id));
    HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(statement, output, "Getting Switch information",
            false);// w  w w .  j  a  v  a  2  s. co  m

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onComplete() {
            String json = output.toString();
            JSONObject obj = new JSONObject(json);
            boolean success = obj.getBoolean("success");

            if (success == true) {
                JSONObject result = obj.getJSONObject("result");
                long txBytes = result.getLong("tx_bytes_rate");
                long rxBytes = result.getLong("rx_bytes_rate");

                addUser("", hostname, txBytes, rxBytes);
            } else {
                String msg = obj.getString("msg");
                Log.Debug("Freebox Switch information", msg);
            }

            setVisible(true);
        }
    });

    task.addListener(new HttpUtils.DownloadListener() {
        @Override
        public void onError(IOException ex) {
            Log.Debug("Freebox Switch information", ex.getMessage());
        }
    });
}

From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java

private List<DownloadItem> retrieveCategories() throws Exception {
    List<DownloadItem> diList = new LinkedList<DownloadItem>();
    JSONArray jsonArray = new JSONArray(downloadJSONString(SS_API_GET_CATEGORIES));
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject jsonItem = jsonArray.getJSONObject(i);
        DownloadItem di = new DownloadItem();
        di.setType(DownloadItem.TYPE_CATEGORY);
        di.setTitle(jsonItem.getString("name"));
        di.setExtras("id", jsonItem.getString("id"));
        di.setExtras("pid", jsonItem.getString("parentId"));
        di.setExtras("page", "1");

        if (di.getTitle() != null) {
            diList.add(di);//  w  w w.  jav  a 2 s.  c o  m
        }
    }
    return diList;
}