Example usage for org.json JSONObject getBoolean

List of usage examples for org.json JSONObject getBoolean

Introduction

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

Prototype

public boolean getBoolean(String key) throws JSONException 

Source Link

Document

Get the boolean value associated with a key.

Usage

From source file:hongik.android.project.best.StoreReviewActivity.java

public void drawTable() throws Exception {
    String query = "func=morereview" + "&license=" + license;
    DBConnector conn = new DBConnector(query);
    conn.start();/*from w  w  w .  jav  a2s.  c om*/

    conn.join();
    JSONObject jsonResult = conn.getResult();
    boolean result = jsonResult.getBoolean("result");

    if (!result) {
        return;
    }

    String storeName = jsonResult.getString("sname");
    ((TextViewPlus) findViewById(R.id.storereview_storename)).setText(storeName);

    JSONArray review = null;
    if (!jsonResult.isNull("review")) {
        review = jsonResult.getJSONArray("review");
    }

    //Draw Review Table
    if (review != null) {
        TableRow motive = (TableRow) reviewTable.getChildAt(1);

        for (int i = 0; i < review.length(); i++) {
            JSONObject json = review.getJSONObject(i);
            final String[] elements = new String[4];
            elements[0] = Double.parseDouble(json.getString("GRADE")) + "";
            elements[1] = json.getString("NOTE");
            elements[2] = json.getString("CID#");
            elements[3] = json.getString("DAY");

            TableRow tbRow = new TableRow(this);
            TextViewPlus[] tbCols = new TextViewPlus[4];

            if (elements[1].length() > 14)
                elements[1] = elements[1].substring(0, 14) + "...";

            for (int j = 0; j < 4; j++) {
                tbCols[j] = new TextViewPlus(this);
                tbCols[j].setText(elements[j]);
                tbCols[j].setLayoutParams(motive.getChildAt(j).getLayoutParams());
                tbCols[j].setGravity(Gravity.CENTER);
                tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(),
                        "InterparkGothicBold.ttf"));
                tbCols[j].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent reviewIntent = new Intent(originActivity, ReviewDetailActivity.class);
                        reviewIntent.putExtra("ACCESS", "STORE");
                        reviewIntent.putExtra("CID", elements[2]);
                        reviewIntent.putExtra("LICENSE", license);
                        Log.i("StoreReview", "StartActivity");
                        startActivity(reviewIntent);
                    }
                });

                Log.i("StoreMenu", "COL" + j + ":" + elements[j]);
                tbRow.addView(tbCols[j]);
            }
            reviewTable.addView(tbRow);
        }
    }
    reviewTable.removeViewAt(1);
}

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a boolean stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/*from w w w . j  a v a2s  .  com*/
 * @return the boolean stored in the key, or the default value if the key doesn't exist
 */
public static boolean safeGetBoolean(JSONObject obj, String key, boolean defaultValue) {
    if (obj == null || TextUtils.isEmpty(key))
        return defaultValue;
    if (obj.has(key)) {
        try {
            return obj.getBoolean(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get boolean from key " + key, e);
        }
    }
    return defaultValue;
}

From source file:com.github.koraktor.steamcondenser.community.SteamGame.java

/**
 * Returns whether the given version of the game with the given application
 * ID is up-to-date//  ww  w .  ja  v  a 2 s.c o m
 *
 * @param appId The application ID of the game to check
 * @param version The version to check against the Web API
 * @return <code>true</code> if the given version is up-to-date
 * @throws JSONException if the JSON data is malformed
 * @throws SteamCondenserException if the Web API request fails
 */
public static boolean isUpToDate(int appId, int version) throws JSONException, SteamCondenserException {
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("appid", appId);
    params.put("version", version);
    String json = WebApi.getJSON("ISteamApps", "UpToDateCheck", 1, params);
    JSONObject result = new JSONObject(json).getJSONObject("response");
    if (!result.getBoolean("success")) {
        throw new SteamCondenserException(result.getString("error"));
    }
    return result.getBoolean("up_to_date");
}

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   w  w w  .  j av  a  2s .  c  o  m*/
        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:com.microsoft.live.unittest.PostTest.java

@Override
protected void checkValidResponseBody(LiveOperation operation) throws JSONException {
    JSONObject result = operation.getResult();
    String id = result.getString(JsonKeys.ID);
    Object description = result.get(JsonKeys.DESCRIPTION);
    String name = result.getString(JsonKeys.NAME);
    String permissions = result.getString(JsonKeys.PERMISSIONS);
    boolean isDefault = result.getBoolean(JsonKeys.IS_DEFAULT);

    JSONObject from = result.getJSONObject(JsonKeys.FROM);
    String fromId = from.getString(JsonKeys.ID);
    String fromName = from.getString(JsonKeys.NAME);

    Object subscriptionLocation = result.get(JsonKeys.SUBSCRIPTION_LOCATION);
    String createdTime = result.getString(JsonKeys.CREATED_TIME);
    String updatedTime = result.getString(JsonKeys.UPDATED_TIME);

    assertEquals("calendar_id", id);
    assertEquals(JSONObject.NULL, description);
    assertEquals("name", name);
    assertEquals("owner", permissions);
    assertEquals(false, isDefault);/*from w  w  w. j  ava2  s  .  co  m*/
    assertEquals("from_id", fromId);
    assertEquals("from_name", fromName);
    assertEquals(JSONObject.NULL, subscriptionLocation);
    assertEquals("2011-12-10T02:48:33+0000", createdTime);
    assertEquals("2011-12-10T02:48:33+0000", updatedTime);
}

From source file:com.roiland.crm.sm.core.service.impl.ContacterAPIImpl.java

@SuppressWarnings("unchecked")
@Override//from   w  ww .  j ava 2s .co  m
public List<Contacter> getContacterList(String userID, String dealerOrgID, String projectID, String customerID)
        throws ResponseException {
    ReleasableList<Contacter> contacterList = null;
    try {

        // ??.
        if (userID == null || dealerOrgID == null) {
            throw new ResponseException("userID or dealerOrgID is null.");
        }

        JSONObject params = new JSONObject();
        params.put("userID", userID);
        params.put("dealerOrgID", dealerOrgID);
        params.put("projectID", projectID);
        params.put("customerID", customerID);

        // ?Key
        String key = getKey(URLContact.METHOD_GET_CONTACTER_LIST, params);

        // ????
        contacterList = lruCache.get(key);
        if (contacterList != null && !contacterList.isExpired()) {
            return contacterList;
        }

        RLHttpResponse response = getHttpClient()
                .executePostJSON(getURLAddress(URLContact.METHOD_GET_CONTACTER_LIST), params, null);
        if (response.isSuccess()) {
            contacterList = new ArrayReleasableList<Contacter>();
            String data = getSimpleString(response);
            Log.i("getContacterList", data);
            JSONObject jsonBean = new JSONObject(data);
            JSONArray contacter = jsonBean.getJSONArray("result");
            int n = contacter.length();
            for (int i = 0; i < n; i++) {
                JSONObject json = contacter.getJSONObject(i);
                Contacter resultContacter = new Contacter();
                resultContacter.setContacterID(json.getString("contacterID"));
                resultContacter.setProjectID(String.valueOf(json.getString("projectID")));
                resultContacter.setCustomerID(String.valueOf(json.getString("customerID")));
                resultContacter.setContName(parsingString(json.get("contName")));
                resultContacter.setContMobile(parsingString(json.get("contMobile")));
                resultContacter.setContOtherPhone(parsingString(json.get("contOtherPhone")));
                resultContacter.setIsPrimContanter(String.valueOf(json.getBoolean("isPrimContanter")));
                resultContacter.setContGenderCode(parsingString(json.get("contGenderCode")));
                resultContacter.setContGender(parsingString(json.get("contGender")));
                resultContacter
                        .setContBirthday(String.valueOf(DataVerify.isZero(json.getString("contBirthday"))));
                resultContacter.setIdNumber(parsingString(json.get("idNumber")));
                resultContacter.setAgeScopeCode(parsingString(json.get("ageScopeCode")));
                resultContacter.setAgeScope(parsingString(json.get("ageScope")));
                resultContacter.setContType(parsingString(json.get("contType")));
                resultContacter.setContTypeCode(String.valueOf(json.getString("contTypeCode")));
                resultContacter.setContRelationCode(String.valueOf(json.getString("contRelationCode")));
                resultContacter.setContRelation(parsingString(json.get("contRelation")));
                resultContacter
                        .setLicenseValid(StringUtils.toLong(DataVerify.isZero(json.getString("licenseValid"))));
                contacterList.add(resultContacter);

            }
            // ?
            if (contacterList != null) {
                lruCache.put(key, contacterList);
            }
            return contacterList;
        }
        throw new ResponseException();
    } catch (IOException e) {
        Log.e(tag, "Connection network error.", e);
        throw new ResponseException(e);
    } catch (JSONException e) {
        Log.e(tag, "Parsing data error.", e);
        throw new ResponseException(e);
    }

}

From source file:com.trellmor.berrytube.Poll.java

/**
 * Constructs a <code>Poll</code> from a <code>JSONObject<code>
 * //from  ww  w.j a va  2  s  .co m
 * @param poll <code>JSONObject<code> containing the poll data
 * @throws JSONException
 */
public Poll(JSONObject poll) throws JSONException {
    mTitle = poll.getString("title");
    mCreator = poll.getString("title");
    mObscure = poll.getBoolean("obscure");

    JSONArray options = poll.getJSONArray("options");
    for (int i = 0; i < options.length(); i++) {
        mOptions.add(options.getString(i));
    }

    JSONArray votes = poll.getJSONArray("votes");
    for (int i = 0; i < votes.length(); i++) {
        mVotes.add(votes.optInt(i, -1));
    }
}

From source file:br.unicamp.cst.behavior.bn.Behavior.java

/**
 *  Checks if there is a current behavior proposition in working storage that is using the resources this behavior needs
 * @return if there is conflict of resources
 *//*w  w  w  .j  av  a2 s.  co m*/
private boolean resourceConflict() {//TODO must develop this idea further
    boolean resourceConflict = false;
    ArrayList<MemoryObject> allOfType = new ArrayList<MemoryObject>();

    if (ws != null)
        allOfType.addAll(ws.getAllOfType("BEHAVIOR_PROPOSITION"));

    ArrayList<String> usedResources = new ArrayList<String>();

    if (allOfType != null) {

        for (MemoryObject bp : allOfType) {
            try {
                JSONObject jsonBp = new JSONObject(bp.getI());
                //System.out.println("=======> bp.getInfo(): "+bp.getInfo());
                boolean performed = jsonBp.getBoolean("PERFORMED");
                if (!performed) {//otherwise it is not consuming those resources

                    JSONArray resourceList = jsonBp.getJSONArray("RESOURCELIST");

                    for (int i = 0; i < resourceList.length(); i++) {
                        usedResources.add(resourceList.getString(i));
                    }
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
    //      System.out.println("%%% usedResources: "+usedResources);
    //      System.out.println("%%% getResourceList: "+getResourceList());
    int sizeBefore = usedResources.size();
    usedResources.removeAll(this.getResourceList());
    int sizeLater = usedResources.size();

    if (sizeLater != sizeBefore) {
        resourceConflict = true;
        //         System.out.println("%%%%%%%%%%%%%%%%%%%%% There was a conflict here");
    }

    return resourceConflict;
}

From source file:org.apache.cordova.plugins.DownloadManager.DownloadManager.java

@Override
public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) {
    if (action.equals("start")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    /* Get OPTIONS */
                    JSONObject params = args.getJSONObject(0);
                    String fileUrl = params.getString("url");
                    Boolean overwrite = params.getBoolean("overwrite");
                    String fileName = params.has("fileName") ? params.getString("fileName")
                            : fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
                    String filePath = params.has("filePath") ? params.getString("filePath")
                            : cordova.getActivity()
                                    .getString(cordova.getActivity().getResources().getIdentifier("app_name",
                                            "string", cordova.getActivity().getPackageName()));
                    String startToast = params.has("startToast") ? params.getString("startToast")
                            : "Download Start!";
                    String ticker = params.has("ticker") ? params.getString("ticker") : "Downloading...";
                    String endToast = params.has("endToast") ? params.getString("endToast")
                            : "Download Complete!";
                    String cancelToast = params.has("cancelToast") ? params.getString("cancelToast")
                            : "Download canceled!";
                    Boolean useNotificationBar = params.has("useNotificationBar")
                            ? params.getBoolean("useNotificationBar")
                            : true;//  w  w  w .  ja v a2  s .  co  m
                    String notificationTitle = params.has("notificationTitle")
                            ? params.getString("notificationTitle")
                            : "Downloading: " + fileName;

                    String dirName = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Download/"
                            + filePath + "/";

                    // Get an ID:
                    int downloader_id = new Random().nextInt(10000);
                    String downloader_id_str = String.valueOf(downloader_id);

                    // Instantiate Downloader with the ID:
                    Downloader downloadFile = new Downloader(downloader_id_str, fileUrl, dirName, fileName,
                            overwrite, startToast, ticker, notificationTitle, endToast, cancelToast,
                            useNotificationBar, callbackContext, cordova, webView);
                    // Store ID: ATT! GLobal Here!
                    //DownloadControllerGlobals.ids.add(downloader_id_str);
                    downloading_ids.add(downloader_id_str);

                    // Start Download
                    downloadFile.run();
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.ERROR);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR));
                }
            }
        });
        return true;
    } else if (action.equals("cancel")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    JSONObject params = args.getJSONObject(0);
                    String cancelID = params.has("id") ? params.getString("id") : null;
                    Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID);

                    if (cancelID == null) {
                        callbackContext
                                .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "ID not found"));
                    }
                    //if (DownloadControllerGlobals.ids.indexOf(cancelID) == -1) {
                    if (!downloading_ids.isId(cancelID)) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR,
                                "The id has no download associated"));
                    } else {
                        //DownloadControllerGlobals.ids.remove(DownloadControllerGlobals.ids.indexOf(cancelID));
                        downloading_ids.del(cancelID);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                }
            }
        });
        return true;
    } else if (action.equals("isdownloading")) {
        cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                try {
                    JSONObject params = args.getJSONObject(0);
                    String cancelID = params.has("id") ? params.getString("id") : null;
                    Log.d("PhoneGapLog", "Este es el ID que me llega para cancelar: " + cancelID);

                    if (cancelID == null) {
                        callbackContext.sendPluginResult(
                                new PluginResult(PluginResult.Status.ERROR, "Error checking id"));
                    }
                    if (!downloading_ids.isId(cancelID)) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, false));
                    } else {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, true));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Log.e("PhoneGapLog",
                            "DownloaderMaganager Plugin: Error: " + PluginResult.Status.JSON_EXCEPTION);
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
                }
            }
        });
        return true;
    } else {
        Log.e("PhoneGapLog", "Downloader Plugin: Error: " + PluginResult.Status.INVALID_ACTION);
        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION));
        return false;
    }
}

From source file:net.dv8tion.jda.core.handle.UserUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    SelfUserImpl self = (SelfUserImpl) api.getSelfUser();

    String name = content.getString("username");
    String discriminator = content.getString("discriminator");
    String avatarId = !content.isNull("avatar") ? content.getString("avatar") : null;
    Boolean verified = content.has("verified") ? content.getBoolean("verified") : null;
    Boolean mfaEnabled = content.has("mfa_enabled") ? content.getBoolean("mfa_enabled") : null;

    //Client only
    String email = !content.isNull("email") ? content.getString("email") : null;

    if (!Objects.equals(name, self.getName()) || !Objects.equals(discriminator, self.getDiscriminator())) {
        String oldName = self.getName();
        String oldDiscriminator = self.getDiscriminator();
        self.setName(name);//from w  w  w. j a v  a  2 s  .  c o  m
        self.setDiscriminator(discriminator);
        api.getEventManager().handle(new SelfUpdateNameEvent(api, responseNumber, oldName, oldDiscriminator));
    }
    if (!Objects.equals(avatarId, self.getAvatarId())) {
        String oldAvatarId = self.getAvatarId();
        self.setAvatarId(avatarId);
        api.getEventManager().handle(new SelfUpdateAvatarEvent(api, responseNumber, oldAvatarId));
    }
    if (verified != null && verified != self.isVerified()) {
        boolean wasVerified = self.isVerified();
        self.setVerified(verified);
        api.getEventManager().handle(new SelfUpdateVerifiedEvent(api, responseNumber, wasVerified));
    }
    if (mfaEnabled != null && mfaEnabled != self.isMfaEnabled()) {
        boolean wasMfaEnabled = self.isMfaEnabled();
        self.setMfaEnabled(mfaEnabled);
        api.getEventManager().handle(new SelfUpdateMFAEvent(api, responseNumber, wasMfaEnabled));
    }
    if (api.getAccountType() == AccountType.CLIENT && !Objects.equals(email, self.getEmail())) {
        String oldEmail = self.getEmail();
        self.setEmail(email);
        api.getEventManager().handle(new SelfUpdateEmailEvent(api, responseNumber, oldEmail));
    }

    return null;
}