Example usage for org.json JSONObject has

List of usage examples for org.json JSONObject has

Introduction

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

Prototype

public boolean has(String key) 

Source Link

Document

Determine if the JSONObject contains a specific key.

Usage

From source file:com.lge.helloFriendsCamera.MainActivity.java

/**
 * Send 'take picture' request to camera
 * - OSC Protocol: osc/commands/execute/* w w  w . java  2  s .  c om*/
 * - OSC API: camera.takePicture
 * - Parameter for 'camera.takePicture':
 * {
 * "parameters": {
 * "sessionId": session ID
 * }
 * }
 *
 * - Use OSCCommandExecute class for /osc/commands/execute
 * - OSCCommandsExecute(String command_name, JSONObject parameters);
 */
private void takePicture() {
    //Set parameter for camera.takePicture API
    //Make parameter by using JSONObject
    OSCCommandsExecute commandsExecute = new OSCCommandsExecute("camera.takePicture", null);
    commandsExecute.setListener(new HttpAsyncTask.OnHttpListener() {
        @Override
        public void onResponse(OSCReturnType type, Object response) {

            try {
                JSONObject jObject = new JSONObject((String) response);
                String state;

                //Get normal response
                if (jObject.has(OSCParameterNameMapper.COMMAND_STATE)) {
                    state = jObject.getString(OSCParameterNameMapper.COMMAND_STATE);
                    //Taking picture is on progress
                    if (state.equals(OSCParameterNameMapper.STATE_INPROGRESS)) {
                        String commandId = jObject.getString(OSCParameterNameMapper.COMMAND_ID);
                        checkCommandsStatus(commandId);
                    } else { //Taking picture is finished
                        handleFinishTakePicture((String) response);
                    }
                } else { //Get error response
                    Toast.makeText(mContext, "[Error] Error occur during taking picture", Toast.LENGTH_LONG)
                            .show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    });
    commandsExecute.execute();
}

From source file:com.lge.helloFriendsCamera.MainActivity.java

/**
 * Check previous api status//from  w ww . j  a va2  s .com
 * - OSC Protocol: osc/commands/status
 * - Parameter for /osc/commands/status: command ID(get from previous /osc/commands/execute)
 * - Use OSCCommandStatus class for /osc/commands/status
 * - OSCCommandsStatus(String command_id);
 */
private void checkCommandsStatus(final String commandId) {
    OSCCommandsStatus commandsStatus = new OSCCommandsStatus(commandId);
    commandsStatus.setListener(new HttpAsyncTask.OnHttpListener() {
        @Override
        public void onResponse(OSCReturnType type, final Object response) {

            try {
                JSONObject jObject = new JSONObject((String) response);
                String state;
                //Get normal response
                if (jObject.has(OSCParameterNameMapper.COMMAND_STATE)) {
                    state = jObject.getString(OSCParameterNameMapper.COMMAND_STATE);
                    //Taking picture is on progress
                    if (state.equals(OSCParameterNameMapper.STATE_INPROGRESS)) {
                        checkCommandsStatus(commandId);
                    } else { //Taking picture is finished
                        handleFinishTakePicture((String) response);
                    }
                } else {//Get error response
                    Toast.makeText(mContext, "Error occur during taking picture", Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
    commandsStatus.execute();
}

From source file:com.lge.helloFriendsCamera.MainActivity.java

private void handleFinishTakePicture(String response) {
    //Finish take picture, then show toast and close session
    String fileUrl = null;/*from   ww  w .j  av a  2s. c  o m*/
    try {
        JSONObject jObject = new JSONObject((String) response);

        if (jObject.has(OSCParameterNameMapper.RESULTS)) {
            JSONObject results = jObject.getJSONObject(OSCParameterNameMapper.RESULTS);

            fileUrl = results.getString(OSCParameterNameMapper.FILEURL);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (fileUrl != null) {
        Toast.makeText(mContext, "Picture " + fileUrl + " is taken", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(mContext, "[Error] Take picture response Error", Toast.LENGTH_LONG).show();
    }
}

From source file:com.mercandalli.android.apps.files.file.cloud.FileMyCloudFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    final View rootView = inflater.inflate(R.layout.fragment_file_files, container, false);
    final Activity activity = getActivity();
    final String succeed = "succeed";

    mProgressBar = (ProgressBar) rootView.findViewById(R.id.circularProgressBar);
    mMessageTextView = (TextView) rootView.findViewById(R.id.message);

    mSwipeRefreshLayout = (SwipeRefreshLayout) rootView
            .findViewById(R.id.fragment_file_files_swipe_refresh_layout);
    mSwipeRefreshLayout.setOnRefreshListener(this);
    mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
            android.R.color.holo_green_light, android.R.color.holo_orange_light,
            android.R.color.holo_red_light);

    mRecyclerView = (RecyclerView) rootView.findViewById(R.id.fragment_file_files_recycler_view);
    mRecyclerView.setHasFixedSize(true);

    final int nbColumn = getResources().getInteger(R.integer.column_number_card);
    if (nbColumn <= 1) {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(activity));
    } else {//from   ww w  .  j  ava 2s . com
        mRecyclerView.setLayoutManager(new GridLayoutManager(activity, nbColumn));
    }

    resetPath();

    mFileModelAdapter = new FileModelAdapter(getContext(), mFilesList, new FileModelListener() {
        @Override
        public void executeFileModel(final FileModel fileModel, final View view) {
            final AlertDialog.Builder menuAlert = new AlertDialog.Builder(getContext());
            String[] menuList = { getString(R.string.download), getString(R.string.rename),
                    getString(R.string.delete), getString(R.string.cut), getString(R.string.properties) };
            if (!fileModel.isDirectory()) {
                if (FileTypeModelENUM.IMAGE.type.equals(fileModel.getType())) {
                    menuList = new String[] { getString(R.string.download), getString(R.string.rename),
                            getString(R.string.delete), getString(R.string.cut), getString(R.string.properties),
                            (fileModel.isPublic()) ? "Become private" : "Become public", "Set as profile" };
                } else if (FileTypeModelENUM.APK.type.equals(fileModel.getType()) && Config.isUserAdmin()) {
                    menuList = new String[] { getString(R.string.download), getString(R.string.rename),
                            getString(R.string.delete), getString(R.string.cut), getString(R.string.properties),
                            (fileModel.isPublic()) ? "Become private" : "Become public",
                            (fileModel.isApkUpdate()) ? "Remove the update" : "Set as update" };
                } else {
                    menuList = new String[] { getString(R.string.download), getString(R.string.rename),
                            getString(R.string.delete), getString(R.string.cut), getString(R.string.properties),
                            (fileModel.isPublic()) ? "Become private" : "Become public" };
                }
            }
            menuAlert.setTitle(getString(R.string.action));
            menuAlert.setItems(menuList, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int item) {
                    switch (item) {
                    case 0:
                        mFileManager.download(getActivity(), fileModel, new IListener() {
                            @Override
                            public void execute() {
                                Toast.makeText(getContext(), "Download finished.", Toast.LENGTH_SHORT).show();
                            }
                        });
                        break;

                    case 1:
                        DialogUtils.prompt(getActivity(), "Rename",
                                "Rename " + (fileModel.isDirectory() ? "directory" : "file") + " "
                                        + fileModel.getName() + " ?",
                                "Ok", new DialogUtils.OnDialogUtilsStringListener() {
                                    @Override
                                    public void onDialogUtilsStringCalledBack(String text) {
                                        mFileManager.rename(fileModel, text, new IListener() {
                                            @Override
                                            public void execute() {
                                                if (mFilesToCutList.size() != 0) {
                                                    mFilesToCutList.clear();
                                                    mFileCloudFabManager.updateFabButtons();
                                                }
                                                refreshCurrentList();
                                            }
                                        });
                                    }
                                }, "Cancel", null, fileModel.getFullName());
                        break;

                    case 2:
                        DialogUtils.alert(getActivity(), "Delete",
                                "Delete " + (fileModel.isDirectory() ? "directory" : "file") + " "
                                        + fileModel.getName() + " ?",
                                "Yes", new DialogUtils.OnDialogUtilsListener() {
                                    @Override
                                    public void onDialogUtilsCalledBack() {
                                        mFileManager.delete(fileModel, new IListener() {
                                            @Override
                                            public void execute() {
                                                if (mFilesToCutList.size() != 0) {
                                                    mFilesToCutList.clear();
                                                    mFileCloudFabManager.updateFabButtons();
                                                }
                                                refreshCurrentList();
                                            }
                                        });
                                    }
                                }, "No", null);
                        break;

                    case 3:
                        mFilesToCutList.add(fileModel);
                        Toast.makeText(getContext(), "File ready to cut.", Toast.LENGTH_SHORT).show();
                        mFileCloudFabManager.updateFabButtons();
                        break;

                    case 4:
                        DialogUtils.alert(getActivity(),
                                getString(R.string.properties) + " : " + fileModel.getName(),
                                mFileManager.toSpanned(getContext(), fileModel), "OK", null, null, null);

                        Html.fromHtml("");

                        break;

                    case 5:
                        mFileManager.setPublic(fileModel, !fileModel.isPublic(), new IListener() {
                            @Override
                            public void execute() {
                            }
                        });
                        break;

                    case 6:
                        // Picture set as profile
                        if (FileTypeModelENUM.IMAGE.type.equals(fileModel.getType())) {
                            List<StringPair> parameters = new ArrayList<>();
                            parameters.add(new StringPair("id_file_profile_picture", "" + fileModel.getId()));
                            (new TaskPost(getActivity(), Constants.URL_DOMAIN + Config.ROUTE_USER_PUT,
                                    new IPostExecuteListener() {
                                        @Override
                                        public void onPostExecute(JSONObject json, String body) {
                                            try {
                                                if (json != null && json.has(succeed)
                                                        && json.getBoolean(succeed)) {
                                                    Config.setUserIdFileProfilePicture(getActivity(),
                                                            fileModel.getId());
                                                }
                                            } catch (JSONException e) {
                                                Log.e(getClass().getName(), "Failed to convert Json", e);
                                            }
                                        }
                                    }, parameters)).execute();
                        } else if (FileTypeModelENUM.APK.type.equals(fileModel.getType())
                                && Config.isUserAdmin()) {
                            List<StringPair> parameters = new ArrayList<>();
                            parameters.add(new StringPair("is_apk_update", "" + !fileModel.isApkUpdate()));
                            (new TaskPost(getActivity(),
                                    Constants.URL_DOMAIN + Config.ROUTE_FILE + "/" + fileModel.getId(),
                                    new IPostExecuteListener() {
                                        @Override
                                        public void onPostExecute(JSONObject json, String body) {
                                            try {
                                                if (json != null && json.has(succeed)
                                                        && json.getBoolean(succeed)) {

                                                }
                                            } catch (JSONException e) {
                                                Log.e(getClass().getName(), "Failed to convert Json", e);
                                            }
                                        }
                                    }, parameters)).execute();
                        }
                        break;

                    }
                }
            });
            AlertDialog menuDrop = menuAlert.create();
            menuDrop.show();
        }
    }, new FileModelAdapter.OnFileClickListener() {
        @Override
        public void onFileClick(View view, int position) {
            /*
            if (hasItemSelected()) {
            mFilesList.get(position).selected = !mFilesList.get(position).selected;
            mFileModelAdapter.notifyItemChanged(position);
            }
            else
            */
            if (mFilesList.get(position).isDirectory()) {
                mIdFileDirectoryStack.add(mFilesList.get(position).getId());
                refreshCurrentList(true);
            } else {
                mFileManager.execute(getActivity(), position, mFilesList, view);
            }
        }
    }, new FileModelAdapter.OnFileLongClickListener() {
        @Override
        public boolean onFileLongClick(View view, int position) {
            /*
            mFilesList.get(position).selected = !mFilesList.get(position).selected;
            mFileModelAdapter.notifyItemChanged(position);
            */
            return true;
        }
    });

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        scaleAnimationAdapter = new ScaleAnimationAdapter(mRecyclerView, mFileModelAdapter);
        scaleAnimationAdapter.setDuration(220);
        scaleAnimationAdapter.setOffsetDuration(32);
        mRecyclerView.setAdapter(scaleAnimationAdapter);
    } else {
        mRecyclerView.setAdapter(mFileModelAdapter);
    }

    refreshCurrentList(true);

    return rootView;
}

From source file:org.apache.cordova.contacts.ContactAccessor.java

/**
 * Create a hash map of what data needs to be populated in the Contact object
 * @param fields the list of fields to populate
 * @return the hash map of required data
 */// w w w  .  ja v a  2s .c  o  m
protected HashMap<String, Boolean> buildPopulationSet(JSONObject options) {
    HashMap<String, Boolean> map = new HashMap<String, Boolean>();

    String key;
    try {
        JSONArray desiredFields = null;
        if (options != null && options.has("desiredFields")) {
            desiredFields = options.getJSONArray("desiredFields");
        }
        if (desiredFields == null || desiredFields.length() == 0) {
            map.put("displayName", true);
            map.put("name", true);
            map.put("nickname", true);
            map.put("phoneNumbers", true);
            map.put("emails", true);
            map.put("addresses", true);
            map.put("ims", true);
            map.put("organizations", true);
            map.put("birthday", true);
            map.put("note", true);
            map.put("urls", true);
            map.put("photos", true);
            map.put("categories", true);
        } else {
            for (int i = 0; i < desiredFields.length(); i++) {
                key = desiredFields.getString(i);
                if (key.startsWith("displayName")) {
                    map.put("displayName", true);
                } else if (key.startsWith("name")) {
                    map.put("displayName", true);
                    map.put("name", true);
                } else if (key.startsWith("nickname")) {
                    map.put("nickname", true);
                } else if (key.startsWith("phoneNumbers")) {
                    map.put("phoneNumbers", true);
                } else if (key.startsWith("emails")) {
                    map.put("emails", true);
                } else if (key.startsWith("addresses")) {
                    map.put("addresses", true);
                } else if (key.startsWith("ims")) {
                    map.put("ims", true);
                } else if (key.startsWith("organizations")) {
                    map.put("organizations", true);
                } else if (key.startsWith("birthday")) {
                    map.put("birthday", true);
                } else if (key.startsWith("note")) {
                    map.put("note", true);
                } else if (key.startsWith("urls")) {
                    map.put("urls", true);
                } else if (key.startsWith("photos")) {
                    map.put("photos", true);
                } else if (key.startsWith("categories")) {
                    map.put("categories", true);
                }
            }
        }
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return map;
}

From source file:org.jandroid2cloud.connection.ChannelHandler.java

private void handleLink(JSONObject link) throws JSONException {
    if (link.has("link")) {
        link = link.getJSONObject("link");
    }/* ww w .  j a  v  a 2  s  . co  m*/
    String url = link.getString("url");
    if (url.equals(waitingFor)) {
        received = true;
        waitingForSema.release(1);
    } else {
        logger.info(NotificationAppender.MARKER, "new link " + url + " received.");
        LinkQueue.INSTANCE.push(url);
    }
}

From source file:org.openhab.habdroid.model.OpenHABNotification.java

public OpenHABNotification(JSONObject jsonObject) {
    try {/*from   w ww.  j  av  a 2  s. co m*/
        if (jsonObject.has("icon"))
            this.setIcon(jsonObject.getString("icon"));
        if (jsonObject.has("severity"))
            this.setSeverity(jsonObject.getString("severity"));
        if (jsonObject.has("message"))
            this.setMessage(jsonObject.getString("message"));
        if (jsonObject.has("created")) {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.S'Z'");
            format.setTimeZone(TimeZone.getTimeZone("UTC"));
            this.setCreated(format.parse(jsonObject.getString("created")));
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

From source file:com.parking.billing.Security.java

/**
 * Verifies that the data was signed with the given signature, and returns
 * the list of verified purchases. The data is in JSON format and contains
 * a nonce (number used once) that we generated and that was signed
 * (as part of the whole data string) with a private key. The data also
 * contains the {@link PurchaseState} and product ID of the purchase.
 * In the general case, there can be an array of purchase transactions
 * because there may be delays in processing the purchase on the backend
 * and then several purchases can be batched together.
 * @param signedData the signed JSON string (signed, not encrypted)
 * @param signature the signature for the data, signed with the private key
 *//*from  w w  w  .  ja  v  a 2s  .  c  o m*/
public static ArrayList<VerifiedPurchase> verifyPurchase(String signedData, String signature) {
    if (signedData == null) {
        Log.e(TAG, "data is null");
        return null;
    }
    if (BillingConstants.DEBUG) {
        Log.i(TAG, "signedData: " + signedData);
    }

    boolean verified = false;

    if (!TextUtils.isEmpty(signature)) {
        /**
         * Compute your public key (that you got from the Android Market publisher site).
         *
         * Instead of just storing the entire literal string here embedded in the
         * program,  construct the key at runtime from pieces or
         * use bit manipulation (for example, XOR with some other string) to hide
         * the actual key.  The key itself is not secret information, but we don't
         * want to make it easy for an adversary to replace the public key with one
         * of their own and then fake messages from the server.
         *
         * Generally, encryption keys / passwords should only be kept in memory
         * long enough to perform the operation they need to perform.
         */
        //Chintan's Key
        String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRIrk/6nAPzZo5HKe261/ZMfoe63mtY5QUlc0A0/77RTicrS9Nk1VjtVniRpHmjasQOGsQrBpBGJUYp0ixsjJpgfjLv7OvpF8Hp/ucth2T/Bm7kl/odRDT3urAp3snvqZEzfOg1wtDU7DAnDW1zNSqVNCVczXRnNrEmGxEjamKkTTQwz37ui7AhjKXCXAJY4n5ANj1oymnjGN5FHfzcMb07wR/ucz39ZX+Raf6qBsbnYkmuDH6pJ/4ZI9+vjbgWzXCx07DefQW4dtNMQZlVlKgKnJUkafePUYJVIO4sRgeWL1e5b8dbIYMO7gB9oopyfVhZifi+pDGr5+YAxi6D3PwIDAQAB";
        //Mandar's Key:
        //String base64EncodedPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAj7zgTswMi1ePyAK7rCnCOkpmviHZzoSn2cxtyQ5ZQRFifNGkKq3Gli3VbeIeeJR8GHzlfOPUSgtMrd17WtGJoo29rsw6UuXov+imQutGKZglcM/cIrlIdZCsse3dGYyDcKFhEHrC/nPdwlYxgIGBaZKAcbbhitkdgYaVHQvGFTagCytxDq9NDJAY7exSKKm2HimfjlcBZjhHeImZ+cRCPux+9uoBQ4mTRYjrXfcpi/OPKTKsq2AHXf/y60qsZJlgGl3tBgRQo6lOEr7UbbHKESTKvOQ4t3J1wjNz8Z3+T0PZHb5JkeTsdAE7cG7jmz2HmMxfdXcT5mBTTDei6DPDGwIDAQAB";
        PublicKey key = Security.generatePublicKey(base64EncodedPublicKey);
        verified = Security.verify(key, signedData, signature);
        if (!verified) {
            Log.w(TAG, "signature does not match data.");
            return null;
        }
    }

    JSONObject jObject;
    JSONArray jTransactionsArray = null;
    int numTransactions = 0;
    long nonce = 0L;
    try {
        jObject = new JSONObject(signedData);

        // The nonce might be null if the user backed out of the buy page.
        nonce = jObject.optLong("nonce");
        jTransactionsArray = jObject.optJSONArray("orders");
        if (jTransactionsArray != null) {
            numTransactions = jTransactionsArray.length();
        }
    } catch (JSONException e) {
        return null;
    }

    if (!Security.isNonceKnown(nonce)) {
        Log.w(TAG, "Nonce not found: " + nonce);
        return null;
    }

    ArrayList<VerifiedPurchase> purchases = new ArrayList<VerifiedPurchase>();
    try {
        for (int i = 0; i < numTransactions; i++) {
            JSONObject jElement = jTransactionsArray.getJSONObject(i);
            int response = jElement.getInt("purchaseState");
            PurchaseState purchaseState = PurchaseState.valueOf(response);
            String productId = jElement.getString("productId");
            String packageName = jElement.getString("packageName");
            long purchaseTime = jElement.getLong("purchaseTime");
            String orderId = jElement.optString("orderId", "");
            String notifyId = null;
            if (jElement.has("notificationId")) {
                notifyId = jElement.getString("notificationId");
            }
            String developerPayload = jElement.optString("developerPayload", null);

            // If the purchase state is PURCHASED, then we require a
            // verified nonce.

            /**
             *   mandarm - We are ok with no signature for our test code! 
             */
            //TODO - Take care for signed purchases.

            if (purchaseState == PurchaseState.PURCHASED && !verified) {
                continue;
            }

            purchases.add(new VerifiedPurchase(purchaseState, notifyId, productId, orderId, purchaseTime,
                    developerPayload));
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSON exception: ", e);
        return null;
    }
    removeNonce(nonce);
    return purchases;
}

From source file:com.clearcenter.mobile_demo.mdStatusActivity.java

public void updateData() {
    JSONObject json_data;

    String projection[] = new String[] { mdDeviceSamples.DATA };

    Cursor cursor = getContentResolver().query(mdDeviceSamples.CONTENT_URI, projection,
            mdDeviceSamples.NICKNAME + " = ?", new String[] { account_nickname }, null);

    int rows = 0;
    try {//from   w  w w .j  a  va 2 s  .  com
        rows = cursor.getCount();
    } catch (NullPointerException e) {
    }

    Log.d(TAG, "Matches: " + rows);

    if (rows == 0) {
        Log.d(TAG, "No rows match for nickname: " + account_nickname);
        cursor.close();
        return;
    }

    cursor.moveToLast();

    String data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

    try {
        json_data = new JSONObject(data);
        if (json_data.has("hostname"))
            hostname_textview.setText("Hostname: " + json_data.getString("hostname"));
        if (json_data.has("name") && json_data.has("release")) {
            final String release = json_data.getString("name") + " " + json_data.getString("release");
            release_textview.setText("Release: " + release);
        }
        if (json_data.has("time_locale")) {
            time_textview.setText("Clock: " + json_data.getString("time_locale"));
        }

        if (rows >= 2) {
            bw_graphview.reset();
            loadavg_graphview.reset();
            mem_graphview.reset();

            if (rows <= samples)
                cursor.moveToFirst();
            else
                cursor.move(-samples);

            long unix_time = 0;
            double bw_up = 0.0;
            double bw_down = 0.0;

            do {
                data = cursor.getString(cursor.getColumnIndex(mdDeviceSamples.DATA));

                final List<JSONObject> samples = sortedSamplesList(data);
                ListIterator<JSONObject> li = samples.listIterator();

                while (li.hasNext()) {
                    json_data = li.next();

                    if (unix_time == 0) {
                        bw_up = json_data.getDouble("bandwidth_up");
                        bw_down = json_data.getDouble("bandwidth_down");
                        unix_time = Long.valueOf(json_data.getString("time"));
                        continue;
                    }

                    long diff = Long.valueOf(json_data.getString("time")) - unix_time;

                    double rate_up = (json_data.getDouble("bandwidth_up") - bw_up) / diff;
                    double rate_down = (json_data.getDouble("bandwidth_down") - bw_down) / diff;

                    if (rate_up < 0.0)
                        rate_up = 0.0;
                    if (rate_down < 0.0)
                        rate_down = 0.0;

                    bw_graphview.addSample(bw_graph_up, unix_time, (float) rate_up);
                    bw_graphview.addSample(bw_graph_down, unix_time, (float) rate_down);

                    //                        Log.d(TAG, "time: " + diff +
                    //                            ", rate_up: " + rate_up + ", rate_down: " + rate_down);
                    bw_up = json_data.getDouble("bandwidth_up");
                    bw_down = json_data.getDouble("bandwidth_down");

                    loadavg_graphview.addSample(loadavg_graph_5min, unix_time,
                            (float) json_data.getDouble("loadavg_5min"));
                    loadavg_graphview.addSample(loadavg_graph_15min, unix_time,
                            (float) json_data.getDouble("loadavg_15min"));

                    mem_graphview.addSample(mem_graph_active, unix_time,
                            (float) json_data.getDouble("mem_active"));
                    mem_graphview.addSample(mem_graph_swap, unix_time,
                            (float) json_data.getDouble("mem_swap_used"));

                    unix_time = Long.valueOf(json_data.getString("time"));
                }
            } while (cursor.moveToNext());

            bw_graphview.update();
            loadavg_graphview.update();
            mem_graphview.update();
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    cursor.close();
}

From source file:com.clearcenter.mobile_demo.mdStatusActivity.java

public List<JSONObject> sortedSamplesList(String data) {
    SortedMap<String, JSONObject> map = new TreeMap<String, JSONObject>();

    try {//from   w  w w  .j a v a 2  s  .c  o  m
        int version = 0;
        JSONObject json_data = new JSONObject(data);
        if (json_data.has("version"))
            version = json_data.getInt("version");
        if (version < 1 && json_data.has("time")) {
            String key = json_data.getString("time");
            map.put(key, json_data);
        } else if (version >= 1 && json_data.has("samples") && !json_data.isNull("samples")) {
            json_data = json_data.getJSONObject("samples");
            Iterator i = json_data.keys();
            while (i.hasNext()) {
                String key = i.next().toString();
                JSONObject sample = json_data.getJSONObject(key);
                sample.put("time", key);
                map.put(key, sample);
            }
        }
    } catch (JSONException e) {
        Log.e(TAG, "JSONException", e);
    }

    return new LinkedList<JSONObject>(map.values());
}