List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.ionicsdk.discovery.Discovery.java
public void doIdentify(final JSONObject opts, final CallbackContext callbackContext) { new AsyncTask<Integer, Void, Void>() { @Override/*from w ww . ja v a2 s . c o m*/ protected Void doInBackground(Integer... params) { try { DatagramSocket socket = new DatagramSocket(); socket.setBroadcast(true); String data = opts.toString(); DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(), getBroadcastAddress(), opts.getInt("port")); socket.send(packet); Log.d(TAG, "Sent packet"); byte[] buf = new byte[1024]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String result = new String(buf, 0, packet.getLength()); Log.d(TAG, "Got response packet of " + packet.getLength() + " bytes: " + result); callbackContext.success(result); } catch (Exception e) { callbackContext.error(e.getMessage()); Log.e(TAG, "Exception while listening for server broadcast"); e.printStackTrace(); } return null; } }.execute(); }
From source file:com.textuality.lifesaver.Columns.java
private static void j2cvInt(JSONObject j, ContentValues cv, String key) { try {//from w w w . j a v a 2s . co m int v = j.getInt(key); cv.put(key, v); } catch (JSONException e) { } }
From source file:com.dimasdanz.kendalipintu.usermodel.UserLoadData.java
@Override protected List<UserModel> doInBackground(String... args) { List<UserModel> userList = new ArrayList<UserModel>(); List<NameValuePair> params = new ArrayList<NameValuePair>(); JSONObject json = jsonParser.makeHttpRequest(ServerUtilities.getUserListUrl(activity) + current_page, "GET", params);//from w w w .j av a 2s . c o m if (json != null) { try { if (json.getInt("response") == 1) { JSONArray userid = json.getJSONArray("userid"); JSONArray username = json.getJSONArray("username"); JSONArray userpass = json.getJSONArray("userpass"); for (int i = 0; i < userid.length(); i++) { userList.add(new UserModel(userid.get(i).toString(), username.get(i).toString(), userpass.getString(i).toString())); } return userList; } else { return null; } } catch (JSONException e) { e.printStackTrace(); return null; } } else { con = false; return null; } }
From source file:de.hackerspacebremen.format.JSONFormatter.java
@Override public T reformat(final String object, final Class<T> entityClass) throws FormatException { T result = null;/*from ww w. ja va 2 s . co m*/ final Map<String, Field> fieldMap = new HashMap<String, Field>(); if (entityClass.isAnnotationPresent(Entity.class)) { final Field[] fields = entityClass.getDeclaredFields(); for (final Field field : fields) { if (field.isAnnotationPresent(FormatPart.class)) { fieldMap.put(field.getAnnotation(FormatPart.class).key(), field); } } try { final JSONObject json = new JSONObject(object); result = entityClass.newInstance(); for (final String key : fieldMap.keySet()) { if (json.has(key)) { final Field field = fieldMap.get(key); final Method method = entityClass.getMethod(this.getSetter(field.getName()), new Class<?>[] { field.getType() }); final String type = field.getType().toString(); if (type.equals("class com.google.appengine.api.datastore.Key")) { method.invoke(result, KeyFactory.stringToKey(json.getString(key))); } else if (type.equals("class com.google.appengine.api.datastore.Text")) { method.invoke(result, new Text(json.getString(key))); } else if (type.equals("boolean")) { method.invoke(result, json.getBoolean(key)); } else if (type.equals("long")) { method.invoke(result, json.getLong(key)); } else if (type.equals("int")) { method.invoke(result, json.getInt(key)); } else { method.invoke(result, json.get(key)); } } } } catch (JSONException e) { logger.warning("JSONException occured: " + e.getMessage()); throw new FormatException(); } catch (NoSuchMethodException e) { logger.warning("NoSuchMethodException occured: " + e.getMessage()); throw new FormatException(); } catch (SecurityException e) { logger.warning("SecurityException occured: " + e.getMessage()); throw new FormatException(); } catch (IllegalAccessException e) { logger.warning("IllegalAccessException occured: " + e.getMessage()); throw new FormatException(); } catch (IllegalArgumentException e) { logger.warning("IllegalArgumentException occured: " + e.getMessage()); throw new FormatException(); } catch (InvocationTargetException e) { logger.warning("InvocationTargetException occured: " + e.getMessage()); throw new FormatException(); } catch (InstantiationException e) { logger.warning("InstantiationException occured: " + e.getMessage()); throw new FormatException(); } } return result; }
From source file:com.github.sgelb.booket.SearchResultActivity.java
private void processResult(String result) { JSONArray items = null;/*from w ww . j ava 2s . c o m*/ try { JSONObject jsonObject = new JSONObject(result); items = jsonObject.getJSONArray("items"); } catch (JSONException e) { noResults.setVisibility(View.VISIBLE); return; } try { // iterate over items aka books Log.d("R2R", "Items: " + items.length()); for (int i = 0; i < items.length(); i++) { Log.d("R2R", "\nBook " + (i + 1)); JSONObject item = (JSONObject) items.get(i); JSONObject info = item.getJSONObject("volumeInfo"); Book book = new Book(); // add authors String authors = ""; if (info.has("authors")) { JSONArray jAuthors = info.getJSONArray("authors"); for (int j = 0; j < jAuthors.length() - 1; j++) { authors += jAuthors.getString(j) + ", "; } authors += jAuthors.getString(jAuthors.length() - 1); } else { authors = "n/a"; } book.setAuthors(authors); Log.d("R2R", "authors " + book.getAuthors()); // add title if (info.has("title")) { book.setTitle(info.getString("title")); Log.d("R2R", "title " + book.getTitle()); } // add pageCount if (info.has("pageCount")) { book.setPageCount(info.getInt("pageCount")); Log.d("R2R", "pageCount " + book.getPageCount()); } // add publisher if (info.has("publisher")) { book.setPublisher(info.getString("publisher")); Log.d("R2R", "publisher " + book.getPublisher()); } // add description if (info.has("description")) { book.setDescription(info.getString("description")); Log.d("R2R", "description " + book.getDescription()); } // add isbn if (info.has("industryIdentifiers")) { JSONArray ids = info.getJSONArray("industryIdentifiers"); for (int k = 0; k < ids.length(); k++) { JSONObject id = ids.getJSONObject(k); if (id.getString("type").equalsIgnoreCase("ISBN_13")) { book.setIsbn(id.getString("identifier")); break; } if (id.getString("type").equalsIgnoreCase("ISBN_10")) { book.setIsbn(id.getString("identifier")); } } Log.d("R2R", "isbn " + book.getIsbn()); } // add published date if (info.has("publishedDate")) { book.setYear(info.getString("publishedDate").substring(0, 4)); Log.d("R2R", "publishedDate " + book.getYear()); } // add cover thumbnail book.setThumbnailBitmap(defaultThumbnail); if (info.has("imageLinks")) { // get cover url from google JSONObject imageLinks = info.getJSONObject("imageLinks"); if (imageLinks.has("thumbnail")) { book.setThumbnailUrl(imageLinks.getString("thumbnail")); } } else if (book.getIsbn() != null) { // get cover url from amazon String amazonCoverUrl = "http://ecx.images-amazon.com/images/P/" + isbn13to10(book.getIsbn()) + ".01._SCMZZZZZZZ_.jpg"; book.setThumbnailUrl(amazonCoverUrl); } // download cover thumbnail if (book.getThumbnailUrl() != null && !book.getThumbnailUrl().isEmpty()) { new DownloadThumbNail(book).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, book.getThumbnailUrl()); Log.d("R2R", "thumbnail " + book.getThumbnailUrl()); } // add google book id if (item.has("id")) { book.setGoogleId(item.getString("id")); } bookList.add(book); } } catch (Exception e) { Log.d("R2R", "Exception: " + e.toString()); // FIXME: catch exception } }
From source file:com.example.android.swiperefreshlistfragment.SwipeRefreshListFragmentFragment.java
/** * Parsing json reponse and passing the data to feed view list adapter * */// w w w. j a v a 2 s .c om private void parseJsonFeed(JSONObject response) { try { JSONArray feedArray = response.getJSONArray("feed"); for (int i = 0; i < feedArray.length(); i++) { JSONObject feedObj = (JSONObject) feedArray.get(i); FeedItem item = new FeedItem(); item.setId(feedObj.getInt("id")); item.setName(feedObj.getString("name")); // Image might be null sometimes String image = feedObj.isNull("image") ? null : feedObj.getString("image"); item.setImge(image); item.setStatus(feedObj.getString("status")); item.setProfilePic(feedObj.getString("profilePic")); item.setTimeStamp(feedObj.getString("timeStamp")); // url might be null sometimes String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url"); item.setUrl(feedUrl); mFeedItems.add(item); } // notify data changes to list adapater mFeedListAdapter.notifyDataSetChanged(); } catch (JSONException e) { e.printStackTrace(); } }
From source file:eu.inmite.apps.smsjizdenka.service.UpdateService.java
@Override protected void onHandleIntent(Intent intent) { if (intent == null) { return;//from ww w .ja va2s . c o m } final boolean force = intent.getBooleanExtra("force", false); try { Locale loc = Locale.getDefault(); String lang = loc.getISO3Language(); // http://www.loc.gov/standards/iso639-2/php/code_list.php; T-values if present both T and B if (lang == null || lang.length() == 0) { lang = ""; } int serverVersion = intent.getIntExtra("serverVersion", -1); boolean fromPush = serverVersion != -1; JSONObject versionJson = null; if (!fromPush) { versionJson = getVersion(true); serverVersion = versionJson.getInt("version"); } int localVersion = Preferences.getInt(c, Preferences.DATA_VERSION, -1); final String localLanguage = Preferences.getString(c, Preferences.DATA_LANGUAGE, ""); if (serverVersion <= localVersion && !force && lang.equals(localLanguage) && !LOCAL_DEFINITION_TESTING) { // don't update DebugLog.i("Nothing new, not updating"); return; } // update but don't notify about it. boolean firstLaunchNoUpdate = ((localVersion == -1 && getVersion(false).getInt("version") == serverVersion) || !lang.equals(localLanguage)); if (!firstLaunchNoUpdate) { DebugLog.i("There are new definitions available!"); } handleAuthorMessage(versionJson, lang, intent, fromPush); InputStream is = getIS(URL_TICKETS_ID); try { String json = readResult(is); JSONObject o = new JSONObject(json); JSONArray array = o.getJSONArray("tickets"); final SQLiteDatabase db = DatabaseHelper.get(this).getWritableDatabase(); for (int i = 0; i < array.length(); i++) { final JSONObject city = array.getJSONObject(i); try { final ContentValues cv = new ContentValues(); cv.put(Cities._ID, city.getInt("id")); cv.put(Cities.CITY, getStringLocValue(city, lang, "city")); if (city.has("city_pubtran")) { cv.put(Cities.CITY_PUBTRAN, city.getString("city_pubtran")); } cv.put(Cities.COUNTRY, city.getString("country")); cv.put(Cities.CURRENCY, city.getString("currency")); cv.put(Cities.DATE_FORMAT, city.getString("dateFormat")); cv.put(Cities.IDENTIFICATION, city.getString("identification")); cv.put(Cities.LAT, city.getDouble("lat")); cv.put(Cities.LON, city.getDouble("lon")); cv.put(Cities.NOTE, getStringLocValue(city, lang, "note")); cv.put(Cities.NUMBER, city.getString("number")); cv.put(Cities.P_DATE_FROM, city.getString("pDateFrom")); cv.put(Cities.P_DATE_TO, city.getString("pDateTo")); cv.put(Cities.P_HASH, city.getString("pHash")); cv.put(Cities.PRICE, city.getString("price")); cv.put(Cities.PRICE_NOTE, getStringLocValue(city, lang, "priceNote")); cv.put(Cities.REQUEST, city.getString("request")); cv.put(Cities.VALIDITY, city.getInt("validity")); if (city.has("confirmReq")) { cv.put(Cities.CONFIRM_REQ, city.getString("confirmReq")); } if (city.has("confirm")) { cv.put(Cities.CONFIRM, city.getString("confirm")); } final JSONArray additionalNumbers = city.getJSONArray("additionalNumbers"); for (int j = 0; j < additionalNumbers.length() && j < 3; j++) { cv.put("ADDITIONAL_NUMBER_" + (j + 1), additionalNumbers.getString(j)); } db.beginTransaction(); int count = db.update(DatabaseHelper.CITY_TABLE_NAME, cv, Cities._ID + " = " + cv.getAsInteger(Cities._ID), null); if (count == 0) { db.insert(DatabaseHelper.CITY_TABLE_NAME, null, cv); } db.setTransactionSuccessful(); getContentResolver().notifyChange(Cities.CONTENT_URI, null); } finally { if (db.inTransaction()) { db.endTransaction(); } } } Preferences.set(c, Preferences.DATA_VERSION, serverVersion); Preferences.set(c, Preferences.DATA_LANGUAGE, lang); if (!firstLaunchNoUpdate && !fromPush) { final int finalServerVersion = serverVersion; mHandler.post(new Runnable() { @Override public void run() { Toast.makeText(UpdateService.this, getString(R.string.cities_update_completed, finalServerVersion), Toast.LENGTH_LONG).show(); } }); } if (LOCAL_DEFINITION_TESTING) { DebugLog.w( "Local definition testing - data updated from assets - must be removed in production!"); } } finally { is.close(); } } catch (IOException e) { DebugLog.e("IOException when calling update: " + e.getMessage(), e); } catch (JSONException e) { DebugLog.e("JSONException when calling update: " + e.getMessage(), e); } }
From source file:com.goliathonline.android.kegbot.io.RemoteKegHandler.java
/** {@inheritDoc} */ @Override/*from w ww. j av a2 s .c o m*/ public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver) throws JSONException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries JSONObject result = parser.getJSONObject("result"); JSONObject keg = result.getJSONObject("keg"); JSONObject type = result.getJSONObject("type"); JSONObject image = type.getJSONObject("image"); final String kegId = sanitizeId(keg.getString("id")); final Uri kegUri = Kegs.buildKegUri(kegId); // Check for existing details, only update when changed final ContentValues values = queryKegDetails(kegUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = 500; //entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found keg " + kegId); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(kegUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation.newInsert(Kegs.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Kegs.KEG_ID, kegId); // Inherit starred value from previous row if (values.containsKey(Kegs.KEG_STARRED)) { builder.withValue(Kegs.KEG_STARRED, values.getAsInteger(Kegs.KEG_STARRED)); } if (keg.has("status")) builder.withValue(Kegs.STATUS, keg.getString("status")); if (keg.has("volume_ml_remain")) builder.withValue(Kegs.VOLUME_REMAIN, keg.getDouble("volume_ml_remain")); if (keg.has("description")) builder.withValue(Kegs.DESCRIPTION, keg.getString("description")); if (keg.has("type_id")) builder.withValue(Kegs.TYPE_ID, keg.getString("type_id")); if (keg.has("size_id")) builder.withValue(Kegs.SIZE_ID, keg.getInt("size_id")); if (keg.has("percent_full")) builder.withValue(Kegs.PERCENT_FULL, keg.getDouble("percent_full")); if (keg.has("size_name")) builder.withValue(Kegs.SIZE_NAME, keg.getString("size_name")); if (keg.has("spilled_ml")) builder.withValue(Kegs.VOLUME_SPILL, keg.getDouble("spilled_ml")); if (keg.has("size_volume_ml")) builder.withValue(Kegs.VOLUME_SIZE, keg.getDouble("size_volume_ml")); if (type.has("name")) builder.withValue(Kegs.KEG_NAME, type.getString("name")); if (type.has("abv")) builder.withValue(Kegs.KEG_ABV, type.getDouble("abv")); if (image.has("url")) builder.withValue(Kegs.IMAGE_URL, image.getString("url")); // Normal keg details ready, write to provider batch.add(builder.build()); return batch; }
From source file:com.ecofactor.qa.automation.newapp.service.BaseDataServiceImpl.java
/** * Creates the algo control list./*from ww w . j a va2 s.c o m*/ * @param jobData the job data * @param thermostatId the thermostat id * @param algoId the algo id * @return the list */ protected List<ThermostatAlgorithmController> createAlgoControlList(JSONArray jobData, Integer thermostatId, Integer algoId) { Algorithm algorithm = findByAlgorithmId(algoId); List<ThermostatAlgorithmController> algoControlList = new ArrayList<ThermostatAlgorithmController>(); int moBlackOut; double moRecovery; double deltaEE = 0; Calendar utcCalendar = null; Calendar startTime = null; Calendar endTime = null; Calendar moCutoffTime = null; JSONObject jsonObj; for (int i = 0; i < jobData.length(); i++) { try { jsonObj = jobData.getJSONObject(i); startTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("start")); endTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("end")); moCutoffTime = DateUtil.getUTCTimeZoneCalendar((String) jsonObj.get("moCutoff")); moBlackOut = jsonObj.getInt("moBlackOut"); moRecovery = jsonObj.getInt("moRecovery"); deltaEE = jsonObj.getDouble("deltaEE"); ThermostatAlgorithmController algoControlPhase1 = new ThermostatAlgorithmController(); algoControlPhase1.setStatus(Status.ACTIVE); algoControlPhase1.setThermostatId(thermostatId); algoControlPhase1.setAlgorithmId(algoId); String utcCalendarTimeStamp = DateUtil.format(startTime, DateUtil.DATE_FMT_FULL); utcCalendar = DateUtil.parseToCalendar(utcCalendarTimeStamp, DateUtil.DATE_FMT_FULL); // Next phase time algoControlPhase1.setNextPhaseTime(utcCalendar); // Execution start time. Calendar executionStartTime = (Calendar) utcCalendar.clone(); executionStartTime.add(Calendar.MINUTE, -3); algoControlPhase1.setExecutionStartTimeUTC(executionStartTime); String endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL); Calendar endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL); // Execution end time. algoControlPhase1.setExecutionEndTimeUTC(endutcCalendar); String cuttoffutcCalendarTimeStamp = DateUtil.format(moCutoffTime, DateUtil.DATE_FMT_FULL); Calendar cutOffutcCalendar = DateUtil.parseToCalendar(cuttoffutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL); // MO cut off time. algoControlPhase1.setMoCutOff(cutOffutcCalendar); algoControlPhase1.setPhase0Spt(deltaEE); algoControlPhase1.setPrevSpt(0.0); algoControlPhase1.setMoBlackOut(moBlackOut); algoControlPhase1.setMoRecovery(moRecovery); algoControlPhase1.setAlgorithm(algorithm); if (algoId == SPO_COOL || algoId == SPO_HEAT) { algoControlPhase1.setActor(ACTOR_SPO); } algoControlList.add(algoControlPhase1); // second row ThermostatAlgorithmController algoControlPhase2 = new ThermostatAlgorithmController(); algoControlPhase2 = algoControlPhase1.clone(); endutcCalendarTimeStamp = DateUtil.format(endTime, DateUtil.DATE_FMT_FULL); endutcCalendar = DateUtil.parseToCalendar(endutcCalendarTimeStamp, DateUtil.DATE_FMT_FULL); if (algoId == SPO_COOL || algoId == SPO_HEAT) { algoControlPhase2.setActor(ACTOR_SPO); } // Execution end time. algoControlPhase2.setExecutionStartTimeUTC(endutcCalendar); algoControlPhase2.setExecutionEndTimeUTC(null); algoControlPhase2.setNextPhaseTime(endutcCalendar); algoControlPhase2.setPhase0Spt(0.0); algoControlPhase2.setAlgorithm(algorithm); algoControlPhase2.setStatus(Status.ACTIVE); algoControlList.add(algoControlPhase2); } catch (JSONException | CloneNotSupportedException e) { e.printStackTrace(); } } return algoControlList; }
From source file:br.com.hslife.orcamento.json.TestJson1.java
@Test public void main() throws JSONException { /* ------------------------------------------------------- * TESTE 1 * cria um JSONObject para armazenar dados de um filme * -------------------------------------------------------*/ //instancia um novo JSONObject JSONObject my_obj = new JSONObject(); //preenche o objeto com os campos: titulo, ano e genero my_obj.put("titulo", "JSON x XML: a Batalha Final"); my_obj.put("ano", 2012); my_obj.put("genero", "Ao"); //serializa para uma string e imprime String json_string = my_obj.toString(); System.out.println("objeto original -> " + json_string); System.out.println(); //altera o titulo e imprime a nova configurao do objeto my_obj.put("titulo", "JSON x XML: o Confronto das Linguagens"); json_string = my_obj.toString();//w w w . j a v a 2s .co m System.out.println("objeto com o ttulo modificado -> " + json_string); System.out.println(); //recupera campo por campo com o mtodo get() e imprime cada um String titulo = my_obj.getString("titulo"); Integer ano = my_obj.getInt("ano"); String genero = my_obj.getString("genero"); System.out.println("titulo: " + titulo); System.out.println("ano: " + ano); System.out.println("genero: " + genero); }