private PanoramioNode parseNode(JSONObject jsonData) { PanoramioNode pnode = new PanoramioNode(); try { if (jsonData.has("name")) pnode.name = jsonData.getString("name"); if (jsonData.has("since")) pnode.date = jsonData.getString("since"); if (jsonData.has("position")) { JSONObject jsonPosition = jsonData.getJSONObject("position"); if (jsonPosition.has("latitude")) pnode.latitude = jsonPosition.getDouble("latitude"); if (jsonPosition.has("longitude")) pnode.longitude = jsonPosition.getDouble("longitude"); } if (jsonData.has("external_info")) { JSONObject jsonInfo = jsonData.getJSONObject("external_info"); if (jsonInfo.has("info_url")) pnode.info_url = jsonInfo.getString("info_url"); if (jsonInfo.has("photo_thumb")) pnode.thumb_url = jsonInfo.getString("photo_thumb"); if (jsonInfo.has("photo_url")) pnode.photo_url = jsonInfo.getString("photo_url"); } return pnode; } catch (JSONException e) { Log.e(TAG, e.getMessage()); return null; } }
@Override protected ArrayList<Marker> doInBackground(Void... params) { HttpParams httpRequestParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpClient client = new DefaultHttpClient(httpRequestParams); HttpPost post = new HttpPost(SERVER_ADDRESS + "getMarker.php"); Log.d("feed", "connected"); ArrayList<Marker> listMarker = new ArrayList<>(); try { HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String strEntity = EntityUtils.toString(entity); Log.d("feed", strEntity); JSONObject json = new JSONObject(strEntity); JSONArray jsonArray = json.getJSONArray("post"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonobject = jsonArray.getJSONObject(i); String id = jsonobject.getString("id"); double latitude = jsonobject.getDouble("latitude"); double longitude = jsonobject.getDouble("longitude"); Marker marker = new Marker(id, latitude, longitude); listMarker.add(marker); } } catch (Exception e) { Log.d("feed", "exception"); e.printStackTrace(); return null; } Log.d("feed", "returned"); return listMarker; }
public static void saveAlerts(JSONArray alerts) throws JSONException { ActiveAndroid.beginTransaction(); try { new Delete().from(Alert.class).execute(); JSONObject currentAlert; for (int i = 0; i < alerts.length(); i++) { currentAlert = alerts.getJSONObject(i); Alert alert = new Alert(); alert.alertId = currentAlert.getLong("id"); alert.description = currentAlert.getString("alert"); alert.date = currentAlert.getString("date"); alert.username = currentAlert.getString("username"); alert.latitude = currentAlert.getDouble("latitude"); alert.longitude = currentAlert.getDouble("longitude"); alert.line = currentAlert.getString("line"); alert.city = currentAlert.getString("city"); alert.station = currentAlert.getString("station"); alert.transport = currentAlert.getString("transport"); alert.icon = currentAlert.getString("transport_icon"); alert.save(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); } }
@Override public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception { if (topic.equals("Likaci/MqttMap")) { String msg = new String(mqttMessage.getPayload()); JSONObject json = new JSONObject(msg); if (!json.getString("id").equals(id)) { Point p = (Point) GeometryEngine.project( new Point(json.getDouble("x"), json.getDouble("y")), SpatialReference.create(4326), SpatialReference.create(3857)); layer.removeAll(); SimpleMarkerSymbol markerSymbol = new SimpleMarkerSymbol( Color.parseColor("#763382"), 15, SimpleMarkerSymbol.STYLE.DIAMOND); layer.addGraphic(new Graphic(p, markerSymbol)); TextSymbol textSymbol = new TextSymbol( 15, json.getString("id"), Color.parseColor("#763382"), TextSymbol.HorizontalAlignment.CENTER, TextSymbol.VerticalAlignment.MIDDLE); textSymbol.setOffsetY(-15); layer.addGraphic(new Graphic(p, textSymbol)); } } }
@Override protected List<PostItem> doInBackground(Void... params) { ArrayList<NameValuePair> inputData = new ArrayList<>(); inputData.add(new BasicNameValuePair("numFeed", "" + numFeed)); inputData.add(new BasicNameValuePair("userId", userId)); Log.d("feed", "do in background"); HttpParams httpRequestParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT); HttpClient client = new DefaultHttpClient(httpRequestParams); HttpPost post = new HttpPost(SERVER_ADDRESS + "getFeed.php"); Log.d("feed", "connected"); List<PostItem> listPostItem = new ArrayList<>(); try { post.setEntity(new UrlEncodedFormEntity(inputData)); HttpResponse httpResponse = client.execute(post); HttpEntity entity = httpResponse.getEntity(); String strEntity = EntityUtils.toString(entity); Log.d("feed", strEntity); JSONObject json = new JSONObject(strEntity); JSONArray jsonArray = json.getJSONArray("post"); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonobject = jsonArray.getJSONObject(i); String id = jsonobject.getString("id"); String link = jsonobject.getString("link"); String linkSmall = jsonobject.getString("linkSmall"); String description = jsonobject.getString("description"); String name = jsonobject.getString("name"); String time = jsonobject.getString("time"); int totalLike = jsonobject.getInt("totalLike"); boolean isLike = jsonobject.getBoolean("isLike"); String address = jsonobject.getString("address"); double latitude = jsonobject.getDouble("latitude"); double longitude = jsonobject.getDouble("longitude"); PostItem postItem = new PostItem( id, null, name, time, link, linkSmall, description, totalLike, isLike, address, latitude, longitude); listPostItem.add(postItem); } } catch (Exception e) { Log.d("feed", "exception"); e.printStackTrace(); return null; } Log.d("feed", "returned"); return listPostItem; }
public Tower(JSONObject jsonObject) { try { setLocationAreaCode(Integer.parseInt(jsonObject.getString("lac"))); } catch (JSONException e) { } try { setCellId(Integer.parseInt(jsonObject.getString("cid"))); } catch (JSONException e) { } try { JSONObject location = jsonObject.getJSONObject("location"); setLatLng(new LatLng(location.getDouble("Latitude"), location.getDouble("Longitude"))); } catch (JSONException e) { } try { setRssi(Integer.parseInt(jsonObject.getString("signal"))); } catch (JSONException e) { } try { setBts(jsonObject.getString("bts")); } catch (JSONException e) { } try { setId(jsonObject.getString("_id")); } catch (JSONException e) { } try { setOperator(jsonObject.getString("operator")); } catch (JSONException e) { } setTime(GeneralUtils.getCurrentTime()); setNeighbor(false); }
public static RouteModel ParseJSON(String json) throws JSONException { RouteModel route = new RouteModel(); ArrayList<Step> localSteps = new ArrayList<RouteModel.Step>(); // JSONをパース JSONObject obj = new JSONObject(json); JSONArray routelist = obj.getJSONArray("routes"); JSONObject mainroute = routelist.getJSONObject(0); JSONArray legslist = mainroute.getJSONArray("legs"); for (int i = 0; i < legslist.length(); i++) { JSONArray steps = legslist.getJSONObject(i).getJSONArray("steps"); for (int j = 0; j < steps.length(); j++) { Step s = route.new Step(); JSONObject step = steps.getJSONObject(j); s.distance = step.getJSONObject("distance").getInt("value"); s.duration = step.getJSONObject("duration").getInt("value"); JSONObject st = step.getJSONObject("start_location"); s.start_addr = new GeoPoint((int) (st.getDouble("lat") * 1E6), (int) (st.getDouble("lng") * 1E6)); JSONObject en = step.getJSONObject("end_location"); s.end_addr = new GeoPoint((int) (en.getDouble("lat") * 1E6), (int) (en.getDouble("lng") * 1E6)); s.instruction = step.getString("html_instructions"); localSteps.add(s); } } route.steps = new Step[localSteps.size()]; for (int i = 0; i < localSteps.size(); i++) { route.steps[i] = localSteps.get(i); } return route; }
/** * @param url full URL request * @return the list of POI, of null if technical issue. */ public ArrayList<POI> getThem(String url) { Log.d(BonusPackHelper.LOG_TAG, "NominatimPOIProvider:get:" + url); String jString = BonusPackHelper.requestStringFromUrl(url); if (jString == null) { Log.e(BonusPackHelper.LOG_TAG, "NominatimPOIProvider: request failed."); return null; } try { JSONArray jPlaceIds = new JSONArray(jString); int n = jPlaceIds.length(); ArrayList<POI> pois = new ArrayList<POI>(n); Bitmap thumbnail = null; for (int i = 0; i < n; i++) { JSONObject jPlace = jPlaceIds.getJSONObject(i); POI poi = new POI(POI.POI_SERVICE_NOMINATIM); poi.mId = jPlace.optLong("osm_id"); poi.mLocation = new GeoPoint(jPlace.getDouble("lat"), jPlace.getDouble("lon")); poi.mCategory = jPlace.optString("class"); poi.mType = jPlace.getString("type"); poi.mDescription = jPlace.optString("display_name"); poi.mThumbnailPath = jPlace.optString("icon", null); if (i == 0 && poi.mThumbnailPath != null) { // first POI, and we have a thumbnail: load it thumbnail = BonusPackHelper.loadBitmap(poi.mThumbnailPath); } poi.mThumbnail = thumbnail; pois.add(poi); } return pois; } catch (JSONException e) { e.printStackTrace(); return null; } }
private void fitPoints() { if (places == null || places.size() == 0) { return; } // set min and max for two points int nwLat = -90 * 1000000; int nwLng = 180 * 1000000; int seLat = 90 * 1000000; int seLng = -180 * 1000000; // find bounding lats and lngs for (JSONObject place : places) { try { nwLat = Math.max(nwLat, (int) (place.getDouble("latitude") * 1000000)); nwLng = Math.min(nwLng, (int) (place.getDouble("longitude") * 1000000)); seLat = Math.min(seLat, (int) (place.getDouble("latitude") * 1000000)); seLng = Math.max(seLng, (int) (place.getDouble("longitude") * 1000000)); } catch (JSONException e) { e.printStackTrace(); } } GeoPoint center = new GeoPoint((nwLat + seLat) / 2, (nwLng + seLng) / 2); // add padding in each direction int spanLatDelta = (int) (Math.abs(nwLat - seLat) * 1.1); int spanLngDelta = (int) (Math.abs(seLng - nwLng) * 1.1); // pop the baloon for the first pin onTap(0); // fit map to points map.getController().animateTo(center); map.getController().zoomToSpan(spanLatDelta, spanLngDelta); }
private void updatePlaces() { Log.d(TAG, "updatePlaces"); if (map == null) { return; } removePlaces(); try { Iterator<String> keys = MainApplication.places.keys(); while (keys.hasNext()) { String key = keys.next(); JSONObject placeObj = MainApplication.places.getJSONObject(key); Circle circle = map.addCircle( new CircleOptions() .center(new LatLng(placeObj.getDouble("lat"), placeObj.getDouble("lon"))) .radius(placeObj.getInt("rad")) .strokeWidth(0) .fillColor(getResources().getColor(R.color.place_circle))); placesOverlay.add(circle); } } catch (Exception ex) { ex.printStackTrace(); } updatePlaceAddingTipVisibility(); }
public void handleMessage(String event, JSONObject message) { try { if (MESSAGE_ZOOM_RECT.equals(event)) { float x = (float) message.getDouble("x"); float y = (float) message.getDouble("y"); final RectF zoomRect = new RectF(x, y, x + (float) message.getDouble("w"), y + (float) message.getDouble("h")); mTarget.post( new Runnable() { public void run() { animatedZoomTo(zoomRect); } }); } else if (MESSAGE_ZOOM_PAGE.equals(event)) { ImmutableViewportMetrics metrics = getMetrics(); RectF cssPageRect = metrics.getCssPageRect(); RectF viewableRect = metrics.getCssViewport(); float y = viewableRect.top; // attempt to keep zoom keep focused on the center of the viewport float newHeight = viewableRect.height() * cssPageRect.width() / viewableRect.width(); float dh = viewableRect.height() - newHeight; // increase in the height final RectF r = new RectF(0.0f, y + dh / 2, cssPageRect.width(), y + dh / 2 + newHeight); mTarget.post( new Runnable() { public void run() { animatedZoomTo(r); } }); } } catch (Exception e) { Log.e(LOGTAG, "Exception handling message \"" + event + "\":", e); } }
private void assertVariantDetailLevel( VariantDetailLevel detailLevel, JSONObject result, int nVariants) { if (detailLevel.equals(VariantDetailLevel.NONE)) { Assert.assertEquals(0, result.length()); } else { Assert.assertEquals(1, result.length()); JSONArray variants = result.getJSONArray("variants"); // Ensure expected number of variants Assert.assertEquals(nVariants, variants.length()); for (int i = 0; i < nVariants; i++) { JSONObject v = variants.getJSONObject(i); Assert.assertNotNull(v); if (detailLevel.equals(VariantDetailLevel.FULL)) { // Ensure full variant details displayed Assert.assertTrue(v.length() > 4); Assert.assertTrue(v.getDouble("score") > 0); Assert.assertFalse(v.getString("chrom").isEmpty()); Assert.assertTrue(v.getInt("position") > 0); Assert.assertFalse(v.getString("ref").isEmpty()); Assert.assertFalse(v.getString("alt").isEmpty()); Assert.assertFalse(v.getString("type").isEmpty()); } else if (detailLevel.equals(VariantDetailLevel.LIMITED)) { // Ensure limited variant details displayed Assert.assertEquals(2, v.length()); Assert.assertTrue(v.getDouble("score") > 0); Assert.assertFalse(v.getString("type").isEmpty()); } } } }
private void parseStep(JSONObject step) { try { travelMode = step.getString("travel_mode"); if (!step.isNull("start_location")) { JSONObject pos = step.getJSONObject("start_location"); start = new LatLng(pos.getDouble("lat"), pos.getDouble("lng")); } if (!step.isNull("end_location")) { JSONObject pos = step.getJSONObject("end_location"); end = new LatLng(pos.getDouble("lat"), pos.getDouble("lng")); } if (!step.isNull("duration")) { JSONObject pos = step.getJSONObject("duration"); duration = pos.getString("text"); } if (!step.isNull("distance")) { JSONObject pos = step.getJSONObject("distance"); distance = pos.getString("text"); } if (!step.isNull("polyline")) { JSONObject pos = step.getJSONObject("polyline"); decodePoly(pos.getString("points")); // Log.d("Step count", String.valueOf(stepLine.size())); } instructions = step.getString("html_instructions"); } catch (JSONException e) { e.printStackTrace(); } }
public Departure(JSONObject departureInfo) throws JSONException { // Parse the JSON properties into their corresponding fields. this.Actual = departureInfo.getBoolean("Actual"); this.BlockNumber = departureInfo.getInt("BlockNumber"); this.DepartureText = departureInfo.getString("DepartureText"); this.Description = departureInfo.getString("Description"); this.Gate = departureInfo.getString("Gate"); this.Route = departureInfo.getString("Route"); this.RouteDirection = Direction.fromString(departureInfo.getString("RouteDirection")); this.Terminal = departureInfo.getString("Terminal"); this.VehicleHeading = departureInfo.getInt("VehicleHeading"); this.VehicleLatitude = departureInfo.getDouble("VehicleLatitude"); this.VehicleLongitude = departureInfo.getDouble("VehicleLongitude"); // Parse DepartureTime String departureTimeStr = departureInfo.getString("DepartureTime"); String timeString = departureTimeStr.substring( departureTimeStr.indexOf("(") + 1, departureTimeStr.indexOf(")")); long millis; int timeZoneOffSet = 0; if (timeString.contains("+") || timeString.contains("-")) { String[] timeSegments = timeString.split("[-+]"); millis = Long.valueOf(timeSegments[0]); // timeZoneOffSet = Integer.valueOf(timeSegments[1]) * 36000; // (("0100" / 100) * // 3600 * 1000) // if (timeString.contains("-")) // timeZoneOffSet = -timeZoneOffSet; } else { millis = Long.valueOf(timeString); } this.DepartureTime = new Date(millis + timeZoneOffSet); }
/** * * Convierte un String JSON en una lista de objetos que parten de la clase Registro, es decir, * retorna una lista de objetos que pueden ser RegistroGPS y RegistroAcelerometro * * @param cadena La cadena con contenido JSON * @return Una LinkedList con objetos de clases que hereden a Registro (En este momento * RegistroGPS y RegistroAcelerometro) */ private static LinkedList<Registro> crearJSON(String cadena) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); LinkedList<Registro> respuesta = new LinkedList<Registro>(); try { JSONArray array = new JSONArray(cadena); int cantRegistros = array.length(); Registro registroActual = null; for (int i = 0; i < cantRegistros; i++) { JSONObject objetoRegistro = array.getJSONObject(i); Date timestamp = sdf.parse(objetoRegistro.getString("timestamp")); String tipo = objetoRegistro.getString("tipo"); if (RegistroAcelerometro.TIPO.equals(tipo)) { float ejeX = (float) objetoRegistro.getDouble("ejeX"); float ejeY = (float) objetoRegistro.getDouble("ejeY"); float ejeZ = (float) objetoRegistro.getDouble("ejeZ"); registroActual = new RegistroAcelerometro(timestamp, ejeX, ejeY, ejeZ); } else if (RegistroGPS.TIPO.equals(tipo)) { double latitud = objetoRegistro.getDouble("latitud"); double longitud = objetoRegistro.getDouble("longitud"); float precision = (float) objetoRegistro.getDouble("precision"); registroActual = new RegistroGPS(timestamp, latitud, longitud, precision); } // Sea cual sea el tipo, se agrega a la lista de resultados. respuesta.add(registroActual); } } catch (Exception whatever) { System.out.println(whatever.getMessage()); whatever.printStackTrace(); } return respuesta; }
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex) throws JSONException { // TODO: add parsing code here double max = 0; String jsonString = ""; JSONObject jsonObject; try { jsonObject = new JSONObject(weatherJsonStr); JSONArray jsonArray = jsonObject.getJSONArray("list"); // ArrayList maximumList = new ArrayList<>(); // for (int i = 0; i < jsonArray.length(); i++) { JSONObject tempObject = jsonArray.getJSONObject(dayIndex).getJSONObject("temp"); double min = tempObject.getDouble("min"); max = tempObject.getDouble("max"); // maximumList.add(max); JSONArray weatherArray = jsonArray.getJSONObject(dayIndex).getJSONArray("weather"); String main = weatherArray.getJSONObject(0).getString("main"); // } } catch (JSONException e) { e.printStackTrace(); } return max; }
public sp_GetProvidesByArea_Result(JSONObject obj) { try { if (!obj.isNull("id")) id = obj.getString("id"); if (!obj.isNull("photo")) photo = obj.getString("photo"); if (!obj.isNull("lat")) lat = obj.getDouble("lat"); if (!obj.isNull("lon")) lon = obj.getDouble("lon"); if (!obj.isNull("bidding_id")) bidding_id = obj.getString("bidding_id"); if (!obj.isNull("title")) title = obj.getString("title"); if (!obj.isNull("name")) name = obj.getString("name"); if (!obj.isNull("min_price")) min_price = obj.getInt("min_price"); if (!obj.isNull("description")) description = obj.getString("description"); if (!obj.isNull("user_id")) user_id = obj.getString("user_id"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private Current getCurrentDetails(String weatherData) throws JSONException { // Need a try catch block to fix the error when you first do this // OR WE CAN THROW AN EXCEPTION IN THE METHOD DECLARATION!! // ~ TO MAKE THE throws WORK, WE NEED TO CATCH THE EXCEPTION IN THE TRY CATCH BLOCK ABOVE IN THE // MAIN CLASS JSONObject forecast = new JSONObject(weatherData); // Creates a JSONObject instance to work with the JSON data String timezone = forecast.getString("timezone"); Log.i(TAG, "The timezone from JSON is: " + timezone); JSONObject currently = forecast.getJSONObject( "currently"); // Gets the whole JSON "currently" object for you to parse through Current current = new Current(); // Declares a Current object to set values for WITH THE JSON object's // (currently) data current.setHumidity(currently.getDouble("humidity")); current.setPrecipChance(currently.getDouble("precipProbability")); current.setIcon( currently.getString("icon")); // Retrieves the icon value for our mIcon in Current current.setSummary(currently.getString("summary")); current.setTemperature(currently.getDouble("temperature")); current.setTime( (currently.getLong( "time"))); // Pulling all these values from JSON keys and setting our Current's mVars current.setTimeZone(timezone); current.setWind((currently.getInt("windSpeed"))); Log.d(TAG, current.getFormattedTime()); return current; }
protected void createAndSaveClick(String hash, HttpServletRequest request) { /* Gets the IP from the request, and looks in the db for its country */ String dirIp = extractIP(request); BigInteger valueIp = getIpValue(dirIp); Ip subnet = ipRepository.findSubnet(valueIp); String country = (subnet != null) ? (subnet.getCountry()) : (""); request.getHeader(USER_AGENT); JSONObject jn = getFreegeoip(request); String city = jn.getString("city"); Float latitude = new Float(jn.getDouble("latitude")); Float longitude = new Float(jn.getDouble("longitude")); Click cl = new Click( null, hash, new Date(System.currentTimeMillis()), request.getHeader(REFERER), request.getHeader(USER_AGENT), request.getHeader(USER_AGENT), dirIp, country, city, longitude, latitude); cl = clickRepository.save(cl); logger.info( cl != null ? "[" + hash + "] saved with id [" + cl.getId() + "]" : "[" + hash + "] was not saved"); }
/** * バッテリー全属性取得テストを行う. * * <pre> * 【HTTP通信】 * Method: GET * Path: /battery?deviceid=xxxx * </pre> * * <pre> * 【期待する動作】 * ・resultに0が返ってくること。 * ・chargingがfalseで返ってくること。 * ・chargingtimeが50000で返ってくること。 * ・dischargingtimeが10000で返ってくること。 * ・levelが0.5で返ってくること。 * </pre> */ public void testGetBattery() { URIBuilder builder = TestURIBuilder.createURIBuilder(); builder.setProfile(BatteryProfileConstants.PROFILE_NAME); builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()); builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken()); try { HttpUriRequest request = new HttpGet(builder.toString()); JSONObject root = sendRequest(request); assertResultOK(root); assertEquals( "charging is not equals.", TestBatteryProfileConstants.CHARGING, root.getBoolean(BatteryProfileConstants.ATTRIBUTE_CHARGING)); assertEquals( "chargingtime is not equals.", TestBatteryProfileConstants.CHARGING_TIME, root.getDouble(BatteryProfileConstants.ATTRIBUTE_CHARGING_TIME)); assertEquals( "dischargingtime is not equals.", TestBatteryProfileConstants.DISCHARGING_TIME, root.getDouble(BatteryProfileConstants.ATTRIBUTE_DISCHARGING_TIME)); assertEquals( "level is not equals.", TestBatteryProfileConstants.LEVEL, root.getDouble(BatteryProfileConstants.ATTRIBUTE_LEVEL)); } catch (JSONException e) { fail("Exception in JSONObject." + e.getMessage()); } }
public sp_GetMyActiveProvides_Result(JSONObject obj) { try { if (!obj.isNull("provide_id")) provide_id = obj.getString("provide_id"); if (!obj.isNull("min_price")) min_price = obj.getInt("min_price"); if (!obj.isNull("lat")) lat = obj.getDouble("lat"); if (!obj.isNull("lon")) lon = obj.getDouble("lon"); if (!obj.isNull("status")) status = obj.getInt("status"); if (!obj.isNull("bidding_count")) bidding_count = obj.getInt("bidding_count"); if (!obj.isNull("title")) title = obj.getString("title"); if (!obj.isNull("matching_count")) matching_count = obj.getInt("matching_count"); if (!obj.isNull("description")) description = obj.getString("description"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
private void parseJSONArray(JSONArray checkIns) { if (checkIns == null) return; try { for (int i = 0; i < checkIns.length(); i++) { JSONObject checkIn = checkIns.getJSONObject(i); NotUsedCheckInPostItem postItem = new NotUsedCheckInPostItem(); postItem.setCheckInId(checkIn.getLong(TAG_CHECKIN)); Log.d(LOGTAG, "TEST ::: checkin post item id : " + checkIn.getLong(TAG_CHECKIN)); postItem.setAuthorId(checkIn.getInt(TAG_AUTHOR)); postItem.setPageId(checkIn.getInt(TAG_PAGE)); postItem.setAppId(checkIn.getInt(TAG_APP)); postItem.setPostId(checkIn.getString(TAG_POST)); postItem.setTaggedIds(checkIn.getJSONArray(TAG_TAGGED_IDS)); JSONObject coordObject = checkIn.getJSONObject(TAG_COORDS); postItem.setCoords( coordObject.getDouble(TAG_COORDS_LONG), coordObject.getDouble(TAG_COORDS_LAT)); postItem.setTimeStamp(checkIn.getInt(TAG_TIMESTAMP)); postItem.setMessage(checkIn.getString(TAG_MESSAGE)); } } catch (JSONException e) { e.printStackTrace(); } }
private NetmeraDeviceDetail jsonArraytoNetmeraDeviceDetail(JSONArray array) throws JSONException, NetmeraException { NetmeraDeviceDetail deviceDetail = new NetmeraDeviceDetail(senderID); JSONObject obj = array.getJSONObject(0); if (obj.has("tags")) { JSONArray tags = obj.getJSONArray("tags"); ArrayList<String> group = new ArrayList<String>(); for (int i = 0; i < tags.length(); i++) { group.add(tags.getString(i)); } deviceDetail.setDeviceGroups(group); } if (obj.has("location")) { JSONObject location = obj.getJSONObject("location"); NetmeraGeoLocation geoLocation = new NetmeraGeoLocation(); double latitude = location.getDouble("latitude"); double longitude = location.getDouble("longitude"); geoLocation.setLatitude(latitude); geoLocation.setLongitude(longitude); deviceDetail.setDeviceLocation(geoLocation); } return deviceDetail; }
private static List<Box> parseBoundingBoxes(JSONArray jPositions) throws JSONException { List<Box> boxes = new ArrayList<Box>(); for (int i = 0; i < jPositions.length(); i++) { JSONObject jBox = jPositions.getJSONObject(i); Point topLeft = null; Point bottomRight = null; Integer page = null; if (jBox.has("page")) { page = jBox.getInt("page"); } if (jBox.has("top_left")) { JSONObject jTopLeft = jBox.getJSONObject("top_left"); topLeft = new Point(jTopLeft.getDouble("x"), jTopLeft.getDouble("y")); } if (jBox.has("bottom_right")) { JSONObject jBottomRight = jBox.getJSONObject("bottom_right"); bottomRight = new Point(jBottomRight.getDouble("x"), jBottomRight.getDouble("y")); } Box box = new Box(topLeft, bottomRight, page); boxes.add(box); } return boxes; }
public ArrayList<ComprobanteVentaDetalle> parserComprobanteVentaDetalle(JSONObject object) { ArrayList<ComprobanteVentaDetalle> arrayList = new ArrayList<ComprobanteVentaDetalle>(); try { JSONArray jsonArray = object.getJSONArray("Value"); JSONObject jsonObj = null; for (int i = 0; i < jsonArray.length(); i++) { jsonObj = jsonArray.getJSONObject(i); Log.d("CANTIDAD HCA", "" + jsonObj.getInt("ComdICantidad")); arrayList.add( new ComprobanteVentaDetalle( jsonObj.getInt("idComprobVentDetalle"), jsonObj.getInt("EstIEstablecimientoId"), jsonObj.getInt("ComIAgenteVentaId"), jsonObj.getInt("ProIProductoId"), jsonObj.getString("ProVNombre"), jsonObj.getInt("ComdICantidad"), jsonObj.getDouble("importe"), jsonObj.getDouble("costoVenta"), jsonObj.getDouble("precioUnitario"), jsonObj.getString("PromedioVenta"), jsonObj.getString("CantDevolucion"), jsonObj.getInt("UniIValor"), Constants._IMPORTADO)); } } catch (JSONException e) { // TODO Auto-generated catch block Log.d("JSONParser => parseComprobanteVentaDetalle", e.getMessage()); } return arrayList; }
private void parsePosition(String json) { position = new ArrayList<FriendsPositionModel>(); try { JSONObject jObj = new JSONObject(json); int status = jObj.getInt("status"); JSONArray jFriends = jObj.getJSONArray("data"); for (int i = 0; i < jFriends.length(); i++) { JSONObject jFriend = jFriends.getJSONObject(i); String id = jFriend.getString(ID); Double latitude = jFriend.getDouble(LATITUDE); Double longitude = jFriend.getDouble(LONGITUDE); FriendsPositionModel positionModel = new FriendsPositionModel(id, latitude, longitude, new Date()); position.add(positionModel); } } catch (Exception e) { Log.e(LOG_TAG, "Fehler beim Parsen der Position: " + e.getMessage()); e.printStackTrace(); } }
private void buildModelMap(String jsonString) throws JSONException { mModelMap = new HashMap<AndroidModel, DistanceCalculator>(); JSONObject jsonObject = new JSONObject(jsonString); JSONArray array = jsonObject.getJSONArray("models"); for (int i = 0; i < array.length(); i++) { JSONObject modelObject = array.getJSONObject(i); boolean defaultFlag = false; if (modelObject.has("default")) { defaultFlag = modelObject.getBoolean("default"); } Double coefficient1 = modelObject.getDouble("coefficient1"); Double coefficient2 = modelObject.getDouble("coefficient2"); Double coefficient3 = modelObject.getDouble("coefficient3"); String version = modelObject.getString("version"); String buildNumber = modelObject.getString("build_number"); String model = modelObject.getString("model"); String manufacturer = modelObject.getString("manufacturer"); CurveFittedDistanceCalculator distanceCalculator = new CurveFittedDistanceCalculator(coefficient1, coefficient2, coefficient3); AndroidModel androidModel = new AndroidModel(version, buildNumber, model, manufacturer); mModelMap.put(androidModel, distanceCalculator); if (defaultFlag) { mDefaultModel = androidModel; } } }
private Place buildPlace(JSONObject json) { Place place = new Place(); place.setAddressString(json.getJSONObject("address_obj").getString("address_string")); Coordinates coord = new Coordinates(json.getDouble("latitude"), json.getDouble("longitude")); if (coord.getLat() != 0 || coord.getLon() != 0) { place.setCoord(coord); } place.setId(json.getString("location_id")); place.setName(json.getString("name")); Rating rating = new Rating(); rating.setRating(json.getDouble("rating")); rating.setRevisions(json.getInt("num_reviews")); place.setRating(rating); if (json.has("price_level") && !json.isNull("price_level")) { place.setPriceLevel(json.getString("price_level").length()); } else { place.setPriceLevel(-1); } place.setPhotoId(place.getId()); place.setProvider(providerId); return place; }
public Event(JSONObject event) throws JSONException { name = event.getString("name"); numParticipants = event.getInt("numParticipants"); loclong = event.getDouble("loclong"); loclat = event.getDouble("loclat"); participants = event.getJSONArray("participants"); createParticipants(); }
public void updateSignpostDealToWelocally(JSONObject deal) throws JSONException { JSONObject location = deal.getJSONObject("location"); Point p = new Point(location.getDouble("latitude"), location.getDouble("longitude")); deal.put("_id", idGen.genPoint("WLD_", p)); }