List of usage examples for org.json JSONObject getString
public String getString(String key) throws JSONException
From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java
private List<DownloadItem> retrieveDatabaseList(DownloadItem category) throws Exception { List<DownloadItem> diList = new LinkedList<DownloadItem>(); String url = SS_API_GET_CATEGORY_CONTENT + category.getExtras("id"); String page = category.getExtras("page"); if (page != null) { url += "&page=" + page; } else {//from w ww .ja va 2 s . c om page = "1"; } JSONArray jsonArray = new JSONArray(downloadJSONString(url)); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonItem = jsonArray.getJSONObject(i); DownloadItem di = new DownloadItem(); di.setType(DownloadItem.TYPE_DATABASE); di.setTitle(jsonItem.getString("stackName")); di.setDescription(jsonItem.getString("description")); di.setExtras("id", jsonItem.getString("id")); di.setAddress(SS_API_GET_DECK + jsonItem.getString("id")); di.setExtras("page", page); if (di.getTitle() != null) { diList.add(di); } } return diList; }
From source file:io.github.medinam.jcheesum.util.VersionChecker.java
public static String getLatestStable() { String version = new String(); try {/*from ww w . j a v a2 s . co m*/ JSONTokener tokener = getVersionTokener(); JSONObject json = new JSONObject(tokener); version = json.getString("version"); } catch (URISyntaxException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } return version; }
From source file:io.github.medinam.jcheesum.util.VersionChecker.java
public static String getLatestStableDownloadURL() { String url = new String(); try {//from w w w. ja v a 2 s .c o m JSONTokener tokener = getVersionTokener(); JSONObject json = new JSONObject(tokener); url = json.getString("url"); } catch (URISyntaxException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (MalformedURLException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(VersionChecker.class.getName()).log(Level.SEVERE, null, ex); } return url; }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * Creates a CSV string corresponding to the provided JSONArray. Indexes in JSONArray expected * to correspond to rows in the CSV string. Each JSONArray element should be a JSONObject with * children being column values (with keys being column names). Make sure all JSONObjects in the * JSONArray have the same number of key-value pairs. * * @param jsonArray JSONArray with the data * @return The CSV string or NULL if the JSONArray is empty or if an error occurs *///w w w. j av a 2s .c om private String getCSVString(JSONArray jsonArray) { String csv = null; if (jsonArray.length() > 0) { try { csv = ""; List<String> keys = new ArrayList<String>(); Iterator<String> iterator = jsonArray.getJSONObject(0).keys(); while (iterator.hasNext()) { String currKey = iterator.next(); keys.add(currKey); if (csv.length() == 0) { csv = currKey; } else { csv = csv + "," + currKey; } } csv = csv + "\n"; for (int rowIndex = 0; rowIndex < jsonArray.length(); rowIndex++) { JSONObject currRow = jsonArray.getJSONObject(rowIndex); for (int keyIndex = 0; keyIndex < keys.size(); keyIndex++) { String currValue = currRow.getString(keys.get(keyIndex)); if (currValue != null) { csv = csv + currValue; } if (keyIndex < keys.size() - 1) {//not the last item in row csv = csv + ","; } } csv = csv + "\n";//will potentially lead to having an empty last line in the csv } } catch (JSONException e) { e.printStackTrace(); } } else { Log.w(TAG, "Provided jsonArray to be converted to CSV is empty returning null as csv"); } return csv; }
From source file:org.cgiar.ilri.odk.pull.backend.services.FetchFormDataService.java
/** * Dumps data provided the rows variable into the specified database. The location of the database * is in the form's media folder in ODK's SDCard's folder. * * Indexes in {@param rows} are expected to correspond to rows in {@param org.cgiar.ilri.odk.pull.backend.carriers.Form.DB_DATA_TABLE} for {@param fileName}. * Each JSONArray element should be a JSONObject with children being column values (with keys being column names). * Make sure all JSONObjects in the JSONArray have the same number of key-value pairs. * * @param fileName Then name to be given to the Database (without the .db suffix) * @param rows The {@link org.json.JSONArray} object containing the data * @return TRUE if database created successfully *///from w ww . ja v a 2 s.c om private boolean saveDataInDb(String fileName, JSONArray rows) { boolean result = false; //TODO: only do this if ODK Collect is not using this file String pathToFile = Form.BASE_ODK_LOCATION + formName + Form.EXTERNAL_ITEM_SET_SUFFIX; /*File existingDb = new File(pathToFile+File.separator+fileName+Form.SUFFIX_DB); existingDb.delete();*/ final DatabaseHelper databaseHelper = new DatabaseHelper(this, fileName, 1, pathToFile); SQLiteDatabase db = null; try { db = databaseHelper.getWritableDatabase(); } catch (SQLiteException e) {//probably because the existing .db file is corrupt e.printStackTrace(); Log.w(TAG, "Unable to open database in " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + " most likely because the database is corrupt. Trying to recreate db file"); File existingDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB); existingDbFile.delete(); File existingDbJournalFile = new File( pathToFile + File.separator + fileName + Form.SUFFIX_DB + Form.SUFFIX_JOURNAL); existingDbJournalFile.delete(); try { db = databaseHelper.getWritableDatabase(); } catch (SQLiteException e1) { Log.e(TAG, "Unable to recreate " + pathToFile + File.separator + fileName + Form.SUFFIX_DB + " file"); e1.printStackTrace(); } } if (rows.length() > 0 && db != null) { try { List<String> columns = new ArrayList<String>(); List<String> indexes = new ArrayList<String>(); Iterator<String> iterator = rows.getJSONObject(0).keys(); //recreate the tables db.execSQL("drop table if exists " + Form.DB_METADATA_TABLE); String createMetaTableString = "create table " + Form.DB_METADATA_TABLE + " (" + Form.DB_META_LOCALE_FIELD + " " + Form.DB_META_LOCALE_FIELD_TYPE + ")"; db.execSQL(createMetaTableString); databaseHelper.runInsertQuery(Form.DB_METADATA_TABLE, new String[] { Form.DB_META_LOCALE_FIELD }, new String[] { Form.DB_DEFAULT_LOCALE }, -1, db); db.execSQL("drop table if exists " + Form.DB_DATA_TABLE); String createTableString = "create table " + Form.DB_DATA_TABLE + " ("; while (iterator.hasNext()) { String currKey = iterator.next(); if (columns.size() > 0) {//this is the first column createTableString = createTableString + ", "; } createTableString = createTableString + Form.DB_DATA_COLUMN_PREFIX + currKey + " " + Form.DB_DATA_COLUMN_TYPE; columns.add(currKey); if (currKey.endsWith(Form.SUFFIX_INDEX_FIELD)) { Log.d(TAG, fileName + " has an index column " + currKey); indexes.add(currKey); } } //only continue if we have at least one column if (columns.size() > 0) { createTableString = createTableString + ", " + Form.DB_DATA_SORT_FIELD + " " + Form.DB_DATA_SORT_COLUMN_TYPE + ")"; db.execSQL(createTableString); for (int index = 0; index < indexes.size(); index++) { db.execSQL("create index " + indexes.get(index) + Form.SUFFIX_INDEX + " on " + Form.DB_DATA_TABLE + "(" + Form.DB_DATA_COLUMN_PREFIX + indexes.get(index) + ")"); } for (int rowIndex = 0; rowIndex < rows.length(); rowIndex++) { JSONObject currRow = rows.getJSONObject(rowIndex); String[] currColumns = new String[columns.size() + 1]; String[] currValues = new String[columns.size() + 1]; for (int columnIndex = 0; columnIndex < columns.size(); columnIndex++) { currColumns[columnIndex] = Form.DB_DATA_COLUMN_PREFIX + columns.get(columnIndex); currValues[columnIndex] = currRow.getString(columns.get(columnIndex)); } currColumns[columns.size()] = Form.DB_DATA_SORT_FIELD; currValues[columns.size()] = String.valueOf((double) rowIndex);//TODO: not sure if should be float or double databaseHelper.runInsertQuery(Form.DB_DATA_TABLE, currColumns, currValues, -1, db);//do not add unique key field index in argument list. Will end up being an extra query } result = true; } } catch (JSONException e) { e.printStackTrace(); } } else { Log.w(TAG, "Provided jsonArray to be dumped into a db is empty"); } db.close(); //copy db to the ADB push directory File adbFormDir = new File( Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX); if (!adbFormDir.exists() || !adbFormDir.isDirectory()) { adbFormDir.setWritable(true); adbFormDir.setReadable(true); Log.i(TAG, "Trying to create dir " + adbFormDir.getPath()); } File sourceDbFile = new File(pathToFile + File.separator + fileName + Form.SUFFIX_DB); File destDbFile = new File(Form.BASE_ODK_LOCATION + formName.replaceAll("[^A-Za-z0-9]", "_") + Form.EXTERNAL_ITEM_SET_SUFFIX + File.separator + fileName + Form.SUFFIX_DB); InputStream in = null; OutputStream out = null; try { in = new FileInputStream(sourceDbFile); out = new FileOutputStream(destDbFile); // Copy the bits from instream to outstream byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; }
From source file:org.cfr.restlet.ext.shindig.resource.MakeRequestResourceTest.java
private void assertResponseOk(int expectedStatus, String expectedBody) throws JSONException { ContextResource contextResource = resource.getContextResource(); if (Status.SUCCESS_OK.equals(contextResource.getStatus())) { String body = contextResource.getText(); assertStartsWith(MakeRequestHandler.UNPARSEABLE_CRUFT, body); body = body.substring(MakeRequestHandler.UNPARSEABLE_CRUFT.length()); JSONObject object = new JSONObject(body); object = object.getJSONObject(REQUEST_URL.toString()); assertEquals(expectedStatus, object.getInt("rc")); assertEquals(expectedBody, object.getString("body")); } else {/* w w w.ja v a 2 s .c o m*/ fail("Invalid response for request."); } }
From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java
private void createFilteredDeck(JSONArray delays, Object[] terms, Boolean resched) { JSONObject dyn; if (AnkiDroidApp.colIsOpen()) { Collection col = AnkiDroidApp.getCol(); try {//from www . j av a 2s .c o m String deckName = col.getDecks().current().getString("name"); String customStudyDeck = getResources().getString(R.string.custom_study_deck_name); JSONObject cur = col.getDecks().byName(customStudyDeck); if (cur != null) { if (cur.getInt("dyn") != 1) { StyledDialog.Builder builder = new StyledDialog.Builder(getActivity()); builder.setMessage(R.string.custom_study_deck_exists); builder.setNegativeButton(getResources().getString(R.string.cancel), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { // } }); builder.create().show(); return; } else { // safe to empty col.getSched().emptyDyn(cur.getLong("id")); // reuse; don't delete as it may have children dyn = cur; col.getDecks().select(cur.getLong("id")); } } else { long did = col.getDecks().newDyn(customStudyDeck); dyn = col.getDecks().get(did); } // and then set various options dyn.put("delays", delays); JSONArray ar = dyn.getJSONArray("terms"); ar.getJSONArray(0).put(0, new StringBuilder("deck:\"").append(deckName).append("\" ").append(terms[0]).toString()); ar.getJSONArray(0).put(1, terms[1]); ar.getJSONArray(0).put(2, terms[2]); dyn.put("resched", resched); if (mFragmented) { Bundle config = new Bundle(); config.putString("searchSuffix", "'deck:" + dyn.getString("name") + "'"); initAllContentViews(getLayoutInflater(config)); finishCongrats(); } else { // Load a new fragment with the filtered deck view. The config passed is null, so it uses the // current deck. The deck we just created is internally set as the current deck. ((StudyOptionsActivity) getActivity()).loadContent(false, null); } // Initial rebuild mProgressDialog = StyledProgressDialog.show(getActivity(), "", getResources().getString(R.string.rebuild_custom_study_deck), true); DeckTask.launchDeckTask(DeckTask.TASK_TYPE_REBUILD_CRAM, mRebuildCustomStudyListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), AnkiDroidApp.getCol().getDecks().selected(), mFragmented)); } catch (JSONException e) { throw new RuntimeException(e); } } }
From source file:com.hichinaschool.flashcards.anki.StudyOptionsFragment.java
private void updateValuesFromDeck(boolean reset) { String fullName;/*from w w w.ja va2s . c om*/ if (!AnkiDroidApp.colIsOpen()) { return; } JSONObject deck = AnkiDroidApp.getCol().getDecks().current(); try { fullName = deck.getString("name"); String[] name = fullName.split("::"); StringBuilder nameBuilder = new StringBuilder(); if (name.length > 0) { nameBuilder.append(name[0]); } if (name.length > 1) { nameBuilder.append("\n").append(name[1]); } if (name.length > 3) { nameBuilder.append("..."); } if (name.length > 2) { nameBuilder.append("\n").append(name[name.length - 1]); } mTextDeckName.setText(nameBuilder.toString()); // open cram deck option if deck is opened for the first time if (mCramInitialConfig != null) { openCramDeckOptions(mCramInitialConfig); return; } } catch (JSONException e) { throw new RuntimeException(e); } if (!mFragmented) { getActivity().setTitle(fullName); } String desc; try { if (deck.getInt("dyn") == 0) { desc = AnkiDroidApp.getCol().getDecks().getActualDescription(); mTextDeckDescription.setMaxLines(3); } else { desc = getResources().getString(R.string.dyn_deck_desc); mTextDeckDescription.setMaxLines(5); } } catch (JSONException e) { throw new RuntimeException(e); } if (desc.length() > 0) { mTextDeckDescription.setText(Html.fromHtml(desc)); mTextDeckDescription.setVisibility(View.VISIBLE); } else { mTextDeckDescription.setVisibility(View.GONE); } DeckTask.launchDeckTask(DeckTask.TASK_TYPE_UPDATE_VALUES_FROM_DECK, mUpdateValuesFromDeckListener, new DeckTask.TaskData(AnkiDroidApp.getCol(), new Object[] { reset, mSmallChart != null })); }
From source file:org.runnerup.export.format.RunKeeper.java
public static ActivityEntity parseToActivity(JSONObject response, double unitMeters) throws JSONException { ActivityEntity newActivity = new ActivityEntity(); newActivity.setSport(RunKeeperSynchronizer.runkeeper2sportMap.get(response.getString("type")).getDbValue()); if (response.has("notes")) { newActivity.setComment(response.getString("notes")); }/* w w w . ja v a2s . co m*/ newActivity.setTime((long) Float.parseFloat(response.getString("duration"))); newActivity.setDistance(Float.parseFloat(response.getString("total_distance"))); String startTime = response.getString("start_time"); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss", Locale.US); try { newActivity.setStartTime(format.parse(startTime)); } catch (ParseException e) { Log.e(Constants.LOG, e.getMessage()); return null; } List<LapEntity> laps = new ArrayList<LapEntity>(); List<LocationEntity> locations = new ArrayList<LocationEntity>(); JSONArray distance = response.getJSONArray("distance"); JSONArray path = response.getJSONArray("path"); JSONArray hr = response.getJSONArray("heart_rate"); SortedMap<Long, HashMap<String, String>> pointsValueMap = createPointsMap(distance, path, hr); Iterator<Map.Entry<Long, HashMap<String, String>>> points = pointsValueMap.entrySet().iterator(); //lap hr int maxHr = 0; int sumHr = 0; int count = 0; //point speed long time = 0; float meters = 0.0f; //activity hr int maxHrOverall = 0; int sumHrOverall = 0; int countOverall = 0; while (points.hasNext()) { Map.Entry<Long, HashMap<String, String>> timePoint = points.next(); HashMap<String, String> values = timePoint.getValue(); LocationEntity lv = new LocationEntity(); lv.setActivityId(newActivity.getId()); lv.setTime(TimeUnit.SECONDS.toMillis(newActivity.getStartTime()) + timePoint.getKey()); String dist = values.get("distance"); if (dist == null) { continue; } String lat = values.get("latitude"); String lon = values.get("longitude"); String alt = values.get("altitude"); String heart = values.get("heart_rate"); String type = values.get("type"); if (lat == null || lon == null) { continue; } else { lv.setLatitude(Double.valueOf(lat)); lv.setLongitude(Double.valueOf(lon)); } if (alt != null) { lv.setAltitude(Double.valueOf(alt)); } if (pointsValueMap.firstKey().equals(timePoint.getKey())) { lv.setType(DB.LOCATION.TYPE_START); } else if (!points.hasNext()) { lv.setType(DB.LOCATION.TYPE_END); } else if (type != null) { lv.setType(RunKeeperSynchronizer.POINT_TYPE.get(type)); } // lap and activity max and avg hr if (heart != null) { lv.setHr(Integer.valueOf(heart)); maxHr = Math.max(maxHr, lv.getHr()); maxHrOverall = Math.max(maxHrOverall, lv.getHr()); sumHr += lv.getHr(); sumHrOverall += lv.getHr(); count++; countOverall++; } meters = Float.valueOf(dist) - meters; time = timePoint.getKey() - time; if (time > 0) { float speed = meters / (float) TimeUnit.MILLISECONDS.toSeconds(time); BigDecimal s = new BigDecimal(speed); s = s.setScale(2, BigDecimal.ROUND_UP); lv.setSpeed(s.floatValue()); } // create lap if distance greater than configured lap distance if (Float.valueOf(dist) >= unitMeters * laps.size()) { LapEntity newLap = new LapEntity(); newLap.setLap(laps.size()); newLap.setDistance(Float.valueOf(dist)); newLap.setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey())); newLap.setActivityId(newActivity.getId()); laps.add(newLap); // update previous lap with duration and distance if (laps.size() > 1) { LapEntity previousLap = laps.get(laps.size() - 2); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap.setTime( (int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } maxHr = 0; sumHr = 0; count = 0; } } // update last lap with duration and distance if (!points.hasNext()) { LapEntity previousLap = laps.get(laps.size() - 1); previousLap.setDistance(Float.valueOf(dist) - previousLap.getDistance()); previousLap .setTime((int) TimeUnit.MILLISECONDS.toSeconds(timePoint.getKey()) - previousLap.getTime()); if (hr != null && hr.length() > 0) { previousLap.setMaxHr(maxHr); previousLap.setAvgHr(sumHr / count); } } lv.setLap(laps.size() - 1); locations.add(lv); } // calculate avg and max hr // update the activity newActivity.setMaxHr(maxHrOverall); if (countOverall > 0) { newActivity.setAvgHr(sumHrOverall / countOverall); } newActivity.putPoints(locations); newActivity.putLaps(laps); return newActivity; }
From source file:org.runnerup.export.format.RunKeeper.java
private static SortedMap<Long, HashMap<String, String>> createPointsMap(JSONArray distance, JSONArray path, JSONArray hr) throws JSONException { SortedMap<Long, HashMap<String, String>> result = new TreeMap<Long, HashMap<String, String>>(); if (distance != null && distance.length() > 0) { for (int i = 0; i < distance.length(); i++) { JSONObject o = distance.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = new HashMap<String, String>(); String valueMapKey = "distance"; String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); result.put(key, value);/*from w w w.j av a 2s .co m*/ } } if (path != null && path.length() > 0) { for (int i = 0; i < path.length(); i++) { JSONObject o = path.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = result.get(key); if (value == null) { value = new HashMap<String, String>(); } String[] attrs = new String[] { "latitude", "longitude", "altitude", "type" }; for (String valueMapKey : attrs) { String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); } result.put(key, value); } } if (hr != null && hr.length() > 0) { for (int i = 0; i < hr.length(); i++) { JSONObject o = hr.getJSONObject(i); Long key = TimeUnit.SECONDS.toMillis((long) Float.parseFloat(o.getString("timestamp"))); HashMap<String, String> value = result.get(key); if (value == null) { value = new HashMap<String, String>(); } String valueMapKey = "heart_rate"; String valueMapValue = o.getString(valueMapKey); value.put(valueMapKey, valueMapValue); result.put(key, value); } } return result; }