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:fr.qinder.tools.JSON.java

/**
 * Get value of the key from a JSONObject. If the key not exists in the
 * JSONObject, defValue is return./*from  w w w .j  ava  2s .c o m*/
 * 
 * @param obj
 *            JSONObject for getting the value
 * @param key
 *            String of the key
 * @param defValue
 *            Default value if key not exists
 * @return The value if key exist, defValue else
 */
@SuppressWarnings("unchecked")
private static <T> T getValue(JSONObject obj, String key, T defValue) throws JSONException {
    T res = defValue;
    if (defValue instanceof Double) {
        res = (T) ((Double) obj.getDouble(key));
    } else if (defValue instanceof Integer) {
        res = (T) ((Integer) obj.getInt(key));
    } else if (defValue instanceof Boolean) {
        res = (T) ((Boolean) obj.getBoolean(key));
    } else if (defValue instanceof Long) {
        res = (T) ((Long) obj.getLong(key));
    } else if (defValue instanceof String) {
        res = (T) obj.getString(key);
    } else if (defValue instanceof JSONObject) {
        res = (T) obj.getJSONObject(key);
    } else if (defValue instanceof JSONArray) {
        res = (T) obj.getJSONArray(key);
    }
    return res;
}

From source file:org.wso2.iot.agent.utils.CommonUtils.java

/**
 * Call EMM system app in COPE mode./*from  w ww  . j  ava2s .c o m*/
 * @param context - Application context.
 * @param operation - Operation code.
 * @param command - Shell command to be executed.
 * @param appUri - App package/APK URI when an app operation executed.
 */
public static void callSystemApp(Context context, String operation, String command, String appUri) {
    if (Constants.SYSTEM_APP_ENABLED) {
        Intent intent = new Intent(Constants.SYSTEM_APP_SERVICE_START_ACTION);
        Intent explicitIntent = createExplicitFromImplicitIntent(context, intent);
        if (explicitIntent != null) {
            intent = explicitIntent;
        }
        intent.putExtra(Constants.OPERATION_CODE, operation);
        intent.setPackage(Constants.AGENT_PACKAGE);

        if (appUri != null) {
            intent.putExtra("appUri", appUri);
        }

        if (command != null) {
            if (Constants.Operation.UPGRADE_FIRMWARE.equals(operation)) {
                try {
                    JSONObject upgradeData = new JSONObject(command);
                    if (upgradeData
                            .isNull(context.getResources().getString(R.string.firmware_upgrade_automatic_retry))
                            && Preference.hasPreferenceKey(context,
                                    context.getResources().getString(R.string.is_automatic_firmware_upgrade))) {
                        boolean isFirmwareUpgradeAutoRetry = Preference.getBoolean(context,
                                context.getResources().getString(R.string.is_automatic_firmware_upgrade));
                        upgradeData.put(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                isFirmwareUpgradeAutoRetry);
                        command = upgradeData.toString();
                        Log.d(TAG, "Updated payload: " + command);
                    } else if (!upgradeData.isNull(
                            context.getResources().getString(R.string.firmware_upgrade_automatic_retry))) {
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.is_automatic_firmware_upgrade),
                                upgradeData.getBoolean(context.getResources()
                                        .getString(R.string.firmware_upgrade_automatic_retry)));
                    } else {
                        upgradeData.put(
                                context.getResources().getString(R.string.firmware_upgrade_automatic_retry),
                                true);
                        Preference.putBoolean(context,
                                context.getResources().getString(R.string.is_automatic_firmware_upgrade), true);
                        Log.d(TAG, "Updated payload: " + command);
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Could not parse Firmware upgrade operation", e);
                }
                intent.putExtra("operationId", Preference.getInt(context, "firmwareOperationId"));
            }
            intent.putExtra("command", command);
        }
        context.startServiceAsUser(intent, android.os.Process.myUserHandle());
    } else {
        Log.e(TAG, "System app not enabled.");
    }
}

From source file:com.dattasmoon.pebble.plugin.IgnorePreference.java

@Override
protected void onBindDialogView(View view) {

    btnAdd = (Button) view.findViewById(R.id.btnAdd);
    etMatch = (EditText) view.findViewById(R.id.etMatch);
    chkRawRegex = (CheckBox) view.findViewById(R.id.chkRawRegex);
    chkCaseInsensitive = (CheckBox) view.findViewById(R.id.chkCaseInsensitive);
    actvApplications = (AutoCompleteTextView) view.findViewById(R.id.actvApplications);

    spnApplications = (Spinner) view.findViewById(R.id.spnApplications);
    spnMode = (Spinner) view.findViewById(R.id.spnMode);
    lvIgnore = (ListView) view.findViewById(R.id.lvIgnore);
    lvIgnore.setAdapter(arrayAdapter);/*  w w  w  .j ava  2  s . co  m*/
    lvIgnore.setEmptyView(view.findViewById(android.R.id.empty));
    new LoadAppsTask().execute();

    lvIgnore.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
        @Override
        public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
            AdapterView.AdapterContextMenuInfo contextInfo = (AdapterView.AdapterContextMenuInfo) menuInfo;
            int position = contextInfo.position;
            long id = contextInfo.id;
            // the child view who's info we're viewing (should be equal to v)
            final View v = contextInfo.targetView;
            MenuInflater inflater = new MenuInflater(getContext());
            inflater.inflate(R.menu.preference_ignore_context, menu);

            //we have to do this mess because DialogPreference doesn't allow for onMenuItemSelected or onOptionsItemSelected. Bleh
            menu.findItem(R.id.btnEdit).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    final int arrayPosition = (Integer) v.getTag();
                    final String text = ((TextView) v.findViewById(R.id.tvItem)).getText().toString();
                    JSONArray temp = new JSONArray();
                    for (int i = 0; i < arrayAdapter.getJSONArray().length(); i++) {
                        try {
                            JSONObject ignore = arrayAdapter.getJSONArray().getJSONObject(i);
                            if (i == arrayPosition) {
                                etMatch.setText(ignore.getString("match"));
                                chkRawRegex.setChecked(ignore.getBoolean("raw"));
                                chkCaseInsensitive.setChecked(ignore.optBoolean("insensitive", true));
                                String app = ignore.getString("app");
                                if (app == "-1") {
                                    actvApplications.setText(getContext().getString(R.string.ignore_any));
                                } else {
                                    actvApplications.setText(app);
                                }
                                boolean exclude = ignore.optBoolean("exclude", true);
                                if (exclude) {
                                    spnMode.setSelection(Constants.IgnoreMode.EXCLUDE.ordinal());
                                } else {
                                    spnMode.setSelection(Constants.IgnoreMode.INCLUDE.ordinal());
                                }
                                continue;
                            }

                            temp.put(ignore);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    arrayAdapter.setJSONArray(temp);

                    arrayAdapter.notifyDataSetChanged();
                    return true;
                }
            });
            menu.findItem(R.id.btnDelete).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());

                    final int arrayPosition = (Integer) v.getTag();
                    final String text = ((TextView) v.findViewById(R.id.tvItem)).getText().toString();
                    builder.setMessage(getContext().getResources().getString(R.string.confirm_delete) + " '"
                            + text + "' ?")
                            .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    JSONArray temp = new JSONArray();
                                    for (int i = 0; i < arrayAdapter.getJSONArray().length(); i++) {
                                        if (i == arrayPosition) {
                                            continue;
                                        }
                                        try {
                                            temp.put(arrayAdapter.getJSONArray().getJSONObject(i));
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                    arrayAdapter.setJSONArray(temp);

                                    arrayAdapter.notifyDataSetChanged();
                                }
                            }).setNegativeButton(R.string.decline, new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    // User cancelled the dialog
                                }
                            });
                    builder.create().show();
                    return true;
                }
            });
        }
    });
    btnAdd.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            JSONObject item = new JSONObject();
            try {
                item.put("match", etMatch.getText().toString());
                item.put("raw", chkRawRegex.isChecked());
                item.put("insensitive", chkCaseInsensitive.isChecked());
                if (actvApplications.getText().toString()
                        .equalsIgnoreCase(getContext().getString(R.string.ignore_any))) {
                    item.put("app", "-1");
                } else {
                    item.put("app", actvApplications.getText().toString());
                }
                if (spnMode.getSelectedItemPosition() == Constants.IgnoreMode.INCLUDE.ordinal()) {
                    item.put("exclude", false);
                } else {
                    item.put("exclude", true);
                }
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Item is: " + item.toString());
                }
                arrayAdapter.getJSONArray().put(item);
                etMatch.setText("");
                arrayAdapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    });
    actvApplications.setText(getContext().getString(R.string.ignore_any));
    actvApplications.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            actvApplications.showDropDown();
        }
    });
    actvApplications.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ApplicationInfo pkg = (ApplicationInfo) parent.getItemAtPosition(position);
            if (pkg == null) {
                actvApplications.setText(getContext().getString(R.string.ignore_any));
            } else {
                actvApplications.setText(pkg.packageName);
            }
        }
    });
    actvApplications.setOnFocusChangeListener(new View.OnFocusChangeListener() {
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {
                actvApplications.showDropDown();
            } else {
                if (actvApplications.getText().length() == 0) {
                    actvApplications.setText(getContext().getString(R.string.ignore_any));
                }
            }
        }
    });
    super.onBindDialogView(view);

}

From source file:com.nextgis.maplib.datasource.ngw.Resource.java

public Resource(JSONObject json, Connection connection) {

    mConnection = connection;/* w  ww . j a v  a  2s  .c  o  m*/
    try {
        JSONObject JSONResource = json.getJSONObject("resource");

        mHasChildren = JSONResource.getBoolean("children");
        if (JSONResource.has("description"))
            mDescription = JSONResource.getString("description");

        mName = JSONResource.getString("display_name");
        mRemoteId = JSONResource.getLong("id");
        mType = mConnection.getType(JSONResource.getString("cls"));

        if (JSONResource.has("keyname"))
            mKeyName = JSONResource.getString("keyname");
        if (JSONResource.has("owner_user")) {
            JSONObject jsonObjectOwnerUser = JSONResource.getJSONObject("owner_user");
            if (jsonObjectOwnerUser.has("id"))
                mOwnerId = jsonObjectOwnerUser.getLong("id");
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    mId = Connections.getNewId();
}

From source file:edu.umass.cs.gigapaxos.paxospackets.RequestPacket.java

public RequestPacket(JSONObject json) throws JSONException {
    super(json);/*  ww  w  .  ja  v  a 2  s.co m*/
    this.packetType = PaxosPacketType.REQUEST;
    this.stop = json.optBoolean(Keys.STOP.toString());
    this.requestID = json.getLong(Keys.QID.toString());
    this.requestValue = json.getString(Keys.QV.toString());

    this.responseValue = json.has(Keys.RV.toString()) ? json.getString(Keys.RV.toString()) : null;
    this.entryTime = json.getLong(Keys.ET.toString());
    this.forwardCount = (json.has(Keys.NFWDS.toString()) ? json.getInt(Keys.NFWDS.toString()) : 0);
    this.forwarderID = (json.has(RequestPacket.Keys.FWDR.toString())
            ? json.getInt(RequestPacket.Keys.FWDR.toString())
            : IntegerMap.NULL_INT_NODE);
    this.debugInfo = (json.has(Keys.DBG.toString()) ? json.getString(Keys.DBG.toString()) : "");

    this.clientAddress = (json.has(Keys.CA.toString())
            ? Util.getInetSocketAddressFromString(json.getString(Keys.CA.toString()))
            : JSONNIOTransport.getSenderAddress(json));
    this.listenAddress = (json.has(Keys.LA.toString())
            ? Util.getInetSocketAddressFromString(json.getString(Keys.LA.toString()))
            : JSONNIOTransport.getReceiverAddress(json));

    this.entryReplica = json.getInt(PaxosPacket.NodeIDKeys.E.toString());
    this.shouldReturnRequestValue = json.optBoolean(Keys.QF.toString());

    // unwrap latched along batch
    JSONArray batchedJSON = json.has(Keys.BATCH.toString()) ? json.getJSONArray(Keys.BATCH.toString()) : null;
    if (batchedJSON != null && batchedJSON.length() > 0) {
        this.batched = new RequestPacket[batchedJSON.length()];
        for (int i = 0; i < batchedJSON.length(); i++) {
            this.batched[i] = new RequestPacket((JSONObject) batchedJSON.get(i)
            // new JSONObject(batchedJSON.getString(i))
            );
        }
    }

    // we remembered the original string for recalling here
    this.stringifiedSelf = json.has(Keys.STRINGIFIED.toString())
            ? (String) json.get(Keys.STRINGIFIED.toString())
            : null;

    if (json.has(Keys.BC.toString()))
        this.broadcasted = json.getBoolean(Keys.BC.toString());
    if (json.has(Keys.DIG.toString()))
        try {
            this.digest = json.getString(Keys.DIG.toString()).getBytes(CHARSET);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
}

From source file:org.dasein.cloud.tier3.Tier3.java

public JSONObject getDeploymentStatus(int requestId) throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("ENTER - " + Tier3.class.getName() + ".getDeploymentStatus()");
    }//from w  w  w.j ava 2 s  .  c  om
    try {

        APIHandler method = new APIHandler(this);
        JSONObject post = new JSONObject();
        post.put("RequestId", requestId);
        APIResponse response = method.post("Blueprint/GetDeploymentStatus/JSON", post.toString());

        if (response == null) {
            throw new CloudException("Could not retrieve server build request");
        }

        JSONObject json = response.getJSON();
        if (json.has("Success") && !json.getBoolean("Success")) {
            throw new CloudException(json.getString("Message"));
        }

        return json;

    } catch (JSONException e) {
        throw new CloudException(e);
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("EXIT - " + Tier3.class.getName() + ".getDeploymentStatus()");
        }
    }
}

From source file:com.dattasmoon.pebble.plugin.NotificationService.java

@Override
public void onAccessibilityEvent(AccessibilityEvent event) {
    // handle the prefs changing, because of how accessibility services
    // work, sharedprefsonchange listeners don't work
    if (watchFile.lastModified() > lastChange) {
        loadPrefs();//  w  w  w  .  jav  a 2s  . c  o  m
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service: Mode is: " + String.valueOf(mode.ordinal()));
    }
    // if we are off, don't do anything.
    if (mode == Mode.OFF) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Service: Mode is off, not sending any notifications");
        }
        return;
    }

    //handle quiet hours
    if (quiet_hours) {

        Calendar c = Calendar.getInstance();
        Date now = new Date(0, 0, 0, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Checking quiet hours. Now: " + now.toString() + " vs "
                    + quiet_hours_before.toString() + " and " + quiet_hours_after.toString());
        }

        if (quiet_hours_before.after(quiet_hours_after)) {
            if (now.after(quiet_hours_after) && now.before(quiet_hours_before)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, "Time is during quiet time. Returning.");
                }
                return;
            }

        } else if (now.before(quiet_hours_before) || now.after(quiet_hours_after)) {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Time is before or after the quiet hours time. Returning.");
            }
            return;
        }

    }

    // handle if they only want notifications
    if (notifications_only) {
        if (event != null) {
            Parcelable parcelable = event.getParcelableData();
            if (!(parcelable instanceof Notification)) {

                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is not a notification and notifications only is enabled. Returning.");
                }
                return;
            }
        }
    }
    if (no_ongoing_notifs) {
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            Notification notif = (Notification) parcelable;
            if ((notif.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG,
                            "Event is a notification, notification flag contains ongoing, and no ongoing notification is true. Returning.");
                }
                return;
            }
        } else {
            if (Constants.IS_LOGGABLE) {
                Log.i(Constants.LOG_TAG, "Event is not a notification.");
            }
        }
    }

    // Handle the do not disturb screen on settings
    PowerManager powMan = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
    if (Constants.IS_LOGGABLE) {
        Log.d(Constants.LOG_TAG, "NotificationService.onAccessibilityEvent: notifScreenOn=" + notifScreenOn
                + "  screen=" + powMan.isScreenOn());
    }
    if (!notifScreenOn && powMan.isScreenOn()) {
        return;
    }

    if (event == null) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Event is null. Returning.");
        }
        return;
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Event: " + event.toString());
    }

    // main logic
    PackageManager pm = getPackageManager();

    String eventPackageName;
    if (event.getPackageName() != null) {
        eventPackageName = event.getPackageName().toString();
    } else {
        eventPackageName = "";
    }
    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, "Service package list is: ");
        for (String strPackage : packages) {
            Log.i(Constants.LOG_TAG, strPackage);
        }
        Log.i(Constants.LOG_TAG, "End Service package list");
    }

    switch (mode) {
    case EXCLUDE:
        // exclude functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to exclude");
        }

        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                if (Constants.IS_LOGGABLE) {
                    Log.i(Constants.LOG_TAG, packageName + " == " + eventPackageName
                            + " which is on the exclude list. Returning.");
                }
                return;
            }
        }
        break;
    case INCLUDE:
        // include only functionality
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Mode is set to include only");
        }
        boolean found = false;
        for (String packageName : packages) {
            if (packageName.equalsIgnoreCase(eventPackageName)) {
                found = true;
                break;
            }
        }
        if (!found) {
            Log.i(Constants.LOG_TAG, eventPackageName + " was not found in the include list. Returning.");
            return;
        }
        break;
    }

    // get the title
    String title = "";
    try {
        boolean renamed = false;
        for (int i = 0; i < pkg_renames.length(); i++) {
            if (pkg_renames.getJSONObject(i).getString("pkg").equalsIgnoreCase(eventPackageName)) {
                renamed = true;
                title = pkg_renames.getJSONObject(i).getString("to");
            }
        }
        if (!renamed) {
            title = pm.getApplicationLabel(pm.getApplicationInfo(eventPackageName, 0)).toString();
        }
    } catch (NameNotFoundException e) {
        title = eventPackageName;
    } catch (JSONException e) {
        title = eventPackageName;
    }

    // get the notification text
    String notificationText = event.getText().toString();
    // strip the first and last characters which are [ and ]
    notificationText = notificationText.substring(1, notificationText.length() - 1);

    if (notification_extras) {
        if (Constants.IS_LOGGABLE) {
            Log.i(Constants.LOG_TAG, "Fetching extras from notification");
        }
        Parcelable parcelable = event.getParcelableData();
        if (parcelable instanceof Notification) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                notificationText += "\n" + getExtraBigData((Notification) parcelable, notificationText.trim());
            } else {
                notificationText += "\n" + getExtraData((Notification) parcelable, notificationText.trim());
            }

        }
    }

    // Check ignore lists
    for (int i = 0; i < ignores.length(); i++) {
        try {
            JSONObject ignore = ignores.getJSONObject(i);
            String app = ignore.getString("app");
            boolean exclude = ignore.optBoolean("exclude", true);
            boolean case_insensitive = ignore.optBoolean("insensitive", true);
            if ((!app.equals("-1")) && (!eventPackageName.equalsIgnoreCase(app))) {
                //this rule doesn't apply to all apps and this isn't the app we're looking for.
                continue;
            }
            String regex = "";
            if (case_insensitive) {
                regex += "(?i)";
            }
            if (!ignore.getBoolean("raw")) {
                regex += Pattern.quote(ignore.getString("match"));
            } else {
                regex += ignore.getString("match");
            }
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(notificationText);
            if (m.find()) {
                if (exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText + "' matches: '"
                                + regex + "' and exclude is on. Returning");
                    }
                    return;
                }
            } else {
                if (!exclude) {
                    if (Constants.IS_LOGGABLE) {
                        Log.i(Constants.LOG_TAG, "Notification text of '" + notificationText
                                + "' does not match: '" + regex + "' and include is on. Returning");
                    }
                    return;
                }

            }
        } catch (JSONException e) {
            continue;
        }
    }

    // Send the alert to Pebble

    sendToPebble(title, notificationText);

    if (Constants.IS_LOGGABLE) {
        Log.i(Constants.LOG_TAG, event.toString());
        Log.i(Constants.LOG_TAG, event.getPackageName().toString());
    }
}

From source file:com.kimbrelk.da.oauth2.struct.DeviationMetadata.java

public DeviationMetadata(JSONObject json) throws JSONException {
    mAllowsComments = json.getBoolean("allows_comments");
    mAuthor = new User(json.getJSONObject("author"));
    if (json.has("camera")) {
        mCamera = new Camera(json.getJSONObject("camera"));
    }/*from  w w w.  j a  v a 2s.c o m*/
    if (json.has("collections")) {
        JSONArray jsonCollections = json.getJSONArray("collections");
        mCollections = new SimpleFolder[jsonCollections.length()];
        for (int a = 0; a < mCollections.length; a++) {
            mCollections[a] = new SimpleFolder(jsonCollections.getJSONObject(a));
        }
    }
    mDescription = json.getString("description");
    mId = json.getString("deviationid");
    mIsFavourited = json.getBoolean("is_favourited");
    mIsWatching = json.getBoolean("is_watching");
    mLicense = json.getString("license");
    mPrintId = json.optString("printid");
    if (json.has("stats")) {
        mStats = new Stats(json.getJSONObject("stats"));
    }
    if (json.has("submission")) {
        mSubmission = new Submission(json.getJSONObject("submission"));
    }
    JSONArray jsonTags = json.getJSONArray("tags");
    mTags = new Tag[jsonTags.length()];
    for (int a = 0; a < mTags.length; a++) {
        mTags[a] = new Tag(jsonTags.getJSONObject(a));
    }
    mTitle = json.getString("title");
}

From source file:com.soomla.levelup.LevelUp.java

private static boolean resetGatesStateFromJSON(JSONObject state) {
    return resetStateFromJSON(state, "gates", new IItemStateApplier() {
        @Override/*from  w  w w .j a v a  2 s .  com*/
        public boolean applyState(String itemId, JSONObject itemValuesJSON) {
            if (itemValuesJSON.has("open")) {
                try {
                    boolean openState = itemValuesJSON.getBoolean("open");
                    GateStorage.setOpen(itemId, openState, false);
                } catch (JSONException e) {
                    SoomlaUtils.LogError(TAG,
                            "Unable to set state for gate " + itemId + ". error: " + e.getLocalizedMessage());
                    return false;
                }
            }
            return true;
        }
    });
}

From source file:com.soomla.levelup.LevelUp.java

private static boolean resetWorldsStateFromJSON(JSONObject state) {
    boolean worldsApplyState = resetStateFromJSON(state, "worlds", new IItemStateApplier() {
        @Override/*from w ww  . j  a  v  a2 s. c o  m*/
        public boolean applyState(String itemId, JSONObject itemValuesJSON) {
            try {
                if (itemValuesJSON.has("completed")) {
                    boolean completedState = itemValuesJSON.getBoolean("completed");
                    WorldStorage.setCompleted(itemId, completedState, false);
                }

                if (itemValuesJSON.has("assignedReward")) {
                    String assignedRewardId = itemValuesJSON.getString("assignedReward");
                    WorldStorage.setReward(itemId, assignedRewardId, false);
                }
            } catch (JSONException e) {
                SoomlaUtils.LogError(TAG,
                        "Unable to set state for world " + itemId + ". error: " + e.getLocalizedMessage());
                return false;
            }

            return true;
        }
    });

    boolean levelsApplyState = resetStateFromJSON(state, "levels", new IItemStateApplier() {
        @Override
        public boolean applyState(String itemId, JSONObject itemValuesJSON) {
            try {
                if (itemValuesJSON.has("started")) {
                    int timesStarted = itemValuesJSON.getInt("started");
                    LevelStorage.setTimesStarted(itemId, timesStarted);
                }

                if (itemValuesJSON.has("played")) {
                    int timesPlayed = itemValuesJSON.getInt("played");
                    LevelStorage.setTimesPlayed(itemId, timesPlayed);
                }

                if (itemValuesJSON.has("timesCompleted")) {
                    int timesCompleted = itemValuesJSON.getInt("timesCompleted");
                    LevelStorage.setTimesCompleted(itemId, timesCompleted);
                }

                if (itemValuesJSON.has("slowest")) {
                    long slowest = itemValuesJSON.getLong("slowest");
                    LevelStorage.setSlowestDurationMillis(itemId, slowest);
                }

                if (itemValuesJSON.has("fastest")) {
                    long fastest = itemValuesJSON.getLong("fastest");
                    LevelStorage.setFastestDurationMillis(itemId, fastest);
                }
            } catch (JSONException e) {
                SoomlaUtils.LogError(TAG,
                        "Unable to set state for level " + itemId + ". error: " + e.getLocalizedMessage());
                return false;
            }

            return true;
        }
    });

    return worldsApplyState && levelsApplyState;
}