Example usage for org.json JSONObject optLong

List of usage examples for org.json JSONObject optLong

Introduction

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

Prototype

public long optLong(String key, long defaultValue) 

Source Link

Document

Get an optional long value associated with a key, or the default if there is no such key or if the value is not a number.

Usage

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

protected boolean scheduleSingleNotification(AlarmManager am, JSONObject obj) {
    PendingIntent pendingIntent = createPendingIntentForSchedule(obj.optString("id"));
    long time = obj.optLong("timeMillisSince1970", -1);
    if (time < 0) {
        return false;
    }/*from w w w.  j a v  a 2s.c  om*/
    am.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
    return true;
}

From source file:com.futureplatforms.kirin.extensions.localnotifications.LocalNotificationsBackend.java

public void rescheduleAllNotifications() {
    long now = System.currentTimeMillis();
    Map<String, ?> map = mPrefs.getAll();
    int count = 0;
    AlarmManager am = (AlarmManager) mContext.getSystemService(Service.ALARM_SERVICE);
    for (Map.Entry<String, ?> entry : map.entrySet()) {
        if (entry.getKey().startsWith(PREFS_PREFIX)) {
            JSONObject obj = null;
            String json = entry.getValue().toString();
            try {
                obj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e(C.TAG, "Error rescheduling notification: " + json);
                continue;
            }//www.  jav  a2  s .c  o m

            long scheduledTime = obj.optLong("timeMillisSince1970", -1);
            long epsilon = obj.optLong("epsilon", -1);
            if (epsilon >= 0 && scheduledTime >= -1) {
                if (now - epsilon > scheduledTime) {
                    // e.g. epsilon is two hours
                    // if the scheduled event happened three hours ago, the
                    // don't bother
                    // notifying.
                    continue;
                }
            }
            count++;
            scheduleSingleNotification(am, obj);
        }
    }
    Log.i(C.TAG, "Rescheduled " + count + " alarms for notifications");
}

From source file:com.rathravane.drumlin.examples.accounts.exampleAcctPersistence.java

private long readIndex(String indexName, String keyName) throws DrumlinAccountsException {
    try {//ww w. ja  v  a 2s .  com
        final JSONObject o = fIndex.getJSONObject(indexName);
        return o.optLong(keyName, -1);
    } catch (JSONException e) {
        throw new DrumlinAccountsException(e);
    }
}

From source file:net.netheos.pcsapi.credentials.OAuth2Credentials.java

/**
 * Calculate expiration timestamp, if not defined.
 * //w  ww .  j a  v  a  2  s  .  c o m
 * Several cases: absolute expiration time exists in json, or only relative, or no expiration.
 * 
 * @param jsonObj
 * @return expiration date, or null if none.
 */
private static Date calculateExpiresAt(JSONObject jsonObj) {
    long expiresAt_s = jsonObj.optLong(OAuth2Credentials.EXPIRES_AT, -1);
    // If nothing specified in json, check if expires_in is present:
    // this happens when token is received from oauth server
    if (expiresAt_s < 0 && jsonObj.has(OAuth2Credentials.EXPIRES_IN)) {
        long expiresIn_s = jsonObj.getLong(OAuth2Credentials.EXPIRES_IN);
        // We take a margin to be safe: it appears that some providers do NOT take any margin
        // so token will not be early refreshed
        if (expiresIn_s > 6 * 60) { // should be always true
            expiresIn_s -= 5 * 60; // 5 minutes to be safe
        }
        expiresAt_s = System.currentTimeMillis() / 1000 + expiresIn_s;
    }

    if (expiresAt_s < 0) {
        return null;
    }
    return new Date(expiresAt_s * 1000);
}

From source file:ru.orangesoftware.financisto2.rates.OpenExchangeRatesDownloader.java

private void updateRate(JSONObject json, ExchangeRate exchangeRate, Currency fromCurrency, Currency toCurrency)
        throws JSONException {
    JSONObject rates = json.getJSONObject("rates");
    double usdFrom = rates.getDouble(fromCurrency.name);
    double usdTo = rates.getDouble(toCurrency.name);
    exchangeRate.rate = usdTo * (1 / usdFrom);
    exchangeRate.date = 1000 * json.optLong("timestamp", System.currentTimeMillis());
}

From source file:at.alladin.rmbt.android.main.RMBTMainActivity.java

/**
 * //from   w  w  w .  j a v a  2 s. c o  m
 * @param callback
 */
public void updateHistory(final HistoryUpdatedCallback callback) {
    if (historyDirty && (historyTask == null || historyTask.isCancelled()
            || historyTask.getStatus() == AsyncTask.Status.FINISHED)) {
        historyTask = new CheckHistoryTask(this, historyFilterDevicesFilter, historyFilterNetworksFilter);

        historyTask.setEndTaskListener(new EndTaskListener() {
            @Override
            public void taskEnded(final JSONArray resultList) {
                if (resultList != null && resultList.length() > 0 && !historyTask.hasError()) {
                    historyStorageList.clear();
                    historyItemList.clear();

                    final Date tmpDate = new Date();
                    final DateFormat dateFormat = Helperfunctions.getDateFormat(false);

                    for (int i = 0; i < resultList.length(); i++) {

                        JSONObject resultListItem;
                        try {
                            resultListItem = resultList.getJSONObject(i);

                            final HashMap<String, String> storageItem = new HashMap<String, String>();
                            storageItem.put("test_uuid", resultListItem.optString("test_uuid", null));
                            storageItem.put("time", String.valueOf(resultListItem.optLong("time", 0)));
                            storageItem.put("timezone", resultListItem.optString("timezone", null));
                            historyStorageList.add(storageItem);

                            final HashMap<String, String> viewItem = new HashMap<String, String>();
                            // viewIitem.put( "device",
                            // resultListItem.optString("plattform","none"));
                            viewItem.put("device", resultListItem.optString("model", "-"));

                            viewItem.put("type", resultListItem.optString("network_type"));

                            final String timeString = Helperfunctions.formatTimestampWithTimezone(tmpDate,
                                    dateFormat, resultListItem.optLong("time", 0),
                                    resultListItem.optString("timezone", null));

                            viewItem.put("date", timeString == null ? "-" : timeString);

                            viewItem.put("down", resultListItem.optString("speed_download", "-"));
                            viewItem.put("up", resultListItem.optString("speed_upload", "-"));
                            viewItem.put("ping", resultListItem.optString("ping", "-"));
                            historyItemList.add(viewItem);
                        } catch (final JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    historyDirty = false;
                    if (callback != null)
                        callback.historyUpdated(HistoryUpdatedCallback.SUCCESSFUL);
                } else if (callback != null) {
                    callback.historyUpdated(historyTask.hasError() ? HistoryUpdatedCallback.ERROR
                            : HistoryUpdatedCallback.LIST_EMPTY);
                }
            }
        });
        historyTask.execute();
    } else if (callback != null)
        callback.historyUpdated(!(historyStorageList.isEmpty() && historyStorageList.isEmpty())
                ? HistoryUpdatedCallback.SUCCESSFUL
                : HistoryUpdatedCallback.LIST_EMPTY);
}

From source file:com.vk.sdkweb.api.model.ParseUtils.java

/**
 * Parse long from JSONObject with given name.
 *
 * @param from server response like this format: {@code field: 34}
 * @param name name of field to read// ww  w .j  a v  a  2 s  . c  o  m
 */
public static long parseLong(JSONObject from, String name) {
    if (from == null)
        return 0;
    return from.optLong(name, 0);
}

From source file:org.apache.cordova.mediacapture.Capture.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    this.callbackContext = callbackContext;
    this.limit = 1;
    this.duration = 0;
    this.results = new JSONArray();

    JSONObject options = args.optJSONObject(0);
    if (options != null) {
        limit = options.optLong("limit", 1);
        duration = options.optInt("duration", 0);
    }/*from   w  ww .  j a  v  a 2  s.  co m*/

    if (action.equals("getFormatData")) {
        JSONObject obj = getFormatData(args.getString(0), args.getString(1));
        callbackContext.success(obj);
        return true;
    } else if (action.equals("captureAudio")) {
        this.captureAudio();
    } else if (action.equals("captureImage")) {
        this.captureImage();
    } else if (action.equals("captureVideo")) {
        this.captureVideo(duration);
    } else {
        return false;
    }

    return true;
}