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:org.mozilla.gecko.gfx.GeckoSoftwareLayerClient.java

public void handleMessage(String event, JSONObject message) {
    if ("Viewport:UpdateAndDraw".equals(event)) {
        mUpdateViewportOnEndDraw = true;

        // Redraw everything.
        Rect rect = new Rect(0, 0, mBufferSize.width, mBufferSize.height);
        GeckoAppShell.sendEventToGecko(GeckoEvent.createDrawEvent(rect));
    } else if ("Viewport:UpdateLater".equals(event)) {
        mUpdateViewportOnEndDraw = true;
    } else if ("Checkerboard:Toggle".equals(event)) {
        try {/*from  w w  w . ja  v  a  2s  .com*/
            boolean showChecks = message.getBoolean("value");
            LayerController controller = getLayerController();
            controller.setCheckerboardShowChecks(showChecks);
            Log.i(LOGTAG, "Showing checks: " + showChecks);
        } catch (JSONException ex) {
            Log.e(LOGTAG, "Error decoding JSON", ex);
        }
    }
}

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

public void drawReview() throws Exception {
    String query = "func=beaconreview" + "&buid=" + buid;
    DBConnector conn = new DBConnector(query);
    conn.start();//from w ww .  j a va  2  s  .  co m
    conn.join();
    JSONObject jsonResult = conn.getResult();
    boolean result = jsonResult.getBoolean("result");

    if (!result) {
        Toast.makeText(this, "This store is not beacon store", Toast.LENGTH_SHORT).show();
        finish();
        return;
    }

    JSONObject json = jsonResult.getJSONArray("values").getJSONObject(0);

    sname = json.getString("SNAME");
    addr = json.getString("ADDR");
    license = json.getString("LICENSE#");

    ((TextViewPlus) findViewById(R.id.review_title)).setText(sname);
    ((TextViewPlus) findViewById(R.id.review_address)).setText(addr);
}

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

public void reviewClick(View view) {
    if (view.getId() == R.id.review_submit) {
        String note = ((EditTextPlus) findViewById(R.id.review_text)).getText().toString();
        float grade = ((RatingBar) findViewById(R.id.review_grade)).getRating();

        String query = "func=submitreview" + "&license=" + license + "&cid=" + cid + "&note=" + note + "&grade="
                + grade;/*from ww w  .  j av a 2s  .co  m*/
        DBConnector conn = new DBConnector(query);
        conn.start();

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

            if (!result) {
                Toast.makeText(this, "Submit Error", Toast.LENGTH_SHORT).show();
                setResult(0, new Intent());
                finish();
                return;
            }
            Toast.makeText(this, "Thank you for your opinion", Toast.LENGTH_SHORT).show();
            setResult(1, new Intent());
            finish();
        } catch (Exception e) {
        }
    }
}

From source file:com.mjhram.ttaxi.login_register.LoginActivity.java

/**
 * function to verify login details in mysql db
 * *///w  w  w.j  a  v  a 2  s  .c  om
private void checkLogin(final String name, final String password) {
    // Tag used to cancel the request
    String tag_string_req = "req_login";

    pDialog.setMessage(getString(R.string.loginDlgMsgUpdating));
    showDialog();

    StringRequest strReq = new StringRequest(Method.POST, AppConfig.URL_REGISTER,
            new Response.Listener<String>() {

                @Override
                public void onResponse(String response) {
                    Log.d(TAG, "Login Response: " + response);
                    hideDialog();

                    try {
                        JSONObject jObj = new JSONObject(response);
                        boolean error = jObj.getBoolean("error");

                        // Check for error node in json
                        if (!error) {
                            // user successfully logged in
                            // Create login session
                            String uid = jObj.getString("uid");

                            JSONObject user = jObj.getJSONObject("user");
                            String name = user.getString("name");
                            String email = user.getString("email");
                            String imageId = user.getString("image_id");
                            String phone = user.getString("phone");
                            int licenseState = user.getInt("licenseState");
                            //String created_at = user.getString("created_at");
                            switch (licenseState) {
                            case 1: //license expire
                                Utilities.showExitDialog("Your license has been expired", LoginActivity.this);
                                return;
                            case 2: //other msg
                                Utilities.showExitDialog("Some error happened prevent app from continue",
                                        LoginActivity.this);
                                return;
                            }
                            AppSettings.setLogin(true, name, email, uid);
                            AppSettings.setPhone(phone);

                            AppSettings.setPhotoId(imageId);
                            AppSettings.shouldUploadRegId = false;
                            // Launch main activity
                            Intent intent = new Intent(LoginActivity.this,
                                    com.mjhram.ttaxi.GpsMainActivity.class);
                            intent.putExtra(Constants.KEY_UID, AppSettings.getUid());
                            intent.putExtra(Constants.KEY_EMAIL, AppSettings.getEmail());
                            startActivity(intent);
                            finish();
                        } else {
                            // Error in login. Get the error message
                            //String errorMsg = jObj.getString("error_msg");
                            int errorno = jObj.getInt("error_no");
                            String errorMsg = phpErrorMsgs.msgMap.get(errorno);
                            Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show();
                        }
                    } catch (JSONException e) {
                        // JSON error
                        e.printStackTrace();
                    }

                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.e(TAG, "Login Error: " + error.getMessage());
                    Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
                    hideDialog();
                }
            }) {

        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("tag", "login");
            params.put("name", name);
            params.put("password", password);
            params.put("regId", AppSettings.regId);
            return params;
        }

    };

    // Adding request to request queue
    AppSettings tmp = AppSettings.getInstance();
    tmp.addToRequestQueue(strReq, tag_string_req);
}

From source file:org.mozilla.gecko.ui.SubdocumentScrollHelper.java

public void handleMessage(final String event, final JSONObject message) {
    // this comes in on the gecko thread; hand off the handling to the UI thread
    mUiHandler.post(new Runnable() {
        public void run() {
            Log.i(LOGTAG, "Got message: " + event);
            try {
                if (MESSAGE_PANNING_OVERRIDE.equals(event)) {
                    mOverridePanning = true;
                    mOverrideScrollAck = true;
                    mOverrideScrollPending = false;
                    mScrollSucceeded = true;
                } else if (MESSAGE_CANCEL_OVERRIDE.equals(event)) {
                    mOverridePanning = false;
                } else if (MESSAGE_SCROLL_ACK.equals(event)) {
                    mOverrideScrollAck = true;
                    mScrollSucceeded = message.getBoolean("scrolled");
                    if (mOverridePanning && mOverrideScrollPending) {
                        scrollBy(mPanZoomController.getDisplacement());
                    }/* w w  w .j ava 2  s.com*/
                }
            } catch (Exception e) {
                Log.e(LOGTAG, "Exception handling message", e);
            }
        }
    });
}

From source file:com.f16gaming.pathofexilestatistics.PoeEntry.java

public static PoeEntry[] getEntriesFromJSONString(String jsonData) throws JSONException {
    JSONObject root = (JSONObject) new JSONTokener(jsonData).nextValue();
    JSONObject ladder = root.getJSONObject("ladder");
    JSONArray entries = ladder.getJSONArray("entries");
    int length = entries.length();
    PoeEntry[] result = new PoeEntry[length];
    for (int i = 0; i < length; i++) {
        JSONObject entry = entries.getJSONObject(i);
        String account = entry.getJSONObject("account").getString("name");
        int rank = entry.getInt("rank");
        JSONObject character = entry.getJSONObject("character");
        String name = character.getString("name");
        int level = character.getInt("level");
        boolean online = entry.getBoolean("online");
        String className = character.getString("class");
        long experience = character.getLong("experience");
        PoeEntry poeEntry = new PoeEntry(account, rank, name, level, online, className, experience);
        result[i] = poeEntry;/*from  w  w  w . java 2  s.co  m*/
    }
    return result;
}

From source file:com.google.blockly.model.BlockFactory.java

/**
 * Generate a {@link Block} from JSON, including all inputs and fields within the block.
 *
 * @param type The type id of the block.
 * @param json The JSON to generate the block from.
 *
 * @return The generated Block./*w w w  .  j  ava2s.co m*/
 * @throws BlockLoadingException if the json is malformed.
 */
public Block fromJson(String type, JSONObject json) throws BlockLoadingException {
    if (TextUtils.isEmpty(type)) {
        throw new IllegalArgumentException("Block type may not be null or empty.");
    }
    if (json == null) {
        throw new IllegalArgumentException("Json may not be null.");
    }
    Block.Builder builder = new Block.Builder(type);

    if (json.has("output") && json.has("previousStatement")) {
        throw new BlockLoadingException("Block cannot have both an output and a previous statement.");
    }

    // Parse any connections that are present.
    if (json.has("output")) {
        String[] checks = Input.getChecksFromJson(json, "output");
        Connection output = new Connection(Connection.CONNECTION_TYPE_OUTPUT, checks);
        builder.setOutput(output);
    } else if (json.has("previousStatement")) {
        String[] checks = Input.getChecksFromJson(json, "previousStatement");
        Connection previous = new Connection(Connection.CONNECTION_TYPE_PREVIOUS, checks);
        builder.setPrevious(previous);
    }
    // A block can have either an output connection or previous connection, but it can always
    // have a next connection.
    if (json.has("nextStatement")) {
        String[] checks = Input.getChecksFromJson(json, "nextStatement");
        Connection next = new Connection(Connection.CONNECTION_TYPE_NEXT, checks);
        builder.setNext(next);
    }
    if (json.has("inputsInline")) {
        try {
            builder.setInputsInline(json.getBoolean("inputsInline"));
        } catch (JSONException e) {
            // Do nothing and it will remain false.
        }
    }

    int blockColor = ColorUtils.DEFAULT_BLOCK_COLOR;
    if (json.has("colour")) {
        try {
            String colourString = json.getString("colour");
            blockColor = ColorUtils.parseColor(colourString, TEMP_IO_THREAD_FLOAT_ARRAY,
                    ColorUtils.DEFAULT_BLOCK_COLOR);
        } catch (JSONException e) {
            // Won't get here. Checked above.
        }
    }
    builder.setColor(blockColor);

    ArrayList<Input> inputs = new ArrayList<>();
    ArrayList<Field> fields = new ArrayList<>();
    for (int i = 0;; i++) {
        String messageKey = "message" + i;
        String argsKey = "args" + i;
        String lastDummyAlignKey = "lastDummyAlign" + i;
        if (!json.has(messageKey)) {
            break;
        }
        String message = json.optString(messageKey);
        JSONArray args = json.optJSONArray(argsKey);
        if (args == null) {
            // If there's no args for this message use an empty array.
            args = new JSONArray();
        }

        if (message.matches("^%[a-zA-Z][a-zA-Z_0-9]*$")) {
            // TODO(#83): load the message from resources.
        }
        // Split on all argument indices of the form "%N" where N is a number from 1 to
        // the number of args without removing them.
        List<String> tokens = Block.tokenizeMessage(message);
        int indexCount = 0;
        // Indices start at 1, make the array 1 bigger so we don't have to offset things
        boolean[] seenIndices = new boolean[args.length() + 1];

        for (String token : tokens) {
            // Check if this token is an argument index of the form "%N"
            if (token.matches("^%\\d+$")) {
                int index = Integer.parseInt(token.substring(1));
                if (index < 1 || index > args.length()) {
                    throw new BlockLoadingException("Message index " + index + " is out of range.");
                }
                if (seenIndices[index]) {
                    throw new BlockLoadingException(("Message index " + index + " is duplicated"));
                }
                seenIndices[index] = true;

                JSONObject element;
                try {
                    element = args.getJSONObject(index - 1);
                } catch (JSONException e) {
                    throw new BlockLoadingException("Error reading arg %" + index, e);
                }
                while (element != null) {
                    String elementType = element.optString("type");
                    if (TextUtils.isEmpty(elementType)) {
                        throw new BlockLoadingException("No type for arg %" + index);
                    }

                    if (Field.isFieldType(elementType)) {
                        fields.add(loadFieldFromJson(type, element));
                        break;
                    } else if (Input.isInputType(elementType)) {
                        Input input = Input.fromJson(element);
                        input.addAll(fields);
                        fields.clear();
                        inputs.add(input);
                        break;
                    } else {
                        // Try getting the fallback block if it exists
                        Log.w(TAG, "Unknown element type: " + elementType);
                        element = element.optJSONObject("alt");
                    }
                }
            } else {
                token = token.replace("%%", "%").trim();
                if (!TextUtils.isEmpty(token)) {
                    fields.add(new FieldLabel(null, token));
                }
            }
        }

        // Verify every argument was used
        for (int j = 1; j < seenIndices.length; j++) {
            if (!seenIndices[j]) {
                throw new BlockLoadingException("Argument " + j + " was never used.");
            }
        }
        // If there were leftover fields we need to add a dummy input to hold them.
        if (fields.size() != 0) {
            String align = json.optString(lastDummyAlignKey, Input.ALIGN_LEFT_STRING);
            Input input = new Input.InputDummy(null, align);
            input.addAll(fields);
            inputs.add(input);
            fields.clear();
        }
    }

    builder.setInputs(inputs);
    return builder.build();
}

From source file:com.visionspace.jenkins.vstart.plugin.VSPluginPerformer.java

public Long runVstart(Long id, BuildListener listener, int timeInterval) {
    try {//from w  ww  . ja  va 2 s.  c  o  m
        //Run VSTART
        org.json.JSONObject runObject = vstObject.run(id);
        listener.getLogger().println("\nVSTART is now running!");
        Long reportId = runObject.getLong("reportId");

        //Inform which test case is running
        //listener.getLogger().println("The test case " + vstObject.getTestCase(testCaseId) + "has started.");

        //For concurrency issues
        Object obj = new Object();

        synchronized (obj) {
            long timeStamp = 0;
            org.json.JSONObject logger = null;

            do {
                logger = vstObject.getLog(reportId, timeStamp);
                JSONArray jArray = logger.getJSONArray("log");
                for (int i = 0; i < jArray.length(); i++) {
                    org.json.JSONObject json = jArray.getJSONObject(i);
                    Long eventTimeStamp = json.getLong("timestamp");
                    Date date = new Date(eventTimeStamp);
                    listener.getLogger().println(json.getString("level") + " " + /*eventTimeStamp*/date + " ["
                            + json.getString("resource") + "]" + " - " + json.getString("message") + "\n");

                    //Stores the latest timestamp
                    if (eventTimeStamp > timeStamp) {
                        timeStamp = eventTimeStamp;
                    }
                }
                if (!logger.getBoolean("finished")) {
                    obj.wait(timeInterval);
                }
            } while (!logger.getBoolean("finished"));
        }

        //inform the finishing of the test case execution
        //listener.getLogger().println("The test case " + vstObject.getTestCase(testCaseId) + "has finished its execution.");

        //Finished run
        listener.getLogger().println("VSTART run has now ended!");

        return reportId;
    } catch (URISyntaxException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getReason());
        return 0l;
    } catch (IOException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getMessage());
        return 0l;
    } catch (InterruptedException ex) {
        Logger.getLogger(VSPluginPerformer.class.getName()).log(Level.SEVERE, null, ex);
        listener.getLogger().println("Exception during the VSTART run! -> " + ex.getMessage());
        return 0l;
    }
}

From source file:com.Maestro.MidiOptions.java

public static MidiOptions fromJson(String jsonString) {
    if (jsonString == null) {
        return null;
    }/*ww w .  ja  v a  2s .  c  o  m*/
    MidiOptions options = new MidiOptions();
    try {
        JSONObject json = new JSONObject(jsonString);
        JSONArray jsonTracks = json.getJSONArray("tracks");
        options.tracks = new boolean[jsonTracks.length()];
        for (int i = 0; i < options.tracks.length; i++) {
            options.tracks[i] = jsonTracks.getBoolean(i);
        }

        JSONArray jsonMute = json.getJSONArray("mute");
        options.mute = new boolean[jsonMute.length()];
        for (int i = 0; i < options.mute.length; i++) {
            options.mute[i] = jsonMute.getBoolean(i);
        }

        JSONArray jsonInstruments = json.getJSONArray("instruments");
        options.instruments = new int[jsonInstruments.length()];
        for (int i = 0; i < options.instruments.length; i++) {
            options.instruments[i] = jsonInstruments.getInt(i);
        }

        if (json.has("time")) {
            JSONObject jsonTime = json.getJSONObject("time");
            int numer = jsonTime.getInt("numerator");
            int denom = jsonTime.getInt("denominator");
            int quarter = jsonTime.getInt("quarter");
            int tempo = jsonTime.getInt("tempo");
            options.time = new TimeSignature(numer, denom, quarter, tempo);
        }

        options.useDefaultInstruments = json.getBoolean("useDefaultInstruments");
        options.scrollVert = json.getBoolean("scrollVert");
        options.showPiano = json.getBoolean("showPiano");
        options.showLyrics = json.getBoolean("showLyrics");
        options.twoStaffs = json.getBoolean("twoStaffs");
        options.showNoteLetters = json.getInt("showNoteLetters");
        options.transpose = json.getInt("transpose");
        options.key = json.getInt("key");
        options.combineInterval = json.getInt("combineInterval");
        options.shade1Color = json.getInt("shade1Color");
        options.shade2Color = json.getInt("shade2Color");
        options.showMeasures = json.getBoolean("showMeasures");
        options.playMeasuresInLoop = json.getBoolean("playMeasuresInLoop");
        options.playMeasuresInLoopStart = json.getInt("playMeasuresInLoopStart");
        options.playMeasuresInLoopEnd = json.getInt("playMeasuresInLoopEnd");
    } catch (Exception e) {
        return null;
    }
    return options;
}

From source file:com.jsonstore.api.JSONStoreChangeOptions.java

public JSONStoreChangeOptions(JSONObject js_options) throws JSONException {
    this();//from  ww  w.  j av  a  2  s  . c  o m
    if (js_options == null)
        return;

    if (js_options.has(ADD_NEW_KEY)) {
        setAddNew(js_options.getBoolean(ADD_NEW_KEY));
    }

    if (js_options.has(MARK_DIRTY_KEY)) {
        setMarkDirty(js_options.getBoolean(MARK_DIRTY_KEY));
    }

    if (js_options.has(REPLACE_CRITERIA_KEY)) {
        JSONArray replaceCrit = js_options.optJSONArray(REPLACE_CRITERIA_KEY);
        if (replaceCrit != null) {
            for (int i = 0; i < replaceCrit.length(); i++) {
                addSearchFieldToCriteria(replaceCrit.getString(i));
            }
        }
    }

}