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:com.sencha.plugins.calendar.Calendar.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    try {/*from w ww  .j  a  va 2  s .c om*/
        if (ACTION_ADD_CALENDAR_ENTRY.equals(action)) {
            JSONObject arg_object = args.getJSONObject(0);
            Intent calIntent = new Intent(Intent.ACTION_EDIT).setType("vnd.android.cursor.item/event")
                    .putExtra("beginTime", arg_object.getLong("startTimeMillis"))
                    .putExtra("endTime", arg_object.getLong("endTimeMillis"))
                    .putExtra("title", arg_object.getString("title"))
                    .putExtra("description", arg_object.getString("description"))
                    .putExtra("eventLocation", arg_object.getString("eventLocation"));

            this.cordova.getActivity().startActivity(calIntent);
            callbackContext.success();
            return true;
        }
        callbackContext.error("Invalid action");
        return false;
    } catch (Exception e) {
        System.err.println("Exception: " + e.getMessage());
        callbackContext.error(e.getMessage());
        return false;
    }
}

From source file:org.anhonesteffort.flock.SubscriptionGoogleFragment.java

private void handleRefreshDaysTillCharge() {
    if (recurringTask != null)
        return;/*from   w w  w.ja v  a  2 s  .  com*/

    recurringTask = new AsyncTask<Void, Void, Bundle>() {

        @Override
        protected void onPreExecute() {
            Log.d(TAG, "handleRefreshDaysTillCharge");
            subscriptionActivity.setProgressBarIndeterminateVisibility(true);
            subscriptionActivity.setProgressBarVisibility(true);
        }

        @Override
        protected Bundle doInBackground(Void... params) {
            Bundle result = new Bundle();

            if (subscriptionActivity.billingService == null) {
                Log.e(TAG, "billing service is null");
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
                return result;
            }

            try {

                Bundle ownedItems = subscriptionActivity.billingService.getPurchases(3,
                        SubscriptionGoogleFragment.class.getPackage().getName(), PRODUCT_TYPE_SUBSCRIPTION,
                        null);

                ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");

                for (int i = 0; i < purchaseDataList.size(); ++i) {
                    JSONObject productObject = new JSONObject(purchaseDataList.get(i));
                    if (productObject.getString("productId").equals(SKU_YEARLY_SUBSCRIPTION)) {
                        long purchaseTime = productObject.getLong("purchaseTime");
                        long msSincePurchase = new Date().getTime() - purchaseTime;
                        if (msSincePurchase < 0)
                            msSincePurchase = 0;

                        daysTillNextCharge = 365 - (msSincePurchase / 1000 / 60 / 60 / 24);
                        if (daysTillNextCharge < 0)
                            daysTillNextCharge = 0;
                    }
                }

                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_SUCCESS);

            } catch (RemoteException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            } catch (JSONException e) {
                Log.e(TAG, "error while getting owned items", e);
                result.putInt(ErrorToaster.KEY_STATUS_CODE, ErrorToaster.CODE_GOOGLE_PLAY_ERROR);
            }

            return result;
        }

        @Override
        protected void onPostExecute(Bundle result) {
            recurringTask = null;
            subscriptionActivity.setProgressBarIndeterminateVisibility(false);
            subscriptionActivity.setProgressBarVisibility(false);

            if (result.getInt(ErrorToaster.KEY_STATUS_CODE) == ErrorToaster.CODE_SUCCESS)
                handleUpdateUi();
            else
                ErrorToaster.handleDisplayToastBundledError(subscriptionActivity, result);
        }
    }.execute();
}

From source file:com.github.akinaru.hcidebugger.activity.HciDebuggerActivity.java

/**
 * callback called from native function when a HCI pakcet has been decoded
 *
 * @param snoopFrame snoop frame part//from www.ja v a  2s.  com
 * @param hciFrame   HCI packet part
 */
@Override
public void onHciFrameReceived(final String snoopFrame, final String hciFrame) {

    if (mFirstPacketReceived) {
        mFirstPacketReceived = false;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //display recyclerview + swipe refresh view
                mWaitingFrame.setVisibility(View.GONE);
                mDisplayFrame.setVisibility(View.VISIBLE);
            }
        });
    }
    if (!mAllPacketInit && ((frameCount >= mPacketCount) || (frameCount >= mMaxPacketCount))) {
        mAllPacketInit = true;
    }
    if (mAllPacketInit)
        mPacketCount++;

    try {
        JSONObject snoopJson = new JSONObject(snoopFrame);

        final Date timestamp = new Date(snoopJson.getLong("timestamp_microseconds") / 1000);

        PacketDest dest = PacketDest.PACKET_SENT;

        if (snoopJson.getBoolean("packet_received")) {
            dest = PacketDest.PACKET_RECEIVED;
        }

        JSONObject hciJson = new JSONObject(hciFrame);

        JSONObject packet_type = hciJson.getJSONObject("packet_type");
        final ValuePair type = new ValuePair(packet_type.getInt("code"), packet_type.getString("value"));

        JSONObject parameters = null;

        if (hciJson.has("parameters"))
            parameters = hciJson.getJSONObject("parameters");

        final PacketDest finalDest = dest;

        if (type.getCode() == 4) {

            JSONObject event_code = hciJson.getJSONObject("event_code");
            final ValuePair eventType = new ValuePair(event_code.getInt("code"), event_code.getString("value"));

            if (hciJson.has("subevent_code")) {

                JSONObject subevent_code = hciJson.getJSONObject("subevent_code");
                final ValuePair subevent_code_val = new ValuePair(subevent_code.getInt("code"),
                        subevent_code.getString("value"));

                if (subevent_code_val.getCode() == 2) {

                    if (parameters != null && parameters.has("reports")) {

                        JSONArray reports = parameters.getJSONArray("reports");

                        final List<AdvertizingReport> reportList = new ArrayList<>();

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

                            JSONObject reportItem = reports.getJSONObject(i);
                            reportList.add(new AdvertizingReport(reportItem.getString("address"),
                                    reportItem.getInt("address_type"), reportItem.getJSONArray("data"),
                                    reportItem.getInt("data_length"), reportItem.getInt("event_type"),
                                    reportItem.getInt("rssi")));
                        }
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {

                                Packet packet = new PacketHciLEAdvertizing(frameCount++, timestamp, finalDest,
                                        type, eventType, subevent_code_val, reportList, hciFrame, snoopFrame);

                                packetList.add(0, packet);

                                if (isFiltered && matchFilter(packet))
                                    packetFilteredList.add(0, packet);

                                notifyAdapter();
                            }
                        });

                        return;
                    }
                }
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Packet packet = new PacketHciEvent(frameCount++, timestamp, finalDest, type, eventType,
                            hciFrame, snoopFrame);

                    packetList.add(0, packet);

                    if (isFiltered && matchFilter(packet))
                        packetFilteredList.add(0, packet);

                    notifyAdapter();
                }
            });

        } else if (type.getCode() == 1) {

            JSONObject ogf_obj = hciJson.getJSONObject("ogf");
            final ValuePair ogf = new ValuePair(ogf_obj.getInt("code"), ogf_obj.getString("value"));

            final ValuePair ocf;

            if (hciJson.has("ocf")) {
                JSONObject ocf_obj = hciJson.getJSONObject("ocf");
                ocf = new ValuePair(ocf_obj.getInt("code"), ocf_obj.getString("value"));
            } else {
                ocf = new ValuePair(-1, "");
            }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Packet packet = new PacketHciCmd(frameCount++, timestamp, finalDest, type, ocf, ogf,
                            hciFrame, snoopFrame);

                    packetList.add(0, packet);

                    if (isFiltered && matchFilter(packet))
                        packetFilteredList.add(0, packet);

                    notifyAdapter();
                }
            });
        } else if (type.getCode() == 2) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Packet packet = new PacketHciAclData(frameCount++, timestamp, finalDest, type, hciFrame,
                            snoopFrame);

                    packetList.add(0, packet);

                    if (isFiltered && matchFilter(packet))
                        packetFilteredList.add(0, packet);

                    notifyAdapter();
                }
            });

        } else if (type.getCode() == 3) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Packet packet = new PacketHciScoData(frameCount++, timestamp, finalDest, type, hciFrame,
                            snoopFrame);

                    packetList.add(0, packet);

                    if (isFiltered && matchFilter(packet))
                        packetFilteredList.add(0, packet);

                    notifyAdapter();
                }
            });

        }

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

}

From source file:fr.immotronic.ubikit.pems.enocean.impl.item.data.EEP070904DataImpl.java

public static EEP070904DataImpl constructDataFromRecord(JSONObject lastKnownData) {
    if (lastKnownData == null)
        return new EEP070904DataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, null);

    try {/*from  w w  w .  jav a2  s  .  c  o m*/
        float relativeHumidity = (float) lastKnownData.getDouble("relativeHumidity");
        int CO2ppm = lastKnownData.getInt("CO2ppm");
        float temperature = (float) lastKnownData.getDouble("temperature");
        Date date = new Date(lastKnownData.getLong("date"));

        return new EEP070904DataImpl(relativeHumidity, CO2ppm, temperature, date);
    } catch (JSONException e) {
        Logger.error(LC.gi(), null,
                "constructDataFromRecord(): An exception while building a sensorData from a JSONObject SHOULD never happen. Check the code !",
                e);
        return new EEP070904DataImpl(Float.MIN_VALUE, -1, Float.MIN_VALUE, null);
    }
}

From source file:eu.sathra.io.IO.java

@SuppressWarnings({ "unchecked", "rawtypes" })
private Object getValue(JSONObject jObj, String param, Class<?> clazz)
        throws ArrayIndexOutOfBoundsException, IllegalArgumentException, Exception {
    try {//w ww  . j  a v  a  2s  . c o  m
        if (clazz.equals(String.class)) {
            return jObj.getString(param);
        } else if (clazz.equals(int.class)) {
            return jObj.getInt(param);
        } else if (clazz.equals(long.class)) {
            return jObj.getLong(param);
        } else if (clazz.equals(float.class)) {
            return (float) jObj.getDouble(param);
        } else if (clazz.equals(double.class)) {
            return jObj.getDouble(param);
        } else if (clazz.equals(boolean.class)) {
            return jObj.getBoolean(param);
        } else if (mAdapters.containsKey(clazz)) {
            return mAdapters.get(clazz).load(param, jObj);
        } else if (clazz.isEnum()) {
            return Enum.valueOf((Class<? extends Enum>) clazz, jObj.getString(param));
        } else if (clazz.isArray()) {
            return getValue(jObj.getJSONArray(param), clazz.getComponentType());
        } else {
            return load(jObj.getJSONObject(param), clazz);
        }
    } catch (JSONException e) {
        return null;
    } finally {
        jObj.remove(param);
    }

}

From source file:edu.cens.loci.classes.LociVisit.java

public LociVisit(long visitId, long placeId, int type, long enter, long exit, String recognitions) {
    this.visitId = visitId;
    this.placeId = placeId;
    this.type = type;
    this.enter = enter;
    this.exit = exit;
    try {/*from   w w  w. j av a  2s . c o m*/
        JSONArray jArr = new JSONArray(recognitions);
        this.recognitions = new ArrayList<RecognitionResult>();
        for (int i = 0; i < jArr.length(); i++) {
            JSONObject jObj = jArr.getJSONObject(i);
            RecognitionResult result = new RecognitionResult(jObj.getLong("time"), jObj.getInt("place_id"),
                    jObj.getInt("fingerprint_id"), jObj.getDouble("score"));
            this.recognitions.add(result);
        }
    } catch (JSONException e) {
        MyLog.e(LociConfig.D.JSON, TAG, "LociVisit() : json error.");
        e.printStackTrace();
    }
}

From source file:com.google.android.libraries.cast.companionlibrary.utils.Utils.java

/**
 * Builds and returns a {@link MediaInfo} that was wrapped in a {@link Bundle} by
 * <code>mediaInfoToBundle</code>. It is assumed that the type of the {@link MediaInfo} is
 * {@code MediaMetaData.MEDIA_TYPE_MOVIE}
 *
 * @see <code>mediaInfoToBundle()</code>
 *///from w ww . j a  v  a2s  .  c  o m
public static MediaInfo bundleToMediaInfo(Bundle wrapper) {
    if (wrapper == null) {
        return null;
    }

    MediaMetadata metaData = new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);

    metaData.putString(MediaMetadata.KEY_SUBTITLE, wrapper.getString(MediaMetadata.KEY_SUBTITLE));
    metaData.putString(MediaMetadata.KEY_TITLE, wrapper.getString(MediaMetadata.KEY_TITLE));
    metaData.putString(MediaMetadata.KEY_STUDIO, wrapper.getString(MediaMetadata.KEY_STUDIO));
    ArrayList<String> images = wrapper.getStringArrayList(KEY_IMAGES);
    if (images != null && !images.isEmpty()) {
        for (String url : images) {
            Uri uri = Uri.parse(url);
            metaData.addImage(new WebImage(uri));
        }
    }
    String customDataStr = wrapper.getString(KEY_CUSTOM_DATA);
    JSONObject customData = null;
    if (!TextUtils.isEmpty(customDataStr)) {
        try {
            customData = new JSONObject(customDataStr);
        } catch (JSONException e) {
            LOGE(TAG, "Failed to deserialize the custom data string: custom data= " + customDataStr);
        }
    }
    List<MediaTrack> mediaTracks = null;
    if (wrapper.getString(KEY_TRACKS_DATA) != null) {
        try {
            JSONArray jsonArray = new JSONArray(wrapper.getString(KEY_TRACKS_DATA));
            mediaTracks = new ArrayList<MediaTrack>();
            if (jsonArray.length() > 0) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObj = (JSONObject) jsonArray.get(i);
                    MediaTrack.Builder builder = new MediaTrack.Builder(jsonObj.getLong(KEY_TRACK_ID),
                            jsonObj.getInt(KEY_TRACK_TYPE));
                    if (jsonObj.has(KEY_TRACK_NAME)) {
                        builder.setName(jsonObj.getString(KEY_TRACK_NAME));
                    }
                    if (jsonObj.has(KEY_TRACK_SUBTYPE)) {
                        builder.setSubtype(jsonObj.getInt(KEY_TRACK_SUBTYPE));
                    }
                    if (jsonObj.has(KEY_TRACK_CONTENT_ID)) {
                        builder.setContentId(jsonObj.getString(KEY_TRACK_CONTENT_ID));
                    }
                    if (jsonObj.has(KEY_TRACK_LANGUAGE)) {
                        builder.setLanguage(jsonObj.getString(KEY_TRACK_LANGUAGE));
                    }
                    if (jsonObj.has(KEY_TRACKS_DATA)) {
                        builder.setCustomData(new JSONObject(jsonObj.getString(KEY_TRACKS_DATA)));
                    }
                    mediaTracks.add(builder.build());
                }
            }
        } catch (JSONException e) {
            LOGE(TAG, "Failed to build media tracks from the wrapper bundle", e);
        }
    }
    MediaInfo.Builder mediaBuilder = new MediaInfo.Builder(wrapper.getString(KEY_URL))
            .setStreamType(wrapper.getInt(KEY_STREAM_TYPE)).setContentType(wrapper.getString(KEY_CONTENT_TYPE))
            .setMetadata(metaData).setCustomData(customData).setMediaTracks(mediaTracks);

    if (wrapper.containsKey(KEY_STREAM_DURATION) && wrapper.getLong(KEY_STREAM_DURATION) >= 0) {
        mediaBuilder.setStreamDuration(wrapper.getLong(KEY_STREAM_DURATION));
    }

    return mediaBuilder.build();
}

From source file:eu.codeplumbers.cosi.services.CosiSmsService.java

public void sendChangesToCozy() {
    List<Sms> unSyncedSms = Sms.getAllUnsynced();
    int i = 0;/*from w w w.  j  a v  a  2 s . c o m*/
    for (Sms sms : unSyncedSms) {
        URL urlO = null;
        try {
            JSONObject jsonObject = sms.toJsonObject();
            mBuilder.setProgress(unSyncedSms.size(), i, false);
            mBuilder.setContentText("Syncing " + jsonObject.getString("docType") + ":");
            mNotifyManager.notify(notification_id, mBuilder.build());
            EventBus.getDefault()
                    .post(new SmsSyncEvent(SYNC_MESSAGE, getString(R.string.lbl_sms_status_read_phone)));
            String remoteId = jsonObject.getString("remoteId");
            String requestMethod = "";

            if (remoteId.isEmpty()) {
                urlO = new URL(syncUrl);
                requestMethod = "POST";
            } else {
                urlO = new URL(syncUrl + remoteId + "/");
                requestMethod = "PUT";
            }

            HttpURLConnection conn = (HttpURLConnection) urlO.openConnection();
            conn.setConnectTimeout(5000);
            conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
            conn.setRequestProperty("Authorization", authHeader);
            conn.setDoOutput(true);
            conn.setDoInput(true);

            conn.setRequestMethod(requestMethod);

            // set request body
            jsonObject.remove("remoteId");
            long objectId = jsonObject.getLong("id");
            jsonObject.remove("id");
            OutputStream os = conn.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
            os.flush();

            // read the response
            InputStream in = new BufferedInputStream(conn.getInputStream());

            StringWriter writer = new StringWriter();
            IOUtils.copy(in, writer, "UTF-8");
            String result = writer.toString();

            JSONObject jsonObjectResult = new JSONObject(result);

            if (jsonObjectResult != null && jsonObjectResult.has("_id")) {
                result = jsonObjectResult.getString("_id");
                sms.setRemoteId(result);
                sms.save();
            }

            in.close();
            conn.disconnect();

        } catch (MalformedURLException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (ProtocolException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (IOException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        } catch (JSONException e) {
            EventBus.getDefault().post(new SmsSyncEvent(SERVICE_ERROR, e.getLocalizedMessage()));
            e.printStackTrace();
            stopSelf();
        }
        i++;
    }
}

From source file:mp.teardrop.Song.java

static Song fromJsonObject(JSONObject jsonBourne) {

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

        Song song = new Song(jsonBourne.getBoolean("isCloudSong"), jsonBourne.getString("path"),
                jsonBourne.getString("title"), jsonBourne.getString("album"), jsonBourne.getString("artist"),
                jsonBourne.getInt("trackNumber"));

        if (song.isCloudSong) {
            song.id = -1337;
            song.albumId = -1337;
            song.artistId = -1337;
            song.dbPath = jsonBourne.getString("dbPath");
            song.rgTrack = //TODO: make sure there isn't any loss of precision
                    jsonBourne.has("rgTrack") ? new Float(jsonBourne.getDouble("rgTrack")) : null;
            song.rgAlbum = jsonBourne.has("rgAlbum") ? new Float(jsonBourne.getDouble("rgAlbum")) : null;
        } else {
            song.id = jsonBourne.getLong("id");
            song.artistId = jsonBourne.getLong("artistId");
            song.albumId = jsonBourne.getLong("albumId");
            song.dbPath = null;
        }

        return song;

    } catch (JSONException e) {
        return null;
    }

}

From source file:com.citrus.mobile.OauthToken.java

public boolean createToken(JSONObject usertoken) {

    jsontoken = new JSONObject();

    long expiry = new Date().getTime() / 1000l;

    try {/*from   w  w  w.  j a va 2s.  c o m*/
        expiry += usertoken.getLong("expires_in");
        jsontoken.put("expiry", expiry);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    for (Iterator<?> keys = usertoken.keys(); keys.hasNext();) {
        String key = (String) keys.next();

        try {
            jsontoken.put(key, usertoken.get(key));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return storeToken();

}