List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:com.seunghyo.sunshine.FetchWeatherTask.java
/** * Take the String representing the complete forecast in JSON Format and * pull out the data we need to construct the Strings needed for the wireframes. * * Fortunately parsing is easy: constructor takes the JSON string and converts it * into an Object hierarchy for us.//w w w .j ava 2s. c o m */ private String[] getWeatherDataFromJson(String forecastJsonStr, String locationSetting) throws JSONException { // Now we have a String representing the complete forecast in JSON Format. // Fortunately parsing is easy: constructor takes the JSON string and converts it // into an Object hierarchy for us. // These are the names of the JSON objects that need to be extracted. // Location information final String OWM_CITY = "city"; final String OWM_CITY_NAME = "name"; final String OWM_COORD = "coord"; // Location coordinate final String OWM_LATITUDE = "lat"; final String OWM_LONGITUDE = "lon"; // Weather information. Each day's forecast info is an element of the "list" array. final String OWM_LIST = "list"; final String OWM_PRESSURE = "pressure"; final String OWM_HUMIDITY = "humidity"; final String OWM_WINDSPEED = "speed"; final String OWM_WIND_DIRECTION = "deg"; // All temperatures are children of the "temp" object. final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_WEATHER = "weather"; final String OWM_DESCRIPTION = "main"; final String OWM_WEATHER_ID = "id"; try { JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); JSONObject cityJson = forecastJson.getJSONObject(OWM_CITY); String cityName = cityJson.getString(OWM_CITY_NAME); JSONObject cityCoord = cityJson.getJSONObject(OWM_COORD); double cityLatitude = cityCoord.getDouble(OWM_LATITUDE); double cityLongitude = cityCoord.getDouble(OWM_LONGITUDE); long locationId = addLocation(locationSetting, cityName, cityLatitude, cityLongitude); // Insert the new weather information into the database Vector<ContentValues> cVVector = new Vector<ContentValues>(weatherArray.length()); // OWM returns daily forecasts based upon the local time of the city that is being // asked for, which means that we need to know the GMT offset to translate this data // properly. // Since this data is also sent in-order and the first day is always the // current day, we're going to take advantage of that to get a nice // normalized UTC date for all of our weather. Time dayTime = new Time(); dayTime.setToNow(); // we start at the day returned by local time. Otherwise this is a mess. int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff); // now we work exclusively in UTC dayTime = new Time(); for (int i = 0; i < weatherArray.length(); i++) { // These are the values that will be collected. long dateTime; double pressure; int humidity; double windSpeed; double windDirection; double high; double low; String description; int weatherId; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); // Cheating to convert this to UTC time, which is what we want anyhow dateTime = dayTime.setJulianDay(julianStartDay + i); pressure = dayForecast.getDouble(OWM_PRESSURE); humidity = dayForecast.getInt(OWM_HUMIDITY); windSpeed = dayForecast.getDouble(OWM_WINDSPEED); windDirection = dayForecast.getDouble(OWM_WIND_DIRECTION); // Description is in a child array called "weather", which is 1 element long. // That element also contains a weather code. JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0); description = weatherObject.getString(OWM_DESCRIPTION); weatherId = weatherObject.getInt(OWM_WEATHER_ID); // Temperatures are in a child object called "temp". Try not to name variables // "temp" when working with temperature. It confuses everybody. JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); high = temperatureObject.getDouble(OWM_MAX); low = temperatureObject.getDouble(OWM_MIN); ContentValues weatherValues = new ContentValues(); weatherValues.put(WeatherEntry.COLUMN_LOC_KEY, locationId); weatherValues.put(WeatherEntry.COLUMN_DATE, dateTime); weatherValues.put(WeatherEntry.COLUMN_HUMIDITY, humidity); weatherValues.put(WeatherEntry.COLUMN_PRESSURE, pressure); weatherValues.put(WeatherEntry.COLUMN_WIND_SPEED, windSpeed); weatherValues.put(WeatherEntry.COLUMN_DEGREES, windDirection); weatherValues.put(WeatherEntry.COLUMN_MAX_TEMP, high); weatherValues.put(WeatherEntry.COLUMN_MIN_TEMP, low); weatherValues.put(WeatherEntry.COLUMN_SHORT_DESC, description); weatherValues.put(WeatherEntry.COLUMN_WEATHER_ID, weatherId); cVVector.add(weatherValues); } // add to database if (cVVector.size() > 0) { // Student: call bulkInsert to add the weatherEntries to the database here } // Sort order: Ascending, by date. String sortOrder = WeatherEntry.COLUMN_DATE + " ASC"; Uri weatherForLocationUri = WeatherEntry.buildWeatherLocationWithStartDate(locationSetting, System.currentTimeMillis()); // Students: Uncomment the next lines to display what what you stored in the bulkInsert // Cursor cur = mContext.getContentResolver().query(weatherForLocationUri, // null, null, null, sortOrder); // // cVVector = new Vector<ContentValues>(cur.getCount()); // if ( cur.moveToFirst() ) { // do { // ContentValues cv = new ContentValues(); // DatabaseUtils.cursorRowToContentValues(cur, cv); // cVVector.add(cv); // } while (cur.moveToNext()); // } Log.d(LOG_TAG, "FetchWeatherTask Complete. " + cVVector.size() + " Inserted"); String[] resultStrs = convertContentValuesToUXFormat(cVVector); return resultStrs; } catch (JSONException e) { Log.e(LOG_TAG, e.getMessage(), e); e.printStackTrace(); } return null; }
From source file:edu.umass.cs.gigapaxos.paxospackets.AcceptPacket.java
public AcceptPacket(JSONObject json) throws JSONException { super(json);/* ww w .j av a2 s . c o m*/ assert (PaxosPacket.getPaxosPacketType(json) == PaxosPacketType.ACCEPT); this.packetType = PaxosPacketType.ACCEPT; this.sender = json.getInt(PaxosPacket.NodeIDKeys.SNDR.toString()); // TODO: why do we need to set paxosID here? this.paxosID = json.getString(PaxosPacket.Keys.ID.toString()); }
From source file:com.xfinity.ceylon_steel.controller.CustomerController.java
public static void downloadCustomers(final Context context) { new AsyncTask<User, Void, JSONArray>() { @Override/*from w w w . java 2 s . co m*/ protected void onPreExecute() { if (UserController.progressDialog == null) { UserController.progressDialog = new ProgressDialog(context); UserController.progressDialog.setMessage("Downloading Data"); UserController.progressDialog.setCanceledOnTouchOutside(false); } if (!UserController.progressDialog.isShowing()) { UserController.progressDialog.show(); } } @Override protected JSONArray doInBackground(User... users) { try { User user = users[0]; HashMap<String, Object> parameters = new HashMap<String, Object>(); parameters.put("userId", user.getUserId()); return getJsonArray(getCustomersOfUser, parameters, context); } catch (IOException ex) { Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex); } catch (JSONException ex) { Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex); } return null; } @Override protected void onPostExecute(JSONArray result) { if (UserController.atomicInteger.decrementAndGet() == 0 && UserController.progressDialog != null && UserController.progressDialog.isShowing()) { UserController.progressDialog.dismiss(); UserController.progressDialog = null; } if (result != null) { SQLiteDatabaseHelper databaseInstance = SQLiteDatabaseHelper.getDatabaseInstance(context); SQLiteDatabase database = databaseInstance.getWritableDatabase(); SQLiteStatement compiledStatement = database .compileStatement("replace into tbl_customer(customerId,customerName) values(?,?)"); try { database.beginTransaction(); for (int i = 0; i < result.length(); i++) { JSONObject customer = result.getJSONObject(i); compiledStatement.bindAllArgsAsStrings( new String[] { Integer.toString(customer.getInt("customerId")), customer.getString("customerName") }); long response = compiledStatement.executeInsert(); if (response == -1) { return; } } database.setTransactionSuccessful(); Toast.makeText(context, "Customers downloaded successfully", Toast.LENGTH_SHORT).show(); } catch (JSONException ex) { Logger.getLogger(CustomerController.class.getName()).log(Level.SEVERE, null, ex); Toast.makeText(context, "Unable parse customers", Toast.LENGTH_SHORT).show(); } finally { database.endTransaction(); databaseInstance.close(); } } else { Toast.makeText(context, "Unable to download customers", Toast.LENGTH_SHORT).show(); } } }.execute(UserController.getAuthorizedUser(context)); }
From source file:cn.ttyhuo.activity.InfoOwnerActivity.java
protected void setupViewOfHasLogin(JSONObject jObject) { try {//from www. j a va 2 s. c o m ArrayList<String> pics = new ArrayList<String>(); JSONArray jsonArray = jObject.optJSONArray("imageList"); if (jsonArray != null) { for (int s = 0; s < jsonArray.length(); s++) pics.add(jsonArray.getString(s)); } while (pics.size() < 3) pics.add("plus"); mPicData = pics; mPicAdapter.updateData(pics); if (jObject.getBoolean("isTruckVerified")) { tv_edit_tips.setText("?????"); } else if (jsonArray != null && jsonArray.length() > 2 && jObject.has("truckInfo")) { tv_edit_tips.setText( "?????????"); } else { tv_edit_tips.setText("??????"); } if (jObject.has("truckInfo")) { JSONObject userJsonObj = jObject.getJSONObject("truckInfo"); if (!userJsonObj.optString("licensePlate").isEmpty() && userJsonObj.optString("licensePlate") != "null") mEditChepai.setText(userJsonObj.getString("licensePlate")); Integer truckType = userJsonObj.getInt("truckType"); if (truckType != null && truckType > 0) mEditChexing.setText(ConstHolder.TruckTypeItems[truckType - 1]); else mEditChexing.setText(""); if (!userJsonObj.optString("loadLimit").isEmpty() && userJsonObj.optString("loadLimit") != "null") mEditZaizhong.setText(userJsonObj.getString("loadLimit")); if (!userJsonObj.optString("truckLength").isEmpty() && userJsonObj.optString("truckLength") != "null") mEditChechang.setText(userJsonObj.getString("truckLength")); if (!userJsonObj.optString("modelNumber").isEmpty() && userJsonObj.optString("modelNumber") != "null") mEditXinghao.setText(userJsonObj.getString("modelNumber")); if (!userJsonObj.optString("seatingCapacity").isEmpty() && userJsonObj.optString("seatingCapacity") != "null") mEditZuowei.setText(userJsonObj.getString("seatingCapacity")); if (!userJsonObj.optString("releaseYear").isEmpty() && userJsonObj.optString("releaseYear") != "null") mEditDate.setText(userJsonObj.getString("releaseYear") + ""); if (!userJsonObj.optString("truckWidth").isEmpty() && userJsonObj.optString("truckWidth") != "null") mEditKuan.setText(userJsonObj.getString("truckWidth")); if (!userJsonObj.optString("truckHeight").isEmpty() && userJsonObj.optString("truckHeight") != "null") mEditGao.setText(userJsonObj.getString("truckHeight")); } if (!jObject.getBoolean("isTruckVerified")) { mEditChexing.setOnClickListener(this); mEditDate.setOnClickListener(this); mEditChepai.setFocusable(true); mEditChepai.setEnabled(true); mEditZaizhong.setFocusable(true); mEditZaizhong.setEnabled(true); mEditChechang.setFocusable(true); mEditChechang.setEnabled(true); mEditZuowei.setFocusable(true); mEditZuowei.setEnabled(true); mEditKuan.setFocusable(true); mEditKuan.setEnabled(true); mEditGao.setFocusable(true); mEditGao.setEnabled(true); mEditXinghao.setFocusable(true); mEditXinghao.setEnabled(true); canUpdate = true; } else { mPicGrid.setOnItemLongClickListener(null); mEditChepai.setFocusable(false); mEditChepai.setEnabled(false); mEditZaizhong.setFocusable(false); mEditZaizhong.setEnabled(false); mEditChechang.setFocusable(false); mEditChechang.setEnabled(false); mEditZuowei.setFocusable(false); mEditZuowei.setEnabled(false); mEditKuan.setFocusable(false); mEditKuan.setEnabled(false); mEditGao.setFocusable(false); mEditGao.setEnabled(false); mEditXinghao.setFocusable(false); mEditXinghao.setEnabled(false); canUpdate = false; } saveParams(true); } catch (JSONException e) { e.printStackTrace(); } }
From source file:net.zorgblub.typhon.dto.PageOffsets.java
public static PageOffsets fromJSON(String json) throws JSONException { JSONObject offsetsObject = new JSONObject(json); PageOffsets result = new PageOffsets(); result.fontFamily = offsetsObject.getString(Fields.fontFamily.name()); result.fontSize = offsetsObject.getInt(Fields.fontSize.name()); result.vMargin = offsetsObject.getInt(Fields.vMargin.name()); result.hMargin = offsetsObject.getInt(Fields.hMargin.name()); result.lineSpacing = offsetsObject.getInt(Fields.lineSpacing.name()); result.fullScreen = offsetsObject.getBoolean(Fields.fullScreen.name()); result.algorithmVersion = offsetsObject.optInt(Fields.algorithmVersion.name(), -1); result.allowStyling = offsetsObject.optBoolean(Fields.allowStyling.name(), true); result.offsets = readOffsets(offsetsObject.getJSONArray(Fields.offsets.name())); return result; }
From source file:de.dmxcontrol.executor.EntityExecutor.java
public static EntityExecutor Receive(JSONObject o) { EntityExecutor entity = null;//from w ww .j av a2 s.c o m try { if (o.getString("Type").equals(NetworkID)) { entity = new EntityExecutor(o.getInt("Number"), o.getString("Name")); entity.guid = o.getString("GUID"); if (o.has("Value")) { entity.value = Float.parseFloat(o.getString("Value").replace(",", ".")); } if (o.has("Flash")) { entity.flash = o.getBoolean("Flash"); } if (o.has("Toggle")) { entity.toggle = o.getBoolean("Toggle"); } if (o.has("FaderMode")) { entity.faderMode = o.getInt("FaderMode"); } } } catch (Exception e) { Log.e("UDP Listener", e.getMessage()); DMXControlApplication.SaveLog(); } o = null; if (o == null) { ; } return entity; }
From source file:net.dv8tion.jda.core.handle.TypingStartHandler.java
@Override protected Long handleInternally(JSONObject content) { final long channelId = content.getLong("channel_id"); MessageChannel channel = api.getTextChannelMap().get(channelId); if (channel == null) channel = api.getPrivateChannelMap().get(channelId); if (channel == null) channel = api.getFakePrivateChannelMap().get(channelId); if (channel == null && api.getAccountType() == AccountType.CLIENT) channel = api.asClient().getGroupById(channelId); if (channel == null) return null; //We don't have the channel cached yet. We chose not to cache this event // because that happen very often and could easily fill up the EventCache if // we, for some reason, never get the channel. Especially in an active channel. if (channel instanceof TextChannel) { final long guildId = ((TextChannel) channel).getGuild().getIdLong(); if (api.getGuildLock().isLocked(guildId)) return guildId; }/* ww w.j a v a 2 s.c om*/ final long userId = content.getLong("user_id"); User user; if (channel instanceof PrivateChannel) user = ((PrivateChannel) channel).getUser(); else if (channel instanceof Group) user = ((GroupImpl) channel).getUserMap().get(userId); else user = api.getUserMap().get(userId); if (user == null) return null; //Just like in the comment above, if for some reason we don't have the user for some reason // then we will just throw the event away. OffsetDateTime timestamp = Instant.ofEpochSecond(content.getInt("timestamp")).atOffset(ZoneOffset.UTC); api.getEventManager().handle(new UserTypingEvent(api, responseNumber, user, channel, timestamp)); return null; }
From source file:com.goliathonline.android.kegbot.io.RemoteDrinksHandler.java
/** {@inheritDoc} */ @Override//from w w w. j a v a 2s . c om public ArrayList<ContentProviderOperation> parse(JSONObject parser, ContentResolver resolver) throws JSONException, IOException { final ArrayList<ContentProviderOperation> batch = Lists.newArrayList(); // Walk document, parsing any incoming entries int drink_id = 0; JSONObject result = parser.getJSONObject("result"); JSONArray drinks = result.getJSONArray("drinks"); JSONObject drink; for (int i = 0; i < drinks.length(); i++) { if (drink_id == 0) { // && ENTRY.equals(parser.getName() // Process single spreadsheet row at a time drink = drinks.getJSONObject(i); final String drinkId = sanitizeId(drink.getString("id")); final Uri drinkUri = Drinks.buildDrinkUri(drinkId); // Check for existing details, only update when changed final ContentValues values = queryDrinkDetails(drinkUri, resolver); final long localUpdated = values.getAsLong(SyncColumns.UPDATED); final long serverUpdated = 500; //entry.getUpdated(); if (Log.isLoggable(TAG, Log.VERBOSE)) { Log.v(TAG, "found drink " + drinkId); Log.v(TAG, "found localUpdated=" + localUpdated + ", server=" + serverUpdated); } if (localUpdated != KegbotContract.UPDATED_NEVER) continue; final Uri drinkKegUri = Drinks.buildKegUri(drinkId); final Uri drinkUserUri = Drinks.buildUserUri(drinkId); // Clear any existing values for this session, treating the // incoming details as authoritative. batch.add(ContentProviderOperation.newDelete(drinkUri).build()); batch.add(ContentProviderOperation.newDelete(drinkKegUri).build()); final ContentProviderOperation.Builder builder = ContentProviderOperation .newInsert(Drinks.CONTENT_URI); builder.withValue(SyncColumns.UPDATED, serverUpdated); builder.withValue(Drinks.DRINK_ID, drinkId); // Inherit starred value from previous row if (values.containsKey(Drinks.DRINK_STARRED)) { builder.withValue(Drinks.DRINK_STARRED, values.getAsInteger(Drinks.DRINK_STARRED)); } if (drink.has("session_id")) builder.withValue(Drinks.SESSION_ID, drink.getInt("session_id")); if (drink.has("status")) builder.withValue(Drinks.STATUS, drink.getString("status")); if (drink.has("user_id")) builder.withValue(Drinks.USER_ID, drink.getString("user_id")); if (drink.has("keg_id")) builder.withValue(Drinks.KEG_ID, drink.getInt("keg_id")); if (drink.has("volume_ml")) builder.withValue(Drinks.VOLUME, drink.getDouble("volume_ml")); if (drink.has("pour_time")) builder.withValue(Drinks.POUR_TIME, drink.getString("pour_time")); // Normal session details ready, write to provider batch.add(builder.build()); // Assign kegs final int kegId = drink.getInt("keg_id"); batch.add(ContentProviderOperation.newInsert(drinkKegUri).withValue(DrinksKeg.DRINK_ID, drinkId) .withValue(DrinksKeg.KEG_ID, kegId).build()); // Assign users if (drink.has("user_id")) { final String userId = drink.getString("user_id"); batch.add(ContentProviderOperation.newInsert(drinkUserUri) .withValue(DrinksUser.DRINK_ID, drinkId).withValue(DrinksUser.USER_ID, userId).build()); } } } return batch; }
From source file:com.example.android.samplesync.client.RawContact.java
/** * Creates and returns an instance of the RawContact from the provided JSON data. * * @param user The JSONObject containing user data * @return user The new instance of Sample RawContact created from the JSON data. *///from ww w . j av a 2s. c o m public static RawContact valueOf(JSONObject contact) { try { final String userName = !contact.isNull("u") ? contact.getString("u") : null; final int serverContactId = !contact.isNull("i") ? contact.getInt("i") : -1; // If we didn't get either a username or serverId for the contact, then // we can't do anything with it locally... if ((userName == null) && (serverContactId <= 0)) { throw new JSONException("JSON contact missing required 'u' or 'i' fields"); } final int rawContactId = !contact.isNull("c") ? contact.getInt("c") : -1; final String firstName = !contact.isNull("f") ? contact.getString("f") : null; final String lastName = !contact.isNull("l") ? contact.getString("l") : null; final String cellPhone = !contact.isNull("m") ? contact.getString("m") : null; final String officePhone = !contact.isNull("o") ? contact.getString("o") : null; final String homePhone = !contact.isNull("h") ? contact.getString("h") : null; final String email = !contact.isNull("e") ? contact.getString("e") : null; final String status = !contact.isNull("s") ? contact.getString("s") : null; final String avatarUrl = !contact.isNull("a") ? contact.getString("a") : null; final boolean deleted = !contact.isNull("d") ? contact.getBoolean("d") : false; final long syncState = !contact.isNull("x") ? contact.getLong("x") : 0; return new RawContact(userName, null, firstName, lastName, cellPhone, officePhone, homePhone, email, status, avatarUrl, deleted, serverContactId, rawContactId, syncState, false); } catch (final Exception ex) { Log.i(TAG, "Error parsing JSON contact object" + ex.toString()); } return null; }
From source file:org.brickred.socialauth.provider.HotmailImpl.java
private Profile getProfile() throws Exception { Profile p = new Profile(); Response serviceResponse;//from ww w . ja va 2s . co m try { serviceResponse = authenticationStrategy.executeFeed(PROFILE_URL); } catch (Exception e) { throw new SocialAuthException("Failed to retrieve the user profile from " + PROFILE_URL, e); } String result; try { result = serviceResponse.getResponseBodyAsString(Constants.ENCODING); LOG.debug("User Profile :" + result); } catch (Exception e) { throw new SocialAuthException("Failed to read response from " + PROFILE_URL, e); } try { JSONObject resp = new JSONObject(result); if (resp.has("id")) { p.setValidatedId(resp.getString("id")); } if (resp.has("name")) { p.setFullName(resp.getString("name")); } if (resp.has("first_name")) { p.setFirstName(resp.getString("first_name")); } if (resp.has("last_name")) { p.setLastName(resp.getString("last_name")); } if (resp.has("Location")) { p.setLocation(resp.getString("Location")); } if (resp.has("gender")) { p.setGender(resp.getString("gender")); } if (resp.has("ThumbnailImageLink")) { p.setProfileImageURL(resp.getString("ThumbnailImageLink")); } if (resp.has("birth_day") && !resp.isNull("birth_day")) { BirthDate bd = new BirthDate(); bd.setDay(resp.getInt("birth_day")); if (resp.has("birth_month") && !resp.isNull("birth_month")) { bd.setMonth(resp.getInt("birth_month")); } if (resp.has("birth_year") && !resp.isNull("birth_year")) { bd.setYear(resp.getInt("birth_year")); } p.setDob(bd); } if (resp.has("emails")) { JSONObject eobj = resp.getJSONObject("emails"); String email = null; if (eobj.has("preferred")) { email = eobj.getString("preferred"); } if ((email == null || email.isEmpty()) && eobj.has("account")) { email = eobj.getString("account"); } if ((email == null || email.isEmpty()) && eobj.has("personal")) { email = eobj.getString("personal"); } p.setEmail(email); } if (resp.has("locale")) { p.setLanguage(resp.getString("locale")); } serviceResponse.close(); p.setProviderId(getProviderId()); String picUrl = String.format(PROFILE_PICTURE_URL, accessGrant.getKey()); p.setProfileImageURL(picUrl); userProfile = p; return p; } catch (Exception e) { throw new SocialAuthException("Failed to parse the user profile json : " + result, e); } }