List of usage examples for org.json JSONObject getInt
public int getInt(String key) throws JSONException
From source file:ru.otdelit.astrid.opencrx.sync.OpencrxSyncProvider.java
/** Create a task container for the given RtmTaskSeries * @throws JSONException/*from w w w . j a v a 2s . c o m*/ * @throws IOException * @throws ApiServiceException */ private OpencrxTaskContainer parseRemoteTask(JSONObject remoteTask) throws JSONException, ApiServiceException, IOException { String resourceId = Preferences.getStringValue(OpencrxUtilities.PREF_RESOURCE_ID); String crxId = remoteTask.getString("repeating_value"); JSONArray labels = invoker.resourcesShowForTask(crxId); int secondsSpentOnTask = invoker.getSecondsSpentOnTask(crxId, resourceId); Task task = new Task(); ArrayList<Metadata> metadata = new ArrayList<Metadata>(); if (remoteTask.has("task")) remoteTask = remoteTask.getJSONObject("task"); task.setValue(Task.TITLE, ApiUtilities.decode(remoteTask.getString("title"))); task.setValue(Task.NOTES, remoteTask.getString("detailedDescription")); task.setValue(Task.CREATION_DATE, ApiUtilities.producteevToUnixTime(remoteTask.getString("time_created"), 0)); task.setValue(Task.COMPLETION_DATE, remoteTask.getInt("status") == 1 ? DateUtilities.now() : 0); task.setValue(Task.DELETION_DATE, remoteTask.getInt("deleted") == 1 ? DateUtilities.now() : 0); task.setValue(Task.ELAPSED_SECONDS, secondsSpentOnTask); task.setValue(Task.MODIFICATION_DATE, remoteTask.getLong("modifiedAt")); long dueDate = ApiUtilities.producteevToUnixTime(remoteTask.getString("deadline"), 0); if (remoteTask.optInt("all_day", 0) == 1) task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY, dueDate)); else task.setValue(Task.DUE_DATE, Task.createDueDate(Task.URGENCY_SPECIFIC_DAY_TIME, dueDate)); task.setValue(Task.IMPORTANCE, 5 - remoteTask.getInt("star")); for (int i = 0; i < labels.length(); i++) { JSONObject label = labels.getJSONObject(i); Metadata tagData = new Metadata(); tagData.setValue(Metadata.KEY, OpencrxDataService.TAG_KEY); tagData.setValue(OpencrxDataService.TAG, label.getString("name")); metadata.add(tagData); } OpencrxTaskContainer container = new OpencrxTaskContainer(task, metadata, remoteTask); return container; }
From source file:asynctasks.UpdateTicketDataAsync.java
@Override protected void onPostExecute(JSONObject json) { pDialog.cancel();/* w w w . j a v a 2s. co m*/ int success; try { success = json.getInt("success"); if (success == 1) { SavePicker frag = (SavePicker) fm.findFragmentByTag("Save"); frag.iCcallback.updateTicket(true); frag.dialog.dismiss(); Toast.makeText(context, "Updated Woot", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(context, "ERROR IN SUBMISSION", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:com.asd.littleprincesbeauty.data.Task.java
@Override public void setContentByLocalJSON(JSONObject js) { if (js == null || !js.has(GTaskStringUtils.META_HEAD_NOTE) || !js.has(GTaskStringUtils.META_HEAD_DATA)) { Log.w(TAG, "setContentByLocalJSON: nothing is avaiable"); }//from w ww. java 2 s . c o m try { JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); if (note.getInt(NoteColumns.TYPE) != Notes.TYPE_NOTE) { Log.e(TAG, "invalid type"); return; } for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); if (TextUtils.equals(data.getString(DataColumns.MIME_TYPE), DataConstants.NOTE)) { setName(data.getString(DataColumns.CONTENT)); break; } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } }
From source file:com.iespuig.attendancemanager.StudentFetchr.java
public ArrayList<Student> fetchStudent(Classblock classBlock) { ArrayList<Student> items = new ArrayList<Student>(); SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(context); String schoolName = SP.getString(("schoolName"), ""); String urlServer = SP.getString("urlServer", ""); Format formatter = new SimpleDateFormat("ddMMyyyy"); try {/* w w w . ja v a2s .c o m*/ String url = Uri.parse(urlServer).buildUpon().appendQueryParameter("action", ACTION_GET_STUDENTS) .appendQueryParameter("school", schoolName) .appendQueryParameter("login", User.getInstance().getLogin()) .appendQueryParameter("password", User.getInstance().getPassword()) .appendQueryParameter("idGroup", String.valueOf(classBlock.getIdGroup())) .appendQueryParameter("idClassBlock", String.valueOf(classBlock.getId())) .appendQueryParameter("date", formatter.format(classBlock.getDate())).build().toString(); Log.i(TAG, "url: " + url); String data = AtmNet.getUrl(url); Log.i(TAG, "url: " + data); JSONObject jsonObject = new JSONObject(data); JSONArray jsonArray = new JSONArray(jsonObject.getString("data")); for (int i = 0; i < jsonArray.length(); i++) { JSONObject row = jsonArray.getJSONObject(i); Student item = new Student(); item.setId(row.getInt("id")); item.setFullname(row.getString("fullname")); item.setName(row.getString("name")); item.setSurname1(row.getString("surname1")); item.setSurname2(row.getString("surname2")); item.setMissType(0); item.setNotMaterial(false); item.setNetworkTransit(false); if (row.has("misses")) { JSONArray misses = row.getJSONArray("misses"); for (int j = 0; j < misses.length(); j++) { int miss = misses.getInt(j); if (miss > NOT_MISS && miss <= EXPULSION) { item.setMissType(miss); } if (miss == NOT_MATERIAL) item.setNotMaterial(true); } } items.add(item); } } catch (IOException ioe) { Log.e(TAG, "Failed to fetch items", ioe); } catch (JSONException je) { Log.e(TAG, "Failed to parse JSON", je); } return items; }
From source file:edu.asu.msse.gnayak2.main.CollectionSkeleton.java
public String callMethod(String request) { JSONObject result = new JSONObject(); try {/*from ww w .j av a2 s .co m*/ JSONObject theCall = new JSONObject(request); System.out.println(request); String method = theCall.getString("method"); int id = theCall.getInt("id"); JSONArray params = null; if (!theCall.isNull("params")) { params = theCall.getJSONArray("params"); System.out.println(params); } result.put("id", id); result.put("jsonrpc", "2.0"); if (method.equals("resetFromJsonFile")) { mLib.resetFromJsonFile(); result.put("result", true); System.out.println("resetFromJsonCalled"); } else if (method.equals("remove")) { String sName = params.getString(0); boolean removed = mLib.remove(sName); System.out.println(sName + " deleted"); result.put("result", removed); } else if (method.equals("add")) { MovieImpl movie = new MovieImpl(params.getString(0)); boolean added = mLib.add(movie); result.put("result", added); } else if (method.equals("get")) { String sName = params.getString(0); MovieImpl movie = mLib.get(sName); result.put("result", movie.toJson()); } else if (method.equals("getNames")) { String[] names = mLib.getNames(); JSONArray resArr = new JSONArray(); for (int i = 0; i < names.length; i++) { resArr.put(names[i]); } result.put("result", resArr); } else if (method.equals("saveToJsonFile")) { boolean saved = mLib.saveToJsonFile(); result.put("result", saved); } else if (method.equals("getModelInformation")) { //mLib.resetFromJsonFile(); result.put("result", mLib.getModelInformation()); } else if (method.equals("update")) { String movieJSONString = params.getString(0); Movie mo = new MovieImpl(movieJSONString); mLib.updateMovie(mo); } else if (method.equals("deleteAndAdd")) { String oldMovieJSONString = params.getString(0); String editedMovieJSONString = params.getString(1); boolean deletionSuccessful = false; boolean additionSuccessful = false; MovieImpl oldMovie = new MovieImpl(oldMovieJSONString); MovieImpl newMovie = new MovieImpl(editedMovieJSONString); deletionSuccessful = mLib.deleteMovie(oldMovie); additionSuccessful = mLib.add(newMovie); result.put("result", deletionSuccessful & additionSuccessful); } } catch (Exception ex) { System.out.println("exception in callMethod: " + ex.getMessage()); } System.out.println("returning: " + result.toString()); return "HTTP/1.0 200 Data follows\nServer:localhost:8080\nContent-Type:text/plain\nContent-Length:" + (result.toString()).length() + "\n\n" + result.toString(); }
From source file:org.immopoly.android.api.IS24ApiService.java
/** * Runs an IS2 search with the given lat,lon,r * Returns at most 'max' Flats or null if there are less than 'min' flats. * @param lat Latitude/* w w w . j av a2 s. c o m*/ * @param lon Longitude * @param r Radius * @param min minimum nuber of flats * @param max maximum nuber of flats * @return Flats or null * @throws JSONException. MalformedURLException, NullPointerException */ private Flats loadFlats(double lat, double lon, float r, int min, int max) throws JSONException, MalformedURLException { Log.d(Const.LOG_TAG, "IS24 search: Lat: " + lat + " Lon: " + lon + " R: " + r + " min: " + min + " max: " + max); // get the first result page and extract paging info JSONObject json = loadPage(lat, lon, r, 1); // IS24 page nr starts at 1 JSONObject resultList = json.getJSONObject("resultlist.resultlist"); JSONObject pagingInfo = resultList.getJSONObject("paging"); int numPages = pagingInfo.getInt("numberOfPages"); int results = pagingInfo.getInt("numberOfHits"); int pageSize = pagingInfo.getInt("pageSize"); Log.d(Const.LOG_TAG, "IS24 search got first page, numPages: " + numPages + " results: " + results + " pageSize: " + pageSize); // return if there aren't enough results if (results < min || numPages * pageSize < min || results <= 0) return null; // parse flats from 1st result page Flats flats = new Flats(max); flats.parse(json); // calc pages to get int pages = max / pageSize; if (pages >= 0 && max % pageSize > 0) pages++; if (pages > numPages) // if this happens theres something wrong here or in the json pages = numPages; // evtly get more pages for (int i = 2; i <= pages; i++) { json = loadPage(lat, lon, r, i); flats.parse(json); Log.d(Const.LOG_TAG, "IS24 search got page " + i + "/" + pages + " #flats: " + flats.size()); } // restrict number of results if (flats.size() > max) { Flats lessFlats = new Flats(max); lessFlats.addAll(flats.subList(0, max)); flats = lessFlats; } return flats; }
From source file:com.theaigames.game.warlight2.MapCreator.java
/** * @param mapString : string that represents the map to be created * @return : a Map object to use in the game */// ww w. j a va2 s . c om public static Map createMap(String mapString) { Map map = new Map(); //parse the map string try { JSONObject jsonMap = new JSONObject(mapString); // create SuperRegion objects JSONArray superRegions = jsonMap.getJSONArray("SuperRegions"); for (int i = 0; i < superRegions.length(); i++) { JSONObject jsonSuperRegion = superRegions.getJSONObject(i); map.add(new SuperRegion(jsonSuperRegion.getInt("id"), jsonSuperRegion.getInt("bonus"))); } // create Region object JSONArray regions = jsonMap.getJSONArray("Regions"); for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); SuperRegion superRegion = map.getSuperRegion(jsonRegion.getInt("superRegion")); map.add(new Region(jsonRegion.getInt("id"), superRegion)); } // add the Regions' neighbors for (int i = 0; i < regions.length(); i++) { JSONObject jsonRegion = regions.getJSONObject(i); Region region = map.getRegion(jsonRegion.getInt("id")); JSONArray neighbors = jsonRegion.getJSONArray("neighbors"); for (int j = 0; j < neighbors.length(); j++) { Region neighbor = map.getRegion(neighbors.getInt(j)); region.addNeighbor(neighbor); } } } catch (JSONException e) { System.err.println("JSON: Can't parse map string: " + e); } map.sort(); return map; }
From source file:com.example.pyrkesa.shwc.OngoingNotificationListenerService.java
@Override public void onDataChanged(DataEventBuffer dataEvents) { final List<DataEvent> events = FreezableUtils.freezeIterable(dataEvents); final String ACTION_DEMAND = "ACTION_DEMAND"; String EXTRA_CMD = "EXTRA_CMD"; dataEvents.close();// w ww. j av a 2 s.c o m if (!mGoogleApiClient.isConnected()) { ConnectionResult connectionResult = mGoogleApiClient.blockingConnect(30, TimeUnit.SECONDS); if (!connectionResult.isSuccess()) { Log.e(TAG, "Service failed to connect to GoogleApiClient."); return; } } for (DataEvent event : events) { if (event.getType() == DataEvent.TYPE_CHANGED) { String path = event.getDataItem().getUri().getPath(); if (PATH.equals(path)) { // Get the data out of the event DataMapItem dataMapItem = DataMapItem.fromDataItem(event.getDataItem()); //final String title = dataMapItem.getDataMap().getString(KEY_TITLE); final String room_devices = dataMapItem.getDataMap().getString(KEY_ROOM_DEVICES); final String room_name = dataMapItem.getDataMap().getString(KEY_ROOM_NAME); // Asset asset = dataMapItem.getDataMap().getAsset(KEY_BACKGROUND); try { JSONObject roomJSON = new JSONObject(room_devices); JSONArray devicesArray = roomJSON.getJSONArray("devices"); String firstPageText = "quipements :"; ArrayList<Device> devicess = new ArrayList<Device>(); for (int i = 0; i < devicesArray.length(); i++) { JSONObject d = devicesArray.getJSONObject(i); Device device = new Device(d.getString("id"), d.getString("name"), d.getInt("type"), d.getString("status")); String Newline = System.getProperty("line.separator"); firstPageText += Newline; firstPageText += device.name; devicess.add(device); } if (firstPageText.equalsIgnoreCase("quipements :")) { firstPageText = "Aucun quipement"; } Bitmap background = BitmapFactory.decodeResource(this.getResources(), R.drawable.bg_distance); NotificationCompat.WearableExtender notifExtender = new NotificationCompat.WearableExtender(); for (Device d : devicess) { try { notifExtender.addAction(d.getAction(OngoingNotificationListenerService.this)); } catch (Exception e) { Log.e("Erreur get Action :", e.getMessage()); } } NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this) .setContentTitle("Pice : " + roomJSON.getString("name")) .setContentText(firstPageText).setSmallIcon(R.drawable.mini_logo) .extend(notifExtender.setBackground(background)).setOngoing(true); // Build the notification and show it NotificationManager notificationManager = (NotificationManager) getSystemService( NOTIFICATION_SERVICE); notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build()); } catch (Throwable t) { Log.e("JSON_WEAR_SHWC", "Could not parse malformed JSON: " + room_devices + t.getMessage()); } } else { Log.d(TAG, "Unrecognized path: " + path); } } } }
From source file:edu.umass.cs.protocoltask.examples.PingPongPacket.java
public PingPongPacket(JSONObject json) throws JSONException { super(json, unstringer); this.setType(getPacketType(json)); this.counter = (json.has(COUNTER) ? json.getInt(COUNTER) : 0); }
From source file:com.sonoport.freesound.response.mapping.Mapper.java
/** * Extract a named value from a {@link JSONObject}. This method checks whether the value exists and is not an * instance of <code>JSONObject.NULL</code>. * * @param jsonObject The {@link JSONObject} being processed * @param field The field to retrieve/* w w w .j av a2 s .c om*/ * @param fieldType The data type of the field * @return The field value (or null if not found) * * @param <T> The data type to return */ @SuppressWarnings("unchecked") protected <T extends Object> T extractFieldValue(final JSONObject jsonObject, final String field, final Class<T> fieldType) { T fieldValue = null; if ((jsonObject != null) && jsonObject.has(field) && !jsonObject.isNull(field)) { try { if (fieldType == String.class) { fieldValue = (T) jsonObject.getString(field); } else if (fieldType == Integer.class) { fieldValue = (T) Integer.valueOf(jsonObject.getInt(field)); } else if (fieldType == Long.class) { fieldValue = (T) Long.valueOf(jsonObject.getLong(field)); } else if (fieldType == Float.class) { fieldValue = (T) Float.valueOf(Double.toString(jsonObject.getDouble(field))); } else if (fieldType == JSONArray.class) { fieldValue = (T) jsonObject.getJSONArray(field); } else if (fieldType == JSONObject.class) { fieldValue = (T) jsonObject.getJSONObject(field); } else { fieldValue = (T) jsonObject.get(field); } } catch (final JSONException | ClassCastException e) { // TODO Log a warning } } return fieldValue; }