List of usage examples for org.json JSONObject getJSONArray
public JSONArray getJSONArray(String key) throws JSONException
From source file:com.github.secondsun.catfactsdemo.networking.AsyncTaskbasedFactLoader.java
private AsyncTask<Void, Void, List<String>> makeTask() { return new AsyncTask<Void, Void, List<String>>() { @Override/*w w w . j a v a 2 s . c om*/ protected List<String> doInBackground(Void... params) { try { if (data != null && data.size() > 0) { return data; } Thread.sleep(Constants.DELAY); OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder().url(Constants.CAT_FACTS_URL).build(); Response response = client.newCall(request).execute(); JSONObject responseJson = new JSONObject(response.body().string()); JSONArray facts = responseJson.getJSONArray("facts"); ArrayList<String> toReturn = new ArrayList<>(facts.length()); for (int i = 0; i < facts.length(); i++) { toReturn.add(facts.getString(i)); } data = toReturn; return toReturn; } catch (InterruptedException | IOException | JSONException e) { ArrayList<String> toReturn = new ArrayList<>(); toReturn.add("Error:" + e.getMessage()); data = toReturn; return toReturn; } } @Override protected void onPostExecute(List<String> strings) { super.onPostExecute(strings); if (activity != null) { activity.displayFacts(strings); } } }; }
From source file:uk.ac.imperial.presage2.web.export.DataExportServlet.java
/** * Processes the JSON query and returns a table in the form of a double * {@link Iterable}./* www . j av a 2 s .com*/ * * @param query * JSON table specification. * @return An {@link Iterable} which iterates over each row in the result * set, which is also given as an {@link Iterable}. * @throws JSONException * If there is an error in the specification. */ Iterable<Iterable<String>> processRequest(JSONObject query) throws JSONException { // build source set Set<PersistentSimulation> sourceSims = new HashSet<PersistentSimulation>(); Set<Long> sources = new HashSet<Long>(); JSONArray sourcesJSON = query.getJSONArray("sources"); for (int i = 0; i < sourcesJSON.length(); i++) { long simId = sourcesJSON.getLong(i); PersistentSimulation sim = sto.getSimulationById(simId); if (sim != null) { // add simulation and all of it's decendents. getDecendents(simId, sources); } } // build sourceSims set from simIds we have collected. for (Long sim : sources) { sourceSims.add(sto.getSimulationById(sim)); } // check type JSONArray parametersJSON = query.getJSONArray("parameters"); boolean timeSeries = false; List<IndependentVariable> vars = new ArrayList<IndependentVariable>(parametersJSON.length()); for (int i = 0; i < parametersJSON.length(); i++) { if (parametersJSON.getString(i).equalsIgnoreCase("time")) timeSeries = true; else vars.add(new ParameterColumn(sourceSims, parametersJSON.getString(i))); } JSONArray columns = query.getJSONArray("columns"); ColumnDefinition[] columnDefs = new ColumnDefinition[columns.length()]; for (int i = 0; i < columns.length(); i++) { columnDefs[i] = ColumnDefinition.createColumn(columns.getJSONObject(i), timeSeries); columnDefs[i].setSources(sourceSims); } TimeColumn time = timeSeries ? new TimeColumn(sourceSims) : null; return new IterableTable(vars.toArray(new IndependentVariable[] {}), time, sourceSims, columnDefs); }
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);//www . ja v a2s. 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:com.github.sgelb.booket.SearchResultActivity.java
private void processResult(String result) { JSONArray items = null;// www . j a va2s .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 * *//*from w ww. j a va2s . 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 w w w .j a v a 2 s.co 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:org.openqa.selenium.logging.SessionLogs.java
public static SessionLogs fromJSON(JSONObject rawSessionLogs) throws JSONException { SessionLogs sessionLogs = new SessionLogs(); for (Iterator logTypeItr = rawSessionLogs.keys(); logTypeItr.hasNext();) { String logType = (String) logTypeItr.next(); JSONArray rawLogEntries = rawSessionLogs.getJSONArray(logType); List<LogEntry> logEntries = new ArrayList<LogEntry>(); for (int index = 0; index < rawLogEntries.length(); index++) { JSONObject rawEntry = rawLogEntries.getJSONObject(index); logEntries.add(new LogEntry(LogLevelMapping.toLevel(rawEntry.getString("level")), rawEntry.getLong("timestamp"), rawEntry.getString("message"))); }//from ww w . j a va 2 s .c o m sessionLogs.addLog(logType, new LogEntries(logEntries)); } return sessionLogs; }
From source file:cc.vileda.sipgatesync.contacts.SipgateContactSyncAdapter.java
@Override public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {//from w ww. j ava 2s.c o m Log.d("SipgateContactSyncAdapt", "onPerformSync()"); AccountManager accountManager = AccountManager.get(getContext()); final String oauth = accountManager.peekAuthToken(account, "oauth"); Log.d("SipgateContactSyncAdapt", oauth == null ? "NO oauth!" : "Got token"); final JSONArray users = SipgateApi.getContacts(oauth); assert users != null; Log.d("SipgateContactSyncAdapt", String.format("fetched %d contacts", users.length())); Uri rawContactUri = ContactsContract.RawContacts.CONTENT_URI.buildUpon() .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_NAME, account.name) .appendQueryParameter(ContactsContract.RawContacts.ACCOUNT_TYPE, account.type).build(); Cursor c1 = mContentResolver.query(rawContactUri, null, null, null, null); Map<String, Boolean> localContacts = new HashMap<>(); while (c1 != null && c1.moveToNext()) { localContacts.put(c1.getString(c1.getColumnIndex(ContactsContract.RawContacts.SOURCE_ID)), false); } for (int i = 0; i < users.length(); i++) { try { final JSONObject user = users.getJSONObject(i); final String id = user.getString("uuid"); if (localContacts.containsKey(id)) { localContacts.put(id, true); continue; } final String firstname = user.getString("firstname"); final JSONArray emails = user.getJSONArray("emails"); final JSONArray mobile = user.getJSONArray("mobile"); final JSONArray landline = user.getJSONArray("landline"); final JSONArray fax = user.getJSONArray("fax"); Log.d("SipgateContactSyncAdapt", String.format("adding id: %s %s", id, firstname)); ContactManager.addContact(id, firstname, user.getString("lastname"), jsonArrayToList(emails), jsonArrayToList(mobile), jsonArrayToList(landline), jsonArrayToList(fax), mContentResolver, account.name); } catch (JSONException e) { e.printStackTrace(); } } for (Map.Entry<String, Boolean> contact : localContacts.entrySet()) { if (!contact.getValue()) { ContactManager.deleteContact(contact.getKey(), mContentResolver, account.name); } } }
From source file:com.example.android.camera2basic.AgeGender.java
@Override protected String doInBackground(Object... paths) { System.out.println("Performing Visual Recognition..."); // params comes from the execute() call: params[0] is the url. com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition service = new com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition( com.ibm.watson.developer_cloud.visual_recognition.v3.VisualRecognition.VERSION_DATE_2016_05_20); service.setApiKey("26a259b7f5dc0f5c8c1cc933d8722b0e66aed5df"); File actualImageFile = new File((String) paths[0]); // Library link : https://github.com/zetbaitsu/Compressor Bitmap compressedBitmap = Compressor.getDefault(mContext).compressToBitmap(actualImageFile); DirectoryPath = (String) paths[1]; File compressedImage = bitmapToFile(compressedBitmap); System.out.println("The size of image for Age-Gender (in kB) : " + (compressedImage.length() / 1024)); // TODO Image size may be still greater than 1 MB ! System.out.println("Detect faces"); VisualRecognitionOptions options = new VisualRecognitionOptions.Builder().images(compressedImage).build(); DetectedFaces result = service.detectFaces(options).execute(); System.out.println(result);/*w w w . j a v a 2 s.co m*/ try { JSONObject obj = new JSONObject(result.toString()); JSONObject resultarray1 = obj.getJSONArray("images").getJSONObject(0); minAge = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("age").getInt("min"); maxAge = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("age").getInt("max"); gender = resultarray1.getJSONArray("faces").getJSONObject(0).getJSONObject("gender") .getString("gender"); System.out.println("Age Gender : " + minAge + ' ' + maxAge + ' ' + gender); if (minAge == 0 && maxAge == 0 && gender == "") { throw new JSONException("Age,Gender not found"); } // new TextToSpeechTask().execute(classes,DirectoryPath); } catch (JSONException e) { System.out.println("Nothing Detected in Age Gender"); } countDownLatch.countDown(); System.out.println("Latch counted down in AgeGender"); return result.toString(); }
From source file:com.facebook.android.MainPage.java
/** Called when the activity is first created. */ @Override/*from ww w.j a v a 2 s. c om*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (APP_ID == null) { Util.showAlert(this, "Warning", "Facebook Applicaton ID must be " + "specified before running this example: see Example.java"); } setContentView(R.layout.main); mMovieNameInput = (EditText) findViewById(R.id.title); mMediaSpinner = (Spinner) findViewById(R.id.media); mSearchButton = (Button) findViewById(R.id.search); mFacebook = new Facebook(APP_ID); mAsyncRunner = new AsyncFacebookRunner(mFacebook); SessionStore.restore(mFacebook, this); SessionEvents.addAuthListener(new SampleAuthListener()); SessionEvents.addLogoutListener(new SampleLogoutListener()); // set up the Spinner for the media list selection ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.media_list, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); mMediaSpinner.setAdapter(adapter); //for search button final Context context = this; mSearchButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { String servletURL; String movieName = mMovieNameInput.getText().toString(); // check the input text of movie, if the text is empty give user alert movieName = movieName.trim(); if (movieName.length() == 0) { Toast toast = Toast.makeText(context, "Please enter a movie name", Toast.LENGTH_LONG); toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 70); toast.show(); } // if movie name is not empty else { // remove any extra whitespace movieName = movieName.replaceAll("\\s+", "+"); String mediaList = mMediaSpinner.getSelectedItem().toString(); if (mediaList.equals("Feature Film")) { mediaList = "feature"; } mediaList = mediaList.replaceAll("\\s+", "+"); // construct the query string // construct the final URL to Servlet //String servletString = "?" + "title=" + movieName + "&" + "title_type=" + mediaList; //servletURL = "http://cs-server.usc.edu:10854/examples/servlet/Amovie" //+ servletString; //String servletString = "?" + "title=" + movieName + "&" + "media=" + mediaList; //servletURL = "http://cs-server.usc.edu:34404/examples/servlet/HelloWorldExample?title=" + movieName + "&" + "media=" + mediaList; //+ servletString; servletURL = "http://cs-server.usc.edu:10854/examples/servlet/Amovie?title=" + movieName + "&" + "title_type=" + mediaList; BufferedReader in = null; try { // REFERENCE: this part of code is modified from: // "Example of HTTP GET Request using HttpClient in Android" // http://w3mentor.com/learn/java/android-development/android-http-services/example-of-http-get-request-using-httpclient-in-android/ // get response (JSON string) from Servlet HttpClient client = new DefaultHttpClient(); HttpGet request = new HttpGet(); request.setURI(new URI(servletURL)); HttpResponse response = client.execute(request); in = new BufferedReader(new InputStreamReader(response.getEntity().getContent())); StringBuffer sb = new StringBuffer(""); String line = ""; String NL = System.getProperty("line.separator"); while ((line = in.readLine()) != null) { sb.append(line + NL); } in.close(); String page = sb.toString(); //test for JSON string /*LinearLayout lView = new LinearLayout(context); TextView myText = new TextView(context); myText.setText(page); lView.addView(myText); setContentView(lView);*/ // convert the JSON string to real JSON and get out the movie JSON array // to check if there is any movie data JSONObject finalJson; JSONObject movieJson; JSONArray movieJsonArray; finalJson = new JSONObject(page); movieJson = finalJson.getJSONObject("results"); //System.out.println(movieJson); movieJsonArray = movieJson.getJSONArray("result"); // if the response contains some movie data if (movieJsonArray.length() != 0) { // start the ListView activity, and pass the JSON string to it Intent intent = new Intent(context, MovieListActivity.class); intent.putExtra("finalJson", page); startActivity(intent); } // if the response does not contain any movie data, // show user that there is no result for this search else { Toast toast = Toast.makeText(getBaseContext(), "No movie found for this search", Toast.LENGTH_LONG); toast.setGravity(Gravity.CENTER, 0, 0); toast.show(); } } catch (URISyntaxException e) { e.printStackTrace(); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } } } }); }