Example usage for org.json JSONObject getLong

List of usage examples for org.json JSONObject getLong

Introduction

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

Prototype

public long getLong(String key) throws JSONException 

Source Link

Document

Get the long value associated with a key.

Usage

From source file:bean.Atividade.java

public void loadJSON(JSONObject atividadeJSON) {

    if (atividadeJSON.has("id")) {
        setId(atividadeJSON.getInt("id"));
    }/*from w ww  .  j  a v a2 s.c o  m*/

    if (atividadeJSON.has("name")) {
        setNome(atividadeJSON.getString("name"));
    }

    if (atividadeJSON.has("start")) {
        setInicio(atividadeJSON.getLong("start"));
    }

    if (atividadeJSON.has("end")) {
        setFim(atividadeJSON.getLong("end"));
    }

    if (atividadeJSON.has("duration")) {
        setDuracao(atividadeJSON.getInt("duration"));
    }

    if (atividadeJSON.has("description")) {
        setDescricao(atividadeJSON.getString("description"));
    }

    if (atividadeJSON.has("progress")) {
        setProgresso(atividadeJSON.getInt("progress"));
    }

    if (atividadeJSON.has("status")) {
        setStatus(atividadeJSON.getString("status"));
    }

}

From source file:at.alladin.rmbt.android.util.CheckNewsTask.java

@Override
protected void onPostExecute(final JSONArray newsList) {

    if (newsList != null && newsList.length() > 0 && !serverConn.hasError())
        for (int i = 0; i < newsList.length(); i++)
            if (!isCancelled() && !Thread.interrupted())
                try {

                    final JSONObject newsItem = newsList.getJSONObject(i);

                    final DialogFragment newFragment = RMBTAlertDialogFragment.newInstance(
                            newsItem.optString("title", activity.getString(R.string.news_title)),
                            newsItem.optString("text", activity.getString(R.string.news_no_message)), null);

                    newFragment.show(activity.getFragmentManager(), "dialog");

                    if (newsItem.has("uid")) {
                        if (lastNewsUid < newsItem.getLong("uid"))
                            lastNewsUid = newsItem.getLong("uid");
                    }/*  w  w w.j  a v  a  2 s  .  co m*/
                } catch (final JSONException e) {
                    e.printStackTrace();
                }

    ConfigHelper.setLastNewsUid(activity.getApplicationContext(), lastNewsUid);
}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

/**
 * Access the API from a URL and process its data.
 * If any values have changed, the appropriate callbacks in
 * {@link com.google.android.apps.santatracker.service.APIProcessor.APICallback} are called.
 * Returns {@link #ERROR_CODE} if the data could not be loaded or processed.
 * Returns the delay to the next API access if the access was successful.
 *//*from  www . j a  v a2 s .com*/
public long accessAPI(String url) {
    SantaLog.d(TAG, "URL=" + url);
    // Get current values from mPreferences
    long offsetPref = mPreferences.getOffset();
    String fingerprintPref = mPreferences.getFingerprint();
    boolean switchOffPref = mPreferences.getSwitchOff();

    // load data as JSON
    JSONObject json = loadApi(url);

    if (json == null) {
        Log.d(TAG, "Santa Communication Error 3");
        return ERROR_CODE;
    }

    try {
        // Error if the status is not OK
        if (!FIELD_STATUS_OK.equals(json.getString(FIELD_STATUS))) {
            Log.d(TAG, "Santa Communication Error 4");
            return ERROR_CODE;
        }

        final int routeOffset = json.getInt(FIELD_ROUTEOFFSET);
        final long now = json.getLong(FIELD_NOW);
        final long offset = json.getLong(FIELD_TIMEOFFSET);
        final String fingerprint = json.getString(FIELD_FINGERPRINT);
        final long refresh = json.getLong(FIELD_REFRESH);
        final boolean switchOff = json.getBoolean(FIELD_SWITCHOFF);
        final JSONArray locations = json.getJSONArray(FIELD_DESTINATIONS);

        final int streamOffset = json.getInt(FIELD_STREAMOFFSET);
        final JSONArray stream = json.getJSONArray(FIELD_STREAM);

        // Notification stream parameters are optional
        final JSONArray notificationStream = json.has(FIELD_NOTIFICATIONSTREAM)
                ? json.getJSONArray(FIELD_NOTIFICATIONSTREAM)
                : null;

        // Fingerprint has changed, remove route and stream from db
        if (!fingerprint.equals(fingerprintPref)) {
            mCallback.notifyRouteUpdating();
            //empty the database and reset preferences
            mDestinationDBHelper.emptyDestinationTable();
            mStreamDBHelper.emptyCardTable();
            mPreferences.invalidateData();
        }

        // Destinations
        if (locations != null && locations.length() > 0) {
            int processedLocations = processRoute(locations);
            if (processedLocations > 0) {
                final int newOffset = routeOffset + processedLocations;
                mCallback.onNewRouteLoaded();
                mPreferences.setFingerprint(fingerprint);
                mPreferences.setRouteOffset(newOffset);
                SantaLog.d(TAG, "Processed route - new details: " + newOffset + ", " + fingerprint);
            }
        }

        // Stream
        if (stream != null && stream.length() > 0) {
            // process non-notification cards
            int processedCards = processStream(stream, false);
            if (processedCards > 0) {
                final int newOffset = streamOffset + processedCards;
                mCallback.onNewStreamLoaded();
                mPreferences.setStreamOffset(newOffset);
                SantaLog.d(TAG, "Processed stream - new details: " + newOffset);
            }
        }

        // Notification Stream
        if (notificationStream != null && notificationStream.length() > 0) {
            // process notification cards
            int processedCards = processStream(notificationStream, true);
            if (processedCards > 0) {
                mCallback.onNewNotificationStreamLoaded();
                SantaLog.d(TAG, "Processed notification stream - count: " + processedCards);
            }
        }

        // Offset
        final long newOffset = now - System.currentTimeMillis() + offset;
        if (offsetPref != newOffset) {
            mPreferences.setOffset(newOffset);

            SantaLog.d(TAG, "New offset: " + newOffset + ", current=" + System.currentTimeMillis()
                    + ", new Santa=" + SantaPreferences.getCurrentTime());

            // Log.d(TAG, "new offset: new="+newOffset+", now="+now+", offset="+offset+",
            // prefOffset="+offsetPref+", time="+System.currentTimeMillis());
            // Notify only if offset varies significantly
            if ((newOffset > offsetPref + SantaPreferences.OFFSET_ACCEPTABLE_RANGE_DIFFERENCE
                    || newOffset < offsetPref - SantaPreferences.OFFSET_ACCEPTABLE_RANGE_DIFFERENCE)) {
                mCallback.onNewOffset();
            }

        }

        if (switchOffPref != switchOff) {
            mPreferences.setSwitchOff(switchOff);
            mCallback.onNewSwitchOffState(switchOff);

        }

        // Check Switches for Changes
        checkSwitchesDiff(getSwitches());

        if (!fingerprint.equals(fingerprintPref)) {
            // new data has been processed and locations have been stored
            mCallback.onNewFingerprint();
        }

        return refresh;
    } catch (JSONException e) {
        Log.d(TAG, "Santa Communication Error 5");
        SantaLog.d(TAG, "JSON Exception", e);
        return ERROR_CODE;
    }

}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

private int processRoute(JSONArray json) {
    SQLiteDatabase db = mDestinationDBHelper.getWritableDatabase();

    db.beginTransaction();//w  ww .  ja  va 2  s  . c om
    try {
        // loop over each destination
        long previousPresents = mPreferences.getTotalPresents();

        int i;
        for (i = 0; i < json.length(); i++) {
            JSONObject dest = json.getJSONObject(i);

            JSONObject location = dest.getJSONObject(FIELD_DETAILS_LOCATION);

            long presentsTotal = dest.getLong(FIELD_DETAILS_PRESENTSDELIVERED);
            long presents = presentsTotal - previousPresents;
            previousPresents = presentsTotal;

            // Name
            String city = dest.getString(FIELD_DETAILS_CITY);
            String region = null;
            String country = null;

            if (dest.has(FIELD_DETAILS_REGION)) {
                region = dest.getString(FIELD_DETAILS_REGION);
                if (region.length() < 1) {
                    region = null;
                }
            }
            if (dest.has(FIELD_DETAILS_COUNTRY)) {
                country = dest.getString(FIELD_DETAILS_COUNTRY);
                if (country.length() < 1) {
                    country = null;
                }
            }

            //                if (mDebugLog) {
            //                    Log.d(TAG, "Location: " + city);
            //                }

            // Detail fields
            JSONObject details = dest.getJSONObject(FIELD_DETAILS_DETAILS);
            long timezone = details.isNull(FIELD_DETAILS_TIMEZONE) ? 0L
                    : details.getLong(FIELD_DETAILS_TIMEZONE);
            long altitude = details.getLong(FIELD_DETAILS_ALTITUDE);
            String photos = details.has(FIELD_DETAILS_PHOTOS) ? details.getString(FIELD_DETAILS_PHOTOS)
                    : EMPTY_STRING;
            String weather = details.has(FIELD_DETAILS_WEATHER) ? details.getString(FIELD_DETAILS_WEATHER)
                    : EMPTY_STRING;
            String streetview = details.has(FIELD_DETAILS_STREETVIEW)
                    ? details.getString(FIELD_DETAILS_STREETVIEW)
                    : EMPTY_STRING;
            String gmmStreetview = details.has(FIELD_DETAILS_GMMSTREETVIEW)
                    ? details.getString(FIELD_DETAILS_GMMSTREETVIEW)
                    : EMPTY_STRING;

            try {
                // All parsed, insert into DB
                mDestinationDBHelper.insertDestination(db, dest.getString(FIELD_IDENTIFIER),
                        dest.getLong(FIELD_ARRIVAL), dest.getLong(FIELD_DEPARTURE),

                        city, region, country,

                        location.getDouble(FIELD_DETAILS_LOCATION_LAT),
                        location.getDouble(FIELD_DETAILS_LOCATION_LNG), presentsTotal, presents, timezone,
                        altitude, photos, weather, streetview, gmmStreetview);
            } catch (android.database.sqlite.SQLiteConstraintException e) {
                // ignore duplicate locations
            }
        }

        db.setTransactionSuccessful();
        // Update mPreferences
        mPreferences.setDBTimestamp(System.currentTimeMillis());
        mPreferences.setTotalPresents(previousPresents);
        return i;
    } catch (JSONException e) {
        Log.d(TAG, "Santa location tracking error 30");
        SantaLog.d(TAG, "JSON Exception", e);
    } finally {
        db.endTransaction();
    }

    return 0;
}

From source file:com.google.android.apps.santatracker.service.APIProcessor.java

private int processStream(JSONArray json, boolean isWear) {
    SQLiteDatabase db = mStreamDBHelper.getWritableDatabase();

    db.beginTransaction();/* w  w w. j  a  va2  s. c om*/
    try {
        // loop over each card

        int i;
        for (i = 0; i < json.length(); i++) {
            JSONObject card = json.getJSONObject(i);

            final long timestamp = card.getLong(FIELD_STREAM_TIMESTAMP);
            final String status = getExistingJSONString(card, FIELD_STREAM_STATUS);
            final String didYouKnow = getExistingJSONString(card, FIELD_STREAM_DIDYOUKNOW);
            final String imageUrl = getExistingJSONString(card, FIELD_STREAM_IMAGEURL);
            final String youtubeId = getExistingJSONString(card, FIELD_STREAM_YOUTUBEID);

            //                if (mDebugLog) {
            //                    Log.d(TAG, "Notification: " + timestamp);
            //                }

            try {
                // All parsed, insert into DB
                mStreamDBHelper.insert(db, timestamp, status, didYouKnow, imageUrl, youtubeId, isWear);
            } catch (android.database.sqlite.SQLiteConstraintException e) {
                // ignore duplicate cards
            }
        }

        db.setTransactionSuccessful();
        return i;
    } catch (JSONException e) {
        Log.d(TAG, "Santa location tracking error 31");
        SantaLog.d(TAG, "JSON Exception", e);
    } finally {
        db.endTransaction();
    }

    return 0;
}

From source file:ui.panel.UILicenseDetail.java

public void getLicenseData() {
    ArrayList<String> arrayLicenses = new ArrayList<String>();
    JSONArray licenseList = new APIProcess().nodeLicenseList(Data.targetURL, Data.sessionKey, Data.bucketID);
    try {//  ww w  . j  a  v  a  2 s.  co  m
        String[] columnNames = { "License Number", "Validity", "Storage", "Date Created", "Maximum VCA",
                "Bucket Name" };
        Object[][] rowData = new Object[licenseList.length()][columnNames.length];

        for (int i = 0; i < licenseList.length(); i++) {
            JSONObject license = licenseList.getJSONObject(i);

            String licenseNumber = license.getString("licenseNumber");
            char[] charArray = licenseNumber.toCharArray();
            String licenseAdd = "";
            for (int x = 0; x < charArray.length; x++) {
                if (x % 5 == 0 && x != 0) {
                    licenseAdd += " - " + charArray[x];
                } else {
                    licenseAdd += charArray[x];
                }
            }
            JSONObject response = api.getNodeLicenseDetails(Data.targetURL, Data.sessionKey, Data.bucketID,
                    licenseAdd);
            rowData[i][0] = licenseAdd;
            if (response.getInt("duration") == -1) {
                rowData[i][1] = "Perpetual";
            } else {
                rowData[i][1] = response.getInt("duration");
            }
            rowData[i][2] = response.getInt("cloudStorage");
            rowData[i][3] = simpleDate.format(response.getLong("created"));
            rowData[i][4] = response.getInt("maxVCA");
            rowData[i][5] = response.getString("bucketName");
            arrayLicenses.add(licenseAdd);
        }
        tblInfo.setModel(new UneditableModel(rowData, columnNames));
        arrayLicense = arrayLicenses.toArray(arrayLicense);

    } catch (JSONException e1) {
        e1.printStackTrace();
    }
}

From source file:com.xorcode.andtweet.FriendTimeline.java

/**
 * Load Timeline (Friends / Messages) from the Internet
 * and store them in the local database.
 * //from  w w w  .  ja v a  2 s  .  co m
 * @throws ConnectionException
 */
public boolean loadTimeline() throws ConnectionException {
    boolean ok = false;
    mNewTweets = 0;
    mReplies = 0;
    long lastId = mLastStatusId;
    int limit = 200;
    if (mTu.getCredentialsVerified() == CredentialsVerified.SUCCEEDED) {
        JSONArray jArr = null;
        switch (mTimelineType) {
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_FRIENDS:
            jArr = mTu.getConnection().getFriendsTimeline(lastId, limit);
            break;
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_MENTIONS:
            jArr = mTu.getConnection().getMentionsTimeline(lastId, limit);
            break;
        case AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES:
            jArr = mTu.getConnection().getDirectMessages(lastId, limit);
            break;
        default:
            Log.e(TAG, "Got unhandled tweet type: " + mTimelineType);
            break;
        }
        if (jArr != null) {
            ok = true;
            try {
                for (int index = 0; index < jArr.length(); index++) {
                    JSONObject jo = jArr.getJSONObject(index);
                    long lId = jo.getLong("id");
                    if (lId > lastId) {
                        lastId = lId;
                    }
                    insertFromJSONObject(jo);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        if (mNewTweets > 0) {
            mContentResolver.notifyChange(mContentUri, null);
        }
        if (lastId > mLastStatusId) {
            mLastStatusId = lastId;
            mTu.getSharedPreferences().edit().putLong("last_timeline_id" + mTimelineType, mLastStatusId)
                    .commit();
        }
    }
    return ok;
}

From source file:de.liedtke.format.JSONFormatter.java

@Override
public <T extends BasicEntity> T reformat(final String object, final Class<T> entityClass)
        throws FormatException {
    T result = null;//  w ww.j av  a 2 s.c o m
    final Map<String, Field> fieldMap = new HashMap<String, Field>();
    if (entityClass.isAnnotationPresent(Entity.class)) {
        final Field[] fields = entityClass.getDeclaredFields();
        for (final Field field : fields) {
            if (field.isAnnotationPresent(FormatPart.class)) {
                fieldMap.put(field.getAnnotation(FormatPart.class).key(), field);
            }
        }
        try {
            final JSONObject json = new JSONObject(object);
            result = entityClass.newInstance();
            for (final String key : fieldMap.keySet()) {
                if (json.has(key)) {
                    final Field field = fieldMap.get(key);
                    final Method method = entityClass.getMethod(this.getSetter(field.getName()),
                            new Class<?>[] { field.getType() });
                    if (FindInterface.class.isAssignableFrom(field.getType())) {
                        final Method find = field.getType().getMethod("find", new Class<?>[] { String.class });
                        if (find != null) {
                            final Object enumObject = find.invoke(Enum.class, json.get(key));
                            method.invoke(result, enumObject);
                        }
                    } else {
                        final String type = field.getType().toString();
                        if (type.equals("class com.google.appengine.api.datastore.Key")) {
                            method.invoke(result, KeyFactory.stringToKey(json.getString(key)));
                        } else if (type.equals("class com.google.appengine.api.datastore.Text")) {
                            method.invoke(result, new Text(json.getString(key)));
                        } else if (type.equals("boolean")) {
                            method.invoke(result, json.getBoolean(key));
                        } else if (type.equals("long")) {
                            method.invoke(result, json.getLong(key));
                        } else if (type.equals("int")) {
                            method.invoke(result, json.getInt(key));
                        } else {
                            method.invoke(result, json.get(key));
                        }
                    }
                }
            }
        } catch (JSONException e) {
            logger.warning("JSONException occured: " + e.getMessage());
            throw new FormatException();
        } catch (NoSuchMethodException e) {
            logger.warning("NoSuchMethodException occured: " + e.getMessage());
            throw new FormatException();
        } catch (SecurityException e) {
            logger.warning("SecurityException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalAccessException e) {
            logger.warning("IllegalAccessException occured: " + e.getMessage());
            throw new FormatException();
        } catch (IllegalArgumentException e) {
            logger.warning("IllegalArgumentException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InvocationTargetException e) {
            logger.warning("InvocationTargetException occured: " + e.getMessage());
            throw new FormatException();
        } catch (InstantiationException e) {
            logger.warning("InstantiationException occured: " + e.getMessage());
            throw new FormatException();
        }
    }
    return result;
}

From source file:fr.pasteque.client.sync.SyncUpdate.java

private void parseTaxes(JSONObject resp) {
    try {//from www .j  a  va 2 s .co m
        JSONArray array = resp.getJSONArray("content");
        for (int i = 0; i < array.length(); i++) {
            JSONObject taxCat = array.getJSONObject(i);
            String taxCatId = taxCat.getString("id");
            JSONArray taxes = taxCat.getJSONArray("taxes");
            long now = System.currentTimeMillis() / 1000;
            int index = 0;
            long maxDate = 0;
            for (int j = 0; j < taxes.length(); j++) {
                JSONObject tax = taxes.getJSONObject(j);
                long date = tax.getLong("startDate");
                if (date > maxDate && date < now) {
                    index = j;
                    maxDate = date;
                }
            }
            JSONObject currentTax = taxes.getJSONObject(index);
            double rate = currentTax.getDouble("rate");
            String id = currentTax.getString("id");
            this.taxRates.put(taxCatId, rate);
            this.taxIds.put(taxCatId, id);
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, "Unable to parse response: " + resp.toString(), e);
        SyncUtils.notifyListener(this.listener, TAXES_SYNC_ERROR, e);
        this.taxesDone = true;
        this.productsDone = true;
        this.compositionsDone = true;
        return;
    }
    SyncUtils.notifyListener(this.listener, TAXES_SYNC_DONE, this.taxRates);
    // Start synchronizing catalog
    URLTextGetter.getText(SyncUtils.apiUrl(this.ctx), SyncUtils.initParams(this.ctx, "CategoriesAPI", "getAll"),
            new DataHandler(DataHandler.TYPE_CATEGORY));
}

From source file:de.luhmer.owncloudnewsreader.reader.owncloud.InsertItemIntoDatabase.java

private static RssItem parseItem(JSONObject e) throws JSONException {
    Date pubDate = new Date(e.optLong("pubDate") * 1000);

    String content = e.optString("body");
    content = content.replaceAll("<img[^>]*feedsportal.com.*>", "");
    content = content.replaceAll("<img[^>]*statisches.auslieferung.commindo-media-ressourcen.de.*>", "");
    content = content.replaceAll("<img[^>]*auslieferung.commindo-media-ressourcen.de.*>", "");
    content = content.replaceAll("<img[^>]*rss.buysellads.com.*>", "");

    String url = e.optString("url");
    String guid = e.optString("guid");
    String enclosureLink = e.optString("enclosureLink");
    String enclosureMime = e.optString("enclosureMime");

    if (enclosureLink.trim().equals("") && guid.startsWith("http://gdata.youtube.com/feeds/api/")) {
        enclosureLink = url;/*w ww  .j a va  2  s.co  m*/
        enclosureMime = "youtube";
    }

    RssItem rssItem = new RssItem();
    rssItem.setId(e.getLong("id"));
    rssItem.setFeedId(e.optLong("feedId"));
    rssItem.setLink(url);
    rssItem.setTitle(e.optString("title"));
    rssItem.setGuid(guid);
    rssItem.setGuidHash(e.optString("guidHash"));
    rssItem.setBody(content);
    rssItem.setAuthor(e.optString("author"));
    rssItem.setLastModified(new Date(e.optLong("lastModified")));
    rssItem.setEnclosureLink(enclosureLink);
    rssItem.setEnclosureMime(enclosureMime);
    rssItem.setRead(!e.optBoolean("unread"));
    rssItem.setRead_temp(rssItem.getRead());
    rssItem.setStarred(e.optBoolean("starred"));
    rssItem.setStarred_temp(rssItem.getStarred());
    rssItem.setPubDate(pubDate);

    return rssItem;
    /*
    new RssItem(0, e.optString("id"),
                        e.optString("title"),
                        url, content,
                        !e.optBoolean("unread"), null,
                        e.optString("feedId"), null,
                        date, e.optBoolean("starred"),
                        guid,
                        e.optString("guidHash"),
                        e.optString("lastModified"),
                        e.optString("author"),
                        enclosureLink,
                        enclosureMime);
                        */
}