List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java
private void deserializeKey(String key, Bundle bundle) throws JSONException { String jsonString = cache.getString(key, "{}"); JSONObject json = new JSONObject(jsonString); String valueType = json.getString(JSON_VALUE_TYPE); if (valueType.equals(TYPE_BOOLEAN)) { bundle.putBoolean(key, json.getBoolean(JSON_VALUE)); } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); boolean[] array = new boolean[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getBoolean(i); }// ww w . j av a2 s .c om bundle.putBooleanArray(key, array); } else if (valueType.equals(TYPE_BYTE)) { bundle.putByte(key, (byte) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_BYTE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); byte[] array = new byte[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (byte) jsonArray.getInt(i); } bundle.putByteArray(key, array); } else if (valueType.equals(TYPE_SHORT)) { bundle.putShort(key, (short) json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_SHORT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); short[] array = new short[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (short) jsonArray.getInt(i); } bundle.putShortArray(key, array); } else if (valueType.equals(TYPE_INTEGER)) { bundle.putInt(key, json.getInt(JSON_VALUE)); } else if (valueType.equals(TYPE_INTEGER_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int[] array = new int[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getInt(i); } bundle.putIntArray(key, array); } else if (valueType.equals(TYPE_LONG)) { bundle.putLong(key, json.getLong(JSON_VALUE)); } else if (valueType.equals(TYPE_LONG_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); long[] array = new long[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getLong(i); } bundle.putLongArray(key, array); } else if (valueType.equals(TYPE_FLOAT)) { bundle.putFloat(key, (float) json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_FLOAT_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); float[] array = new float[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = (float) jsonArray.getDouble(i); } bundle.putFloatArray(key, array); } else if (valueType.equals(TYPE_DOUBLE)) { bundle.putDouble(key, json.getDouble(JSON_VALUE)); } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); double[] array = new double[jsonArray.length()]; for (int i = 0; i < array.length; i++) { array[i] = jsonArray.getDouble(i); } bundle.putDoubleArray(key, array); } else if (valueType.equals(TYPE_CHAR)) { String charString = json.getString(JSON_VALUE); if (charString != null && charString.length() == 1) { bundle.putChar(key, charString.charAt(0)); } } else if (valueType.equals(TYPE_CHAR_ARRAY)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); char[] array = new char[jsonArray.length()]; for (int i = 0; i < array.length; i++) { String charString = jsonArray.getString(i); if (charString != null && charString.length() == 1) { array[i] = charString.charAt(0); } } bundle.putCharArray(key, array); } else if (valueType.equals(TYPE_STRING)) { bundle.putString(key, json.getString(JSON_VALUE)); } else if (valueType.equals(TYPE_STRING_LIST)) { JSONArray jsonArray = json.getJSONArray(JSON_VALUE); int numStrings = jsonArray.length(); ArrayList<String> stringList = new ArrayList<String>(numStrings); for (int i = 0; i < numStrings; i++) { Object jsonStringValue = jsonArray.get(i); stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue); } bundle.putStringArrayList(key, stringList); } else if (valueType.equals(TYPE_ENUM)) { try { String enumType = json.getString(JSON_VALUE_ENUM_TYPE); @SuppressWarnings({ "unchecked", "rawtypes" }) Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType); @SuppressWarnings("unchecked") Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE)); bundle.putSerializable(key, enumValue); } catch (ClassNotFoundException e) { } catch (IllegalArgumentException e) { } } }
From source file:com.bruce.myrecorder.netwrapper.BaseNetWrapper.java
public JsonObjectRequest getJsonRequst() { jsonObjectRequest = new JsonObjectRequest(url, null, new Response.Listener<JSONObject>() { @Override//from w w w .j av a2 s. c o m public void onResponse(JSONObject response) { CommonUtils.showLog(response.toString()); try { if (response.getInt("flag") == 101) { resultState = true; } else { resultState = false; } responseMessage = response.getString("message"); } catch (JSONException e) { e.printStackTrace(); } doResponse.successResponse(responseMessage, resultState); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Log.e("TAG", error.getMessage(), error); doResponse.errorResponse(); } }); return jsonObjectRequest; }
From source file:pe.chalk.telegram.type.file.photo.PhotoSize.java
protected PhotoSize(final JSONObject json) { super(json);//ww w .j a va 2s . c o m this.width = json.getInt("width"); this.height = json.getInt("height"); }
From source file:com.ultramegatech.ey.UpdateService.java
/** * Add a value from a JSONObject to a ContentValues object in the appropriate data type. * /*from w w w .j av a 2 s . c om*/ * @param to * @param from * @param key The key of the entry to process * @throws JSONException */ private static void addValue(ContentValues to, JSONObject from, String key) throws JSONException { switch (Elements.getColumnType(key)) { case INTEGER: case BOOLEAN: to.put(key, from.getInt(key)); break; case REAL: to.put(key, from.getDouble(key)); break; case TEXT: to.put(key, from.getString(key)); break; } }
From source file:org.akvo.caddisfly.helper.TestConfigHelper.java
private static TestInfo loadTest(JSONObject item) { TestInfo testInfo = null;//from w w w. j a v a 2 s. c o m try { //Get the test type TestType type; if (item.has("subtype")) { switch (item.getString("subtype")) { case "liquid-chamber": type = TestType.COLORIMETRIC_LIQUID; break; case "strip": case "striptest": type = TestType.COLORIMETRIC_STRIP; break; case "sensor": type = TestType.SENSOR; break; default: return null; } } else { return null; } //Get the name for this test String name = item.getString("name"); //Load results JSONArray resultsArray = null; if (item.has("results")) { resultsArray = item.getJSONArray("results"); } //Load the dilution percentages String dilutions = "0"; if (item.has("dilutions")) { dilutions = item.getString("dilutions"); if (dilutions.isEmpty()) { dilutions = "0"; } } String[] dilutionsArray = dilutions.split(","); //Load the ranges String ranges = "0"; if (item.has("ranges")) { ranges = item.getString("ranges"); } String[] rangesArray = ranges.split(","); String[] defaultColorsArray = new String[0]; if (item.has("defaultColors")) { String defaultColors = item.getString("defaultColors"); defaultColorsArray = defaultColors.split(","); } // get uuids String uuid = item.getString(SensorConstants.UUID); testInfo = new TestInfo(name, type, rangesArray, defaultColorsArray, dilutionsArray, uuid, resultsArray); testInfo.setHueTrend(item.has("hueTrend") ? item.getInt("hueTrend") : 0); testInfo.setDeviceId(item.has("deviceId") ? item.getString("deviceId") : "Unknown"); testInfo.setResponseFormat(item.has("responseFormat") ? item.getString("responseFormat") : ""); testInfo.setUseGrayScale(item.has("grayScale") && item.getBoolean("grayScale")); testInfo.setMonthsValid(item.has("monthsValid") ? item.getInt("monthsValid") : DEFAULT_MONTHS_VALID); //if calibrate not specified then default to false otherwise use specified value testInfo.setRequiresCalibration(item.has("calibrate") && item.getBoolean("calibrate")); testInfo.setIsDeprecated(item.has("deprecated") && item.getBoolean("deprecated")); } catch (JSONException e) { Timber.e(e); } return testInfo; }
From source file:pe.chalk.takoyaki.target.NaverCafe.java
public NaverCafe(JSONObject properties) { super(properties.getString("prefix"), properties.getLong("interval")); this.getFilters() .addAll(Utils.buildStream(String.class, properties.getJSONArray("filters")).map(filterName -> { switch (filterName) { case ArticleFilter.NAME: return new ArticleFilter(this); case CommentaryFilter.NAME: return new CommentaryFilter(this); case VisitationFilter.NAME: return new VisitationFilter(this); default: return null; }/*from w w w. j av a2s . c o m*/ }).filter(filter -> filter != null).collect(Collectors.toList())); this.staff = new Staff(this.getLogger(), properties.getInt("timeout"), properties.getJSONObject("naverAccount")); this.address = properties.getString("address"); this.contentUrl = String.format(STRING_CONTENT, this.getAddress()); try { Document contentDocument = Jsoup.parse(this.getStaff().parse(this.contentUrl)); this.setName(contentDocument.select("h1.d-none").text()); Matcher clubIdMatcher = NaverCafe.PATTERN_CLUB_ID .matcher(contentDocument.head().select("script:not([type]):not([src])").first().html()); if (!clubIdMatcher.find()) { throw new IllegalArgumentException(" ID ? : " + this.getName()); } this.clubId = Integer.parseInt(clubIdMatcher.group(1)); this.menus = contentDocument.select("a[id^=menuLink]").stream() .map(element -> new Menu(this, Integer.parseInt(element.id().substring(8)), element.text())) .collect(Collectors.toList()); this.articleUrl = String.format(STRING_ARTICLE, this.getClubId()); Files.write(Paths.get("Takoyaki-menus-" + this.getAddress() + ".log"), this.getMenus().stream().map(Menu::toString).collect(Collectors.toList()), StandardCharsets.UTF_8); } catch (IOException | JSONException e) { String errorMessage = "?? : " + e.getClass().getName() + ": " + e.getMessage(); this.getLogger().error(errorMessage); throw new IllegalStateException(errorMessage); } }
From source file:com.hichinaschool.flashcards.anki.CardEditor.java
@Override protected Dialog onCreateDialog(int id) { StyledDialog dialog = null;/*ww w .j a va 2s.c o m*/ Resources res = getResources(); StyledDialog.Builder builder = new StyledDialog.Builder(this); switch (id) { case DIALOG_TAGS_SELECT: builder.setTitle(R.string.card_details_tags); builder.setPositiveButton(res.getString(R.string.select), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (mAddNote) { try { JSONArray ja = new JSONArray(); for (String t : selectedTags) { ja.put(t); } mCol.getModels().current().put("tags", ja); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } mEditorNote.setTags(selectedTags); } mCurrentTags = selectedTags; updateTags(); } }); builder.setNegativeButton(res.getString(R.string.cancel), null); mNewTagEditText = (EditText) new EditText(this); mNewTagEditText.setHint(R.string.add_new_tag); InputFilter filter = new InputFilter() { public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { if (source.charAt(i) == ' ' || source.charAt(i) == ',') { return ""; } } return null; } }; mNewTagEditText.setFilters(new InputFilter[] { filter }); ImageView mAddTextButton = new ImageView(this); mAddTextButton.setImageResource(R.drawable.ic_addtag); mAddTextButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String tag = mNewTagEditText.getText().toString(); if (tag.length() != 0) { if (mEditorNote.hasTag(tag)) { mNewTagEditText.setText(""); return; } selectedTags.add(tag); actualizeTagDialog(mTagsDialog); mNewTagEditText.setText(""); } } }); FrameLayout frame = new FrameLayout(this); FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.CENTER_VERTICAL); params.rightMargin = 10; mAddTextButton.setLayoutParams(params); frame.addView(mNewTagEditText); frame.addView(mAddTextButton); builder.setView(frame, false, true); dialog = builder.create(); mTagsDialog = dialog; break; case DIALOG_DECK_SELECT: ArrayList<CharSequence> dialogDeckItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogDeckIds = new ArrayList<Long>(); ArrayList<JSONObject> decks = mCol.getDecks().all(); Collections.sort(decks, new JSONNameComparator()); builder.setTitle(R.string.deck); for (JSONObject d : decks) { try { if (d.getInt("dyn") == 0) { dialogDeckItems.add(d.getString("name")); dialogDeckIds.add(d.getLong("id")); } } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items = new String[dialogDeckItems.size()]; dialogDeckItems.toArray(items); builder.setItems(items, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long newId = dialogDeckIds.get(item); if (mCurrentDid != newId) { if (mAddNote) { try { // TODO: mEditorNote.setDid(newId); mEditorNote.model().put("did", newId); mCol.getModels().setChanged(); } catch (JSONException e) { throw new RuntimeException(e); } } mCurrentDid = newId; updateDeck(); } } }); dialog = builder.create(); mDeckSelectDialog = dialog; break; case DIALOG_MODEL_SELECT: ArrayList<CharSequence> dialogItems = new ArrayList<CharSequence>(); // Use this array to know which ID is associated with each // Item(name) final ArrayList<Long> dialogIds = new ArrayList<Long>(); ArrayList<JSONObject> models = mCol.getModels().all(); Collections.sort(models, new JSONNameComparator()); builder.setTitle(R.string.note_type); for (JSONObject m : models) { try { dialogItems.add(m.getString("name")); dialogIds.add(m.getLong("id")); } catch (JSONException e) { throw new RuntimeException(e); } } // Convert to Array String[] items2 = new String[dialogItems.size()]; dialogItems.toArray(items2); builder.setItems(items2, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { long oldModelId; try { oldModelId = mCol.getModels().current().getLong("id"); } catch (JSONException e) { throw new RuntimeException(e); } long newId = dialogIds.get(item); if (oldModelId != newId) { mCol.getModels().setCurrent(mCol.getModels().get(newId)); JSONObject cdeck = mCol.getDecks().current(); try { cdeck.put("mid", newId); } catch (JSONException e) { throw new RuntimeException(e); } mCol.getDecks().save(cdeck); int size = mEditFields.size(); String[] oldValues = new String[size]; for (int i = 0; i < size; i++) { oldValues[i] = mEditFields.get(i).getText().toString(); } setNote(); resetEditFields(oldValues); mTimerHandler.removeCallbacks(checkDuplicatesRunnable); duplicateCheck(false); } } }); dialog = builder.create(); break; case DIALOG_RESET_CARD: builder.setTitle(res.getString(R.string.reset_card_dialog_title)); builder.setMessage(res.getString(R.string.reset_card_dialog_message)); builder.setPositiveButton(res.getString(R.string.yes), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // for (long cardId : // mDeck.getCardsFromFactId(mEditorNote.getId())) { // mDeck.cardFromId(cardId).resetCard(); // } // mDeck.reset(); // setResult(Reviewer.RESULT_EDIT_CARD_RESET); // mCardReset = true; // Themes.showThemedToast(CardEditor.this, // getResources().getString( // R.string.reset_card_dialog_confirmation), true); } }); builder.setNegativeButton(res.getString(R.string.no), null); builder.setCancelable(true); dialog = builder.create(); break; case DIALOG_INTENT_INFORMATION: dialog = createDialogIntentInformation(builder, res); } return dialog; }
From source file:net.zionsoft.obadiah.model.notification.PushNotificationHandler.java
private boolean prepareForVerse(NotificationCompat.Builder builder, String messageType, String messageAttrs) { final SharedPreferences preferences = getSharedPreferences(Constants.PREF_NAME, Context.MODE_PRIVATE); final String translationShortName = preferences.getString(Constants.PREF_KEY_LAST_READ_TRANSLATION, null); if (translationShortName == null) { return false; }//from ww w. j av a2 s . co m SQLiteDatabase db = null; try { final JSONObject jsonObject = new JSONObject(messageAttrs); final int bookIndex = jsonObject.getInt("book"); final int chapterIndex = jsonObject.getInt("chapter"); final int verseIndex = jsonObject.getInt("verse"); db = mDatabaseHelper.openDatabase(); final String bookName = TranslationHelper.getBookNames(db, translationShortName).get(bookIndex); final Verse verse = TranslationHelper.getVerse(db, translationShortName, bookName, bookIndex, chapterIndex, verseIndex); if (verse == null) { throw new IllegalArgumentException("Invalid push message attrs: " + messageAttrs); } builder.setContentIntent(PendingIntent.getActivity(this, 0, BookSelectionActivity.newStartReorderToTopIntent(this, messageType, bookIndex, chapterIndex, verseIndex), PendingIntent.FLAG_UPDATE_CURRENT)) .setContentTitle(String.format("%s, %d:%d", bookName, chapterIndex + 1, verseIndex + 1)) .setContentText(verse.verseText) .setStyle(new NotificationCompat.BigTextStyle().bigText(verse.verseText)); } catch (Exception e) { Crashlytics.logException(e); return false; } finally { if (db != null) { mDatabaseHelper.closeDatabase(); } } return true; }
From source file:com.tedx.logics.AttendeeLogic.java
public static Bundle GetCurrentDancers(Resources res, String EventUniqueId) { String Action = "GetAttendeeByUniqueId"; JSONObject requestJSONParameters = new JSONObject(); try {// w w w . j a va 2 s . co m requestJSONParameters.put("EventId", Integer.valueOf(res.getString(R.string.eventId))); requestJSONParameters.put("EventUniqueId", EventUniqueId); } catch (JSONException e) { // TODO Auto-generated catch block return null; } String URL = res.getString(R.string.WebServiceAddress) + Action; JSONObject responseJSON = WebServices.SendHttpPost(URL, requestJSONParameters); if (responseJSON != null) { try { if (responseJSON.getBoolean("IsSuccessful")) { Bundle ret = new Bundle(); ret.putInt("AttendeeId", responseJSON.getInt("AttendeeId")); ret.putString("FirstName", responseJSON.getString("FirstName")); ret.putString("LastName", responseJSON.getString("LastName")); ret.putString("ContactNumber", responseJSON.getString("ContactNumber")); ret.putString("Website", responseJSON.getString("Website")); ret.putString("Email", responseJSON.getString("Email")); ret.putString("Facebook", responseJSON.getString("Facebook")); ret.putString("Twitter", responseJSON.getString("Twitter")); ret.putString("Description", responseJSON.getString("Description")); return ret; } else return null; } catch (JSONException e) { // TODO Auto-generated catch block return null; } } else return null; }
From source file:de.quadrillenschule.azocamsyncd.astromode_old.PhotoProjectProfile.java
public void fromJSONProfile(String jsonProfile, PhotoProject project) { photoSeries = new LinkedList<>(); try {/* w ww.j a v a2 s . c o m*/ JSONObject jsa = new JSONObject(jsonProfile); ReceivePhotoSerie[] psArray = new ReceivePhotoSerie[jsa.names().length()]; for (int i = 0; i < jsa.names().length(); i++) { JSONObject seriesArray = (JSONObject) jsa.get(jsa.names().getString(i)); ReceivePhotoSerie ps = new ReceivePhotoSerie(project); ps.setName(jsa.names().get(i).toString()); ps.setNumberOfPlannedPhotos(seriesArray.getInt(Columns.NUMBER_OF_PLANNED_PHOTOS.name())); ps.setExposureTimeInMs(seriesArray.getLong(Columns.EXPOSURE_TIME.name())); psArray[seriesArray.getInt("ORDER_NUMBER")] = ps; } for (ReceivePhotoSerie ps : psArray) { photoSeries.add(ps); } } catch (JSONException ex) { Logger.getLogger(PhotoProjectProfile.class.getName()).log(Level.SEVERE, null, ex); } }