List of usage examples for org.json JSONArray getJSONObject
public JSONObject getJSONObject(int index) throws JSONException
From source file:org.aosutils.android.youtube.YtApiClientV3.java
public static ArrayList<YtPlaylist> getPlaylistInfo(Collection<String> playlistIds, String apiKey) throws IOException, JSONException { ArrayList<YtPlaylist> playlists = new ArrayList<>(); String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/playlists") .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet") .appendQueryParameter("id", TextUtils.join(",", playlistIds)).build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); String playlistId = item.getString("id"); String title = item.getJSONObject("snippet").getString("title"); String description = item.getJSONObject("snippet").getString("description"); YtPlaylist playlist = new YtPlaylist(playlistId, title, description); playlists.add(playlist);/*from www. j a v a 2s .c om*/ } return playlists; }
From source file:org.aosutils.android.youtube.YtApiClientV3.java
public static ArrayList<YtVideo> getVideoInfo(Collection<String> videoIds, String apiKey) throws IOException, JSONException { ArrayList<YtVideo> videos = new ArrayList<>(); String uri = new Uri.Builder().scheme("https").authority("www.googleapis.com").path("/youtube/v3/videos") .appendQueryParameter("key", apiKey).appendQueryParameter("part", "id,snippet,contentDetails") .appendQueryParameter("id", TextUtils.join(",", videoIds)).build().toString(); String output = HttpUtils.get(uri, null, _YtApiConstants.HTTP_TIMEOUT); JSONObject jsonObject = new JSONObject(output); JSONArray items = jsonObject.getJSONArray("items"); for (int i = 0; i < items.length(); i++) { JSONObject item = items.getJSONObject(i); String videoId = item.getString("id"); String title = item.getJSONObject("snippet").getString("title"); String description = item.getJSONObject("snippet").getString("description"); String durationStr = item.getJSONObject("contentDetails").getString("duration"); int hours = !durationStr.contains("H") ? 0 : Integer.parseInt( durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("H"))); int minutes = !durationStr.contains("M") ? 0 : hours > 0//w w w . j a v a2 s. c om ? Integer.parseInt( durationStr.substring(durationStr.indexOf("H") + 1, durationStr.indexOf("M"))) : Integer.parseInt( durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("M"))); int seconds = !durationStr.contains("S") ? 0 : minutes > 0 ? Integer.parseInt( durationStr.substring(durationStr.indexOf("M") + 1, durationStr.indexOf("S"))) : hours > 0 ? Integer.parseInt(durationStr.substring(durationStr.indexOf("H") + 1, durationStr.indexOf("S"))) : Integer.parseInt(durationStr.substring(durationStr.indexOf("PT") + 2, durationStr.indexOf("S"))); int duration = (hours * 60 * 60) + (minutes * 60) + seconds; boolean licensedContent = item.getJSONObject("contentDetails").getBoolean("licensedContent"); YtVideo video = new YtVideo(videoId, title, description, duration); video.setIsLicensedContent(licensedContent); videos.add(video); } return videos; }
From source file:com.gmail.boiledorange73.ut.map.MapActivityBase.java
/** * Called when JS sends the message.// w w w . j a v a 2 s . c om * * @param bridge * Receiver instance. * @param code * The code name. This looks like the name of function. * @param message * The message. This looks like the argument of function. This is * usually expressed as JSON. */ @Override public void onArriveMessage(JSBridge bridge, String code, String message) { if (code == null) { } else if (code.equals("onLoad")) { this.mMaptypeList = new ArrayList<ValueText<String>>(); this.mLoaded = true; // executes queued commands. this.execute(null); JSONArray json = null; try { json = new JSONArray(message); } catch (JSONException e) { e.printStackTrace(); } if (json != null) { for (int n = 0; n < json.length(); n++) { JSONObject one = null; try { one = json.getJSONObject(n); } catch (JSONException e) { e.printStackTrace(); } if (one != null) { String id = null, name = null; try { id = one.getString("id"); name = one.getString("name"); } catch (JSONException e) { e.printStackTrace(); } if (id != null && name != null) { this.mMaptypeList.add(new ValueText<String>(id, name)); } } } } // restores map state (2013/08/07) if (this.mInternalMapState != null) { this.restoreMapState(this.mInternalMapState.id, this.mInternalMapState.lon, this.mInternalMapState.lat, this.mInternalMapState.z); this.mInternalMapState = null; } // request to create menu items. this.invalidateOptionsMenuIfPossible(); } else if (code.equals("getCurrentMapState")) { if (message == null || !(message.length() > 0)) { // DOES NOTHING } else { try { JSONObject json = new JSONObject(message); this.mInternalMapState = new MapState(); this.mInternalMapState.id = json.getString("id"); this.mInternalMapState.lat = json.getDouble("lat"); this.mInternalMapState.lon = json.getDouble("lon"); this.mInternalMapState.z = json.getInt("z"); } catch (JSONException e) { e.printStackTrace(); } } this.mWaitingForgetCurrentMapState = false; } else if (code.equals("getCurrentZoomState")) { if (message == null) { // DOES NOTHING } else { try { JSONObject json = new JSONObject(message); this.mZoomState = new ZoomState(); this.mZoomState.minzoom = json.getInt("minzoom"); this.mZoomState.maxzoom = json.getInt("maxzoom"); this.mZoomState.currentzoom = json.getInt("currentzoom"); } catch (JSONException e) { e.printStackTrace(); } this.mWaitingForgetCurrentZoomState = false; } } else if (code.equals("alert")) { // shows alert text. (new AlertDialog.Builder(this)).setTitle(this.getTitle()).setMessage(message != null ? message : "") .setCancelable(true).setPositiveButton(android.R.string.ok, null).show(); } }
From source file:org.pixmob.droidlink.sync.SyncAdapter.java
private void doPerformSync(NetworkClient client, SharedPreferences prefs, ContentProviderClient provider, SyncResult syncResult, boolean fullSync) { // Prepare the query. final String selection = DEVICE_ID + "=? AND " + STATE + "=? OR " + STATE + "=?"; final String[] selectionArgs = { client.getDeviceId(), String.valueOf(EventsContract.PENDING_UPLOAD_STATE), String.valueOf(EventsContract.PENDING_DELETE_STATE) }; // Get local data to sync. final Map<String, JSONObject> eventsToUpload = new HashMap<String, JSONObject>(8); final Set<String> eventsToDelete = new HashSet<String>(4); Cursor c = null;//from w w w .ja va2 s . co m try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION, selection, selectionArgs, null); final int idIdx = c.getColumnIndexOrThrow(_ID); final int typeIdx = c.getColumnIndexOrThrow(TYPE); final int createdIdx = c.getColumnIndexOrThrow(CREATED); final int numberIdx = c.getColumnIndexOrThrow(NUMBER); final int nameIdx = c.getColumnIndexOrThrow(NAME); final int messageIdx = c.getColumnIndexOrThrow(MESSAGE); final int stateIdx = c.getColumnIndexOrThrow(STATE); while (c.moveToNext()) { final String eventId = c.getString(idIdx); final int eventState = c.getInt(stateIdx); if (EventsContract.PENDING_UPLOAD_STATE == eventState) { // This is a newly created event. final JSONObject event = new JSONObject(); try { event.put("deviceId", client.getDeviceId()); event.put("created", c.getLong(createdIdx)); event.put("type", c.getInt(typeIdx)); event.put("number", c.getString(numberIdx)); event.put("name", c.getString(nameIdx)); event.put("message", c.getString(messageIdx)); } catch (JSONException e) { Log.w(TAG, "Invalid event " + eventId + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } eventsToUpload.put(eventId, event); } else if (EventsContract.PENDING_DELETE_STATE == eventState) { // The user wants this event to be deleted. eventsToDelete.add(eventId); } } } catch (RemoteException e) { Log.e(TAG, "Failed to get events: cannot sync", e); syncResult.stats.numIoExceptions++; } finally { if (c != null) { c.close(); c = null; } } final ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>(32); final ContentValues values = new ContentValues(8); if (eventsToDelete.isEmpty()) { Log.i(TAG, "No events to delete"); } else { Log.i(TAG, "Found " + eventsToDelete.size() + " event(s) to delete"); } // Delete events on the remote server. for (final String eventId : eventsToDelete) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event: " + eventId); } try { client.delete("/events/" + eventId); if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } catch (IOException e) { Log.e(TAG, "Event deletion error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (fullSync) { // Get all events from the remote server. final JSONArray events; if (DEVELOPER_MODE) { Log.d(TAG, "Fetching events from the remote server"); } try { events = client.getAsArray("/events"); } catch (IOException e) { Log.e(TAG, "Event listing error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } final int eventsLen = events != null ? events.length() : 0; if (eventsLen == 0) { Log.i(TAG, "No events from the remote server"); } else { Log.i(TAG, "Found " + eventsLen + " event(s) from the remote server"); } // Build a collection with local event identifiers. // This collection will be used to identify which events have // been deleted on the remote server. final Set<String> localEventIds; try { c = provider.query(EventsContract.CONTENT_URI, PROJECTION_ID, STATE + "=?", new String[] { String.valueOf(EventsContract.UPLOADED_STATE) }, null); localEventIds = new HashSet<String>(c.getCount()); final int idIdx = c.getColumnIndexOrThrow(_ID); while (c.moveToNext()) { final String eventId = c.getString(idIdx); localEventIds.add(eventId); } } catch (RemoteException e) { Log.e(TAG, "Failed to get events from local database", e); syncResult.stats.numIoExceptions++; return; } finally { if (c != null) { c.close(); c = null; } } String newEventId = null; int newEventCount = 0; // Reconcile remote events with local events. for (int i = 0; i < eventsLen; ++i) { String eventId = null; try { final JSONObject event = events.getJSONObject(i); eventId = event.getString("id"); // Check if this event exists in the local database. if (localEventIds.contains(eventId)) { // Found the event: update it. values.clear(); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event in local database: " + eventId); } batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withExpectedCount(1).withValues(values).build()); syncResult.stats.numUpdates++; } else { // The event was not found: insert it. values.clear(); values.put(_ID, eventId); values.put(DEVICE_ID, event.getString("deviceId")); values.put(CREATED, event.getLong("created")); values.put(TYPE, event.getInt("type")); values.put(NUMBER, trimToNull(event.getString("number"))); values.put(NAME, trimToNull(event.getString("name"))); values.put(MESSAGE, trimToNull(event.getString("message"))); values.put(STATE, EventsContract.UPLOADED_STATE); if (DEVELOPER_MODE) { Log.d(TAG, "Adding event to local database: " + eventId); } batch.add(ContentProviderOperation .newInsert(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)) .withValues(values).build()); syncResult.stats.numInserts++; ++newEventCount; if (newEventId == null) { newEventId = eventId; } } // This event now exists in the local database: // remove its identifier from this collection as we // don't want to delete it. localEventIds.remove(eventId); } catch (JSONException e) { Log.w(TAG, "Invalid event at index " + i + ": cannot sync", e); syncResult.stats.numSkippedEntries++; continue; } } // The remaining event identifiers was removed on the remote // server: there are still present in the local database. These // events are now being deleted. for (final String eventId : localEventIds) { if (DEVELOPER_MODE) { Log.d(TAG, "Deleting event in local database: " + eventId); } batch.add(ContentProviderOperation .newDelete(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).build()); syncResult.stats.numDeletes++; } try { provider.applyBatch(batch); } catch (Exception e) { Log.e(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); if (newEventCount > 1) { newEventId = null; } if (newEventCount != 0) { startSyncNotificationService(newEventCount, newEventId); } } final int numEventsToUpload = eventsToUpload.size(); if (numEventsToUpload == 0) { Log.i(TAG, "No events to upload"); } else { Log.i(TAG, "Found " + numEventsToUpload + " event(s) to upload"); } // Send local events to the remote server. for (final Map.Entry<String, JSONObject> entry : eventsToUpload.entrySet()) { final String eventId = entry.getKey(); if (DEVELOPER_MODE) { Log.d(TAG, "Uploading event: " + eventId); } final JSONObject event = entry.getValue(); try { client.put("/events/" + eventId, event); if (DEVELOPER_MODE) { Log.d(TAG, "Updating event state to UPLOADED: " + eventId); } values.clear(); values.put(STATE, EventsContract.UPLOADED_STATE); batch.add(ContentProviderOperation .newUpdate(Uri.withAppendedPath(EventsContract.CONTENT_URI, eventId)).withValues(values) .withExpectedCount(1).build()); syncResult.stats.numUpdates++; Log.i(TAG, "Event upload successful: " + eventId); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { Log.e(TAG, "Device not found: cannot sync", e); registerDevice(); } else { Log.e(TAG, "Network error: cannot sync", e); } syncResult.stats.numIoExceptions++; return; } catch (IOException e) { Log.e(TAG, "Event upload error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } } try { provider.applyBatch(batch); } catch (Exception e) { Log.w(TAG, "Database error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } batch.clear(); final SharedPreferences.Editor prefsEditor = prefs.edit(); final boolean syncRequired = !eventsToDelete.isEmpty() || !eventsToUpload.isEmpty(); if (syncRequired) { // Generate an unique sync token: the server will send this token to // every devices. If this token is received on this device, the sync // will not start. final String syncToken = UUID.randomUUID().toString(); prefsEditor.putString(SP_KEY_SYNC_TOKEN, syncToken); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); // Sync user devices. try { final JSONObject data = new JSONObject(); data.put("token", syncToken); client.post("/devices/" + client.getDeviceId() + "/sync", data); } catch (NetworkClientException e) { if (e.getStatusCode() == 404) { registerDevice(); } } catch (IOException e) { Log.e(TAG, "Device sync error: cannot sync", e); syncResult.stats.numIoExceptions++; return; } catch (AppEngineAuthenticationException e) { Log.e(TAG, "Authentication error: cannot sync", e); syncResult.stats.numAuthExceptions++; return; } catch (JSONException e) { Log.w(TAG, "Invalid sync token " + syncToken + ": cannot sync", e); syncResult.stats.numIoExceptions++; return; } } // Store sync time. prefsEditor.putLong(SP_KEY_LAST_SYNC, System.currentTimeMillis()); Features.getFeature(SharedPreferencesSaverFeature.class).save(prefsEditor); }
From source file:com.asd.littleprincesbeauty.data.SqlNote.java
public boolean setContent(JSONObject js) { try {/* w w w. jav a2 s.c om*/ JSONObject note = js.getJSONObject(GTaskStringUtils.META_HEAD_NOTE); if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_SYSTEM) { Log.w(TAG, "cannot set system folder"); } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_FOLDER) { // for folder we can only update the snnipet and type String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } mType = type; } else if (note.getInt(NoteColumns.TYPE) == Notes.TYPE_NOTE) { JSONArray dataArray = js.getJSONArray(GTaskStringUtils.META_HEAD_DATA); long id = note.has(NoteColumns.ID) ? note.getLong(NoteColumns.ID) : INVALID_ID; if (mIsCreate || mId != id) { mDiffNoteValues.put(NoteColumns.ID, id); } mId = id; long alertDate = note.has(NoteColumns.ALERTED_DATE) ? note.getLong(NoteColumns.ALERTED_DATE) : 0; if (mIsCreate || mAlertDate != alertDate) { mDiffNoteValues.put(NoteColumns.ALERTED_DATE, alertDate); } mAlertDate = alertDate; int bgColorId = note.has(NoteColumns.BG_COLOR_ID) ? note.getInt(NoteColumns.BG_COLOR_ID) : ResourceParser.getDefaultBgId(mContext); if (mIsCreate || mBgColorId != bgColorId) { mDiffNoteValues.put(NoteColumns.BG_COLOR_ID, bgColorId); } mBgColorId = bgColorId; long createDate = note.has(NoteColumns.CREATED_DATE) ? note.getLong(NoteColumns.CREATED_DATE) : System.currentTimeMillis(); if (mIsCreate || mCreatedDate != createDate) { mDiffNoteValues.put(NoteColumns.CREATED_DATE, createDate); } mCreatedDate = createDate; int hasAttachment = note.has(NoteColumns.HAS_ATTACHMENT) ? note.getInt(NoteColumns.HAS_ATTACHMENT) : 0; if (mIsCreate || mHasAttachment != hasAttachment) { mDiffNoteValues.put(NoteColumns.HAS_ATTACHMENT, hasAttachment); } mHasAttachment = hasAttachment; long modifiedDate = note.has(NoteColumns.MODIFIED_DATE) ? note.getLong(NoteColumns.MODIFIED_DATE) : System.currentTimeMillis(); if (mIsCreate || mModifiedDate != modifiedDate) { mDiffNoteValues.put(NoteColumns.MODIFIED_DATE, modifiedDate); } mModifiedDate = modifiedDate; long parentId = note.has(NoteColumns.PARENT_ID) ? note.getLong(NoteColumns.PARENT_ID) : 0; if (mIsCreate || mParentId != parentId) { mDiffNoteValues.put(NoteColumns.PARENT_ID, parentId); } mParentId = parentId; String snippet = note.has(NoteColumns.SNIPPET) ? note.getString(NoteColumns.SNIPPET) : ""; if (mIsCreate || !mSnippet.equals(snippet)) { mDiffNoteValues.put(NoteColumns.SNIPPET, snippet); } mSnippet = snippet; int type = note.has(NoteColumns.TYPE) ? note.getInt(NoteColumns.TYPE) : Notes.TYPE_NOTE; if (mIsCreate || mType != type) { mDiffNoteValues.put(NoteColumns.TYPE, type); } mType = type; int widgetId = note.has(NoteColumns.WIDGET_ID) ? note.getInt(NoteColumns.WIDGET_ID) : AppWidgetManager.INVALID_APPWIDGET_ID; if (mIsCreate || mWidgetId != widgetId) { mDiffNoteValues.put(NoteColumns.WIDGET_ID, widgetId); } mWidgetId = widgetId; int widgetType = note.has(NoteColumns.WIDGET_TYPE) ? note.getInt(NoteColumns.WIDGET_TYPE) : Notes.TYPE_WIDGET_INVALIDE; if (mIsCreate || mWidgetType != widgetType) { mDiffNoteValues.put(NoteColumns.WIDGET_TYPE, widgetType); } mWidgetType = widgetType; long originParent = note.has(NoteColumns.ORIGIN_PARENT_ID) ? note.getLong(NoteColumns.ORIGIN_PARENT_ID) : 0; if (mIsCreate || mOriginParent != originParent) { mDiffNoteValues.put(NoteColumns.ORIGIN_PARENT_ID, originParent); } mOriginParent = originParent; for (int i = 0; i < dataArray.length(); i++) { JSONObject data = dataArray.getJSONObject(i); SqlData sqlData = null; if (data.has(DataColumns.ID)) { long dataId = data.getLong(DataColumns.ID); for (SqlData temp : mDataList) { if (dataId == temp.getId()) { sqlData = temp; } } } if (sqlData == null) { sqlData = new SqlData(mContext); mDataList.add(sqlData); } sqlData.setContent(data); } } } catch (JSONException e) { Log.e(TAG, e.toString()); e.printStackTrace(); return false; } return true; }
From source file:drusy.ui.panels.SwitchStatePanel.java
public void update(final Updater updater) { final ByteArrayOutputStream output = new ByteArrayOutputStream(); HttpUtils.DownloadGetTask task = HttpUtils.downloadGetAsync(Config.FREEBOX_API_SWITCH_STATUS, output, "Getting Switch status", false); task.addListener(new HttpUtils.DownloadListener() { @Override/* w ww .j a v a 2 s .com*/ public void onComplete() { String json = output.toString(); JSONObject obj = new JSONObject(json); boolean success = obj.getBoolean("success"); clearUsers(); if (success == true) { JSONArray switchStatusArray = obj.getJSONArray("result"); for (int i = 0; i < switchStatusArray.length(); ++i) { JSONObject switchStatus = switchStatusArray.getJSONObject(i); String status = switchStatus.getString("link"); int id = switchStatus.getInt("id"); if (status.equals("up")) { JSONArray switchMacArray = switchStatus.getJSONArray("mac_list"); JSONObject switchMac = switchMacArray.getJSONObject(i); String hostname = switchMac.getString("hostname"); addUsersForSwitchIdAndHostname(id, hostname); } } } else { String msg = obj.getString("msg"); Log.Debug("Freebox Switch status", msg); } if (updater != null) { updater.updated(); } } }); task.addListener(new HttpUtils.DownloadListener() { @Override public void onError(IOException ex) { Log.Debug("Freebox Switch status", ex.getMessage()); if (updater != null) { updater.updated(); } } }); }
From source file:org.liberty.android.fantastischmemopro.downloader.DownloaderSS.java
private List<DownloadItem> retrieveCategories() throws Exception { List<DownloadItem> diList = new LinkedList<DownloadItem>(); JSONArray jsonArray = new JSONArray(downloadJSONString(SS_API_GET_CATEGORIES)); for (int i = 0; i < jsonArray.length(); i++) { JSONObject jsonItem = jsonArray.getJSONObject(i); DownloadItem di = new DownloadItem(); di.setType(DownloadItem.TYPE_CATEGORY); di.setTitle(jsonItem.getString("name")); di.setExtras("id", jsonItem.getString("id")); di.setExtras("pid", jsonItem.getString("parentId")); di.setExtras("page", "1"); if (di.getTitle() != null) { diList.add(di);/*w w w .ja va 2 s . c o m*/ } } return diList; }
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 w w .j a v a 2 s. c o m*/ 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: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 *//*from w ww . j a v a 2 s.com*/ 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 *//*ww w . j a v a 2s . 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; }