List of usage examples for org.json JSONObject getLong
public long getLong(String key) throws JSONException
From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java
private long postCheckIn(String attendeeId, String eventId, boolean revert, String cookie) { RequestQueue queue = GutenbergApplication.from(getContext()).getRequestQueue(); RequestFuture<JSONObject> future = RequestFuture.newFuture(); queue.add(new CheckInRequest(cookie, eventId, attendeeId, revert, future, future)); try {//from w w w . j a v a 2s . c om JSONObject object = future.get(); return object.getLong("checkinTime"); } catch (InterruptedException | ExecutionException | JSONException e) { Throwable cause = e.getCause(); if (cause instanceof ServerError) { ServerError error = (ServerError) cause; Log.e(TAG, "Server error: " + new String(error.networkResponse.data)); } Log.e(TAG, "Cannot sync checkin.", e); } return -1; }
From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java
private ContentValues[] parseAttendees(String eventId, JSONArray attendees) throws JSONException { int length = attendees.length(); ContentValues[] array = new ContentValues[length]; HashMap<String, String> imageUrls = new HashMap<>(); for (int i = 0; i < length; ++i) { JSONObject attendee = attendees.getJSONObject(i); array[i] = new ContentValues(); array[i].put(Table.Attendee.EVENT_ID, eventId); array[i].put(Table.Attendee.NAME, attendee.getString("name")); array[i].put(Table.Attendee.ID, attendee.getString("id")); array[i].put(Table.Attendee.EMAIL, attendee.getString("email")); String plusid = attendee.getString("plusid"); if (!TextUtils.isEmpty(plusid)) { array[i].put(Table.Attendee.PLUSID, plusid); imageUrls.put(plusid, "null"); }/*from w w w. j a v a2 s . c om*/ long checkinTime = attendee.getLong("checkinTime"); if (0 == checkinTime) { array[i].putNull(Table.Attendee.CHECKIN); } else { array[i].put(Table.Attendee.CHECKIN, checkinTime); } array[i].putNull(Table.Attendee.IMAGE_URL); } // Fetch all the Google+ Image URLs at once if necessary if (mApiClient != null && mApiClient.isConnected() && !imageUrls.isEmpty()) { People.LoadPeopleResult result = Plus.PeopleApi.load(mApiClient, imageUrls.keySet()).await(); PersonBuffer personBuffer = result.getPersonBuffer(); if (personBuffer != null) { // Copy URLs into the HashMap for (Person person : personBuffer) { if (person.hasImage()) { imageUrls.put(extractId(person.getUrl()), person.getImage().getUrl()); } } // Fill the missing URLs in the array of ContentValues for (ContentValues values : array) { if (values.containsKey(Table.Attendee.PLUSID)) { String plusId = values.getAsString(Table.Attendee.PLUSID); String imageUrl = imageUrls.get(plusId); if (!TextUtils.isEmpty(imageUrl)) { values.put(Table.Attendee.IMAGE_URL, imageUrl); } } } } } return array; }
From source file:com.jellymold.boss.WebSearch.java
/** * Performs a search based on the values of parameters search and filters * * @param search - search string// w w w. j a v a 2s . c o m * @param webSearchFilters - set of filters * @return - HTTP response code * @throws BOSSException runtime exception */ public SpellCheckResult spellCheck(String word) throws BOSSException { SpellCheckResult result = null; try { JSONObject searchResults = new JSONObject(yahooAPI.spellCheck(word)).getJSONObject("bossresponse") .getJSONObject("spelling"); long totalResult = searchResults.getLong("totalresults"); if (totalResult > 0) { result = new SpellCheckResult(); String suggestion = searchResults.getJSONArray("results").getJSONObject(0).getString("suggestion"); result.setSuggestion(suggestion); result.setWord(word); } } catch (JSONException e) { e.printStackTrace(); setResponseCode(500); throw new BOSSException("JSON Exception parsing news search results", e); } catch (Exception ioe) { ioe.printStackTrace(); setResponseCode(500); throw new BOSSException("IO Exception", ioe); } return result; }
From source file:com.jellymold.boss.WebSearch.java
protected void parseResults(JSONObject jobj) throws JSONException { if (jobj != null) { // setResponseCode(jobj.getInt("responsecode")); if (jobj.has("nextpage")) setNextPage(jobj.getString("nextpage")); if (jobj.has("prevpage")) setPrevPage(jobj.getString("prevpage")); setTotalResults(jobj.getLong("totalresults")); long count = jobj.getLong("count"); setPagerCount(count);//from w w w . ja va 2s . c o m setPagerStart(jobj.getLong("start")); this.setResults(new ArrayList<WebSearchResult>(((int) count))); if (jobj.has("results")) { JSONArray res = jobj.getJSONArray("results"); for (int i = 0; i < res.length(); i++) { JSONObject thisResult = res.getJSONObject(i); WebSearchResult newResultWeb = new WebSearchResult(); newResultWeb.setDescription(thisResult.getString("abstract")); newResultWeb.setClickUrl(thisResult.getString("clickurl")); newResultWeb.setDate(thisResult.getString("date")); newResultWeb.setTitle(thisResult.getString("title")); newResultWeb.setDisplayUrl(thisResult.getString("dispurl")); newResultWeb.setUrl(thisResult.getString("url")); // newResultWeb.setSize(thisResult.getLong("size")); this.resultWebs.add(newResultWeb); } } } }
From source file:com.transistorsoft.cordova.bggeo.CDVBackgroundGeolocation.java
private void addGeofence(CallbackContext callbackContext, JSONObject config) { try {//from w w w. jav a 2s.c om String identifier = config.getString("identifier"); final Bundle event = new Bundle(); event.putString("name", BackgroundGeolocationService.ACTION_ADD_GEOFENCE); event.putBoolean("request", true); event.putFloat("radius", (float) config.getLong("radius")); event.putDouble("latitude", config.getDouble("latitude")); event.putDouble("longitude", config.getDouble("longitude")); event.putString("identifier", identifier); if (config.has("notifyOnEntry")) { event.putBoolean("notifyOnEntry", config.getBoolean("notifyOnEntry")); } if (config.has("notifyOnExit")) { event.putBoolean("notifyOnExit", config.getBoolean("notifyOnExit")); } if (config.has("notifyOnDwell")) { event.putBoolean("notifyOnDwell", config.getBoolean("notifyOnDwell")); } if (config.has("loiteringDelay")) { event.putInt("loiteringDelay", config.getInt("loiteringDelay")); } addGeofenceCallbacks.put(identifier, callbackContext); postEvent(event); } catch (JSONException e) { e.printStackTrace(); callbackContext.error(e.getMessage()); } }
From source file:com.dnastack.bob.rest.BasicTest.java
private static String readField(JSONObject field, List<String> path) { for (int i = 1; i < path.size(); i++) { field = field.getJSONObject(path.get(i - 1)); }//from ww w . j av a 2 s. c om String loc = path.get(path.size() - 1); String res; try { res = field.getString(loc); } catch (JSONException je) { try { res = String.valueOf(field.getLong(loc)); } catch (JSONException je2) { try { res = String.valueOf(field.getInt(loc)); } catch (JSONException je3) { try { res = String.valueOf(field.getBoolean(loc)); } catch (JSONException je4) { res = null; } } } } return res; }
From source file:eu.codeplumbers.cosi.api.tasks.SyncDocumentTask.java
@Override protected String doInBackground(JSONObject... jsonObjects) { for (int i = 0; i < jsonObjects.length; i++) { JSONObject jsonObject = jsonObjects[i]; URL urlO = null;//from w ww . j a va 2s . c o m try { publishProgress("Syncing " + jsonObject.getString("docType") + ":", i + "", jsonObjects.length + ""); String remoteId = jsonObject.getString("remoteId"); String requestMethod = ""; if (remoteId.isEmpty()) { urlO = new URL(url); requestMethod = "POST"; } else { urlO = new URL(url + remoteId + "/"); requestMethod = "PUT"; } HttpURLConnection conn = (HttpURLConnection) urlO.openConnection(); conn.setConnectTimeout(5000); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setRequestProperty("Authorization", authHeader); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod(requestMethod); // set request body jsonObject.remove("remoteId"); objectId = jsonObject.getLong("id"); jsonObject.remove("id"); OutputStream os = conn.getOutputStream(); os.write(jsonObject.toString().getBytes("UTF-8")); os.flush(); // read the response InputStream in = new BufferedInputStream(conn.getInputStream()); StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String result = writer.toString(); JSONObject jsonObjectResult = new JSONObject(result); if (jsonObjectResult != null && jsonObjectResult.has("_id")) { result = jsonObjectResult.getString("_id"); if (jsonObject.get("docType").equals("Sms")) { Sms sms = Sms.load(Sms.class, objectId); sms.setRemoteId(result); sms.save(); } if (jsonObject.get("docType").equals("Note")) { Note note = Note.load(Note.class, objectId); note.setRemoteId(result); note.save(); } if (jsonObject.get("docType").equals("Call")) { Call call = Call.load(Call.class, objectId); call.setRemoteId(result); call.save(); } if (jsonObject.get("docType").equals("Expense")) { Expense expense = Expense.load(Expense.class, objectId); expense.setRemoteId(result); expense.save(); } } in.close(); conn.disconnect(); } catch (MalformedURLException e) { result = "error"; e.printStackTrace(); errorMessage = e.getLocalizedMessage(); } catch (ProtocolException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (IOException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } catch (JSONException e) { result = "error"; errorMessage = e.getLocalizedMessage(); e.printStackTrace(); } } return result; }
From source file:se.su.dsv.scipro.android.tasks.LoginAsyncTask.java
@Override protected LoginResult doInBackground(Void... params) { String response = SciProJSON.getInstance().jsonLogin(username, password); boolean authenticated = false; String apikey = ""; long userid = -1; try {/*from w w w . j ava2 s. c om*/ JSONObject jsonObject = new JSONObject(response); authenticated = jsonObject.getBoolean("authenticated"); if (authenticated) { apikey = jsonObject.getString("apikey"); userid = jsonObject.getLong("userid"); } } catch (JSONException e) { Log.e(TAG, "JSONException: ", e); } return new LoginResult(authenticated, username, apikey, userid); }
From source file:com.mparticle.internal.ConfigManager.java
public synchronized void updateConfig(JSONObject responseJSON, boolean persistJson) throws JSONException { SharedPreferences.Editor editor = mPreferences.edit(); if (persistJson) { saveConfigJson(responseJSON);//from w w w . j a v a 2 s.co m } if (responseJSON.has(KEY_UNHANDLED_EXCEPTIONS)) { mLogUnhandledExceptions = responseJSON.getString(KEY_UNHANDLED_EXCEPTIONS); } if (responseJSON.has(KEY_PUSH_MESSAGES)) { sPushKeys = responseJSON.getJSONArray(KEY_PUSH_MESSAGES); editor.putString(KEY_PUSH_MESSAGES, sPushKeys.toString()); } mRampValue = responseJSON.optInt(KEY_RAMP, -1); if (responseJSON.has(KEY_OPT_OUT)) { mSendOoEvents = responseJSON.getBoolean(KEY_OPT_OUT); } else { mSendOoEvents = false; } if (responseJSON.has(ProviderPersistence.KEY_PERSISTENCE)) { setProviderPersistence(new ProviderPersistence(responseJSON, mContext)); } else { setProviderPersistence(null); } mSessionTimeoutInterval = responseJSON.optInt(KEY_SESSION_TIMEOUT, -1); mUploadInterval = responseJSON.optInt(KEY_UPLOAD_INTERVAL, -1); mTriggerMessageMatches = null; mTriggerMessageHashes = null; if (responseJSON.has(KEY_TRIGGER_ITEMS)) { try { JSONObject items = responseJSON.getJSONObject(KEY_TRIGGER_ITEMS); if (items.has(KEY_MESSAGE_MATCHES)) { mTriggerMessageMatches = items.getJSONArray(KEY_MESSAGE_MATCHES); } if (items.has(KEY_TRIGGER_ITEM_HASHES)) { mTriggerMessageHashes = items.getJSONArray(KEY_TRIGGER_ITEM_HASHES); } } catch (JSONException jse) { } } if (responseJSON.has(KEY_INFLUENCE_OPEN)) { mInfluenceOpenTimeout = responseJSON.getLong(KEY_INFLUENCE_OPEN) * 60 * 1000; } else { mInfluenceOpenTimeout = 30 * 60 * 1000; } mRestrictAAIDfromLAT = responseJSON.optBoolean(KEY_AAID_LAT, true); mIncludeSessionHistory = responseJSON.optBoolean(KEY_INCLUDE_SESSION_HISTORY, true); if (responseJSON.has(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED)) { MParticle.setDevicePerformanceMetricsDisabled( responseJSON.optBoolean(KEY_DEVICE_PERFORMANCE_METRICS_DISABLED, false)); } editor.apply(); applyConfig(); MParticle.getInstance().getKitManager().updateKits(responseJSON.optJSONArray(KEY_EMBEDDED_KITS)); }
From source file:com.mohammedsazidalrashid.android.sunshine.ForecastFragment.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. *///from w w w. j a v a 2 s. c o m private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays) throws JSONException { // These are the names of the JSON objects that need to be extracted final String OWM_LIST = "list"; final String OWM_WEATHER = "weather"; final String OWM_TEMPERATURE = "temp"; final String OWM_MAX = "max"; final String OWM_MIN = "min"; final String OWM_DATETIME = "dt"; final String OWM_DESCRIPTION = "description"; JSONObject forecastJson = new JSONObject(forecastJsonStr); JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST); String[] resultStrs = new String[numDays]; for (int i = 0; i < weatherArray.length(); i++) { // For now, using the format Day - description - hi/low String day; String description; String highAndLow; // Get the JSON object representing the day JSONObject dayForecast = weatherArray.getJSONObject(i); long dateTime = dayForecast.getLong(OWM_DATETIME); day = getReadableDateString(dateTime); // description is in a child array, which is 1 element long description = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0).getString(OWM_DESCRIPTION); // Temperatures are in a child object called "temp" JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE); double high = temperatureObject.getDouble(OWM_MAX); double low = temperatureObject.getDouble(OWM_MIN); highAndLow = formatHighLows(high, low); resultStrs[i] = day + " - " + description + " - " + highAndLow; } return resultStrs; }