List of usage examples for android.database Cursor isAfterLast
boolean isAfterLast();
From source file:org.jnegre.android.osmonthego.service.ExportService.java
/** * Handle export in the provided background thread *//*from w ww . ja v a 2 s. com*/ private void handleOsmExport(boolean includeAddress, boolean includeFixme) { //TODO handle empty survey //TODO handle bounds around +/-180 if (!isExternalStorageWritable()) { notifyUserOfError(); return; } int id = 0; double minLat = 200; double minLng = 200; double maxLat = -200; double maxLng = -200; StringBuilder builder = new StringBuilder(); if (includeAddress) { Uri uri = AddressTableMetaData.CONTENT_URI; Cursor cursor = getContentResolver().query(uri, new String[] { //projection AddressTableMetaData.LATITUDE, AddressTableMetaData.LONGITUDE, AddressTableMetaData.NUMBER, AddressTableMetaData.STREET }, null, //selection string null, //selection args array of strings null); //sort order if (cursor == null) { notifyUserOfError(); return; } try { int iLat = cursor.getColumnIndex(AddressTableMetaData.LATITUDE); int iLong = cursor.getColumnIndex(AddressTableMetaData.LONGITUDE); int iNumber = cursor.getColumnIndex(AddressTableMetaData.NUMBER); int iStreet = cursor.getColumnIndex(AddressTableMetaData.STREET); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { //Gather values double lat = cursor.getDouble(iLat); double lng = cursor.getDouble(iLong); String number = cursor.getString(iNumber); String street = cursor.getString(iStreet); minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLng = Math.min(minLng, lng); maxLng = Math.max(maxLng, lng); builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"") .append(lng).append("\" version=\"1\" action=\"modify\">\n"); addOsmTag(builder, "addr:housenumber", number); addOsmTag(builder, "addr:street", street); builder.append("</node>\n"); } } finally { cursor.close(); } } if (includeFixme) { Uri uri = FixmeTableMetaData.CONTENT_URI; Cursor cursor = getContentResolver().query(uri, new String[] { //projection FixmeTableMetaData.LATITUDE, FixmeTableMetaData.LONGITUDE, FixmeTableMetaData.COMMENT }, null, //selection string null, //selection args array of strings null); //sort order if (cursor == null) { notifyUserOfError(); return; } try { int iLat = cursor.getColumnIndex(FixmeTableMetaData.LATITUDE); int iLong = cursor.getColumnIndex(FixmeTableMetaData.LONGITUDE); int iComment = cursor.getColumnIndex(FixmeTableMetaData.COMMENT); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { //Gather values double lat = cursor.getDouble(iLat); double lng = cursor.getDouble(iLong); String comment = cursor.getString(iComment); minLat = Math.min(minLat, lat); maxLat = Math.max(maxLat, lat); minLng = Math.min(minLng, lng); maxLng = Math.max(maxLng, lng); builder.append("<node id=\"-").append(++id).append("\" lat=\"").append(lat).append("\" lon=\"") .append(lng).append("\" version=\"1\" action=\"modify\">\n"); addOsmTag(builder, "fixme", comment); builder.append("</node>\n"); } } finally { cursor.close(); } } try { File destinationFile = getDestinationFile(); destinationFile.getParentFile().mkdirs(); PrintWriter writer = new PrintWriter(destinationFile, "UTF-8"); writer.println("<?xml version='1.0' encoding='UTF-8' standalone='yes' ?>"); writer.println("<osm version=\"0.6\" generator=\"OsmOnTheGo\">"); writer.print("<bounds minlat=\""); writer.print(minLat - MARGIN); writer.print("\" minlon=\""); writer.print(minLng - MARGIN); writer.print("\" maxlat=\""); writer.print(maxLat + MARGIN); writer.print("\" maxlon=\""); writer.print(maxLng + MARGIN); writer.println("\" />"); writer.println(builder); writer.print("</osm>"); writer.close(); if (writer.checkError()) { notifyUserOfError(); } else { //FIXME i18n the subject and content Intent emailIntent = new Intent(Intent.ACTION_SEND); emailIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); emailIntent.setType(HTTP.OCTET_STREAM_TYPE); //emailIntent.putExtra(Intent.EXTRA_EMAIL, new String[]{"johndoe@exemple.com"}); emailIntent.putExtra(Intent.EXTRA_SUBJECT, "OSM On The Go"); emailIntent.putExtra(Intent.EXTRA_TEXT, "Your last survey."); emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(destinationFile)); startActivity(emailIntent); } } catch (IOException e) { Log.e(TAG, "Could not write to file", e); notifyUserOfError(); } }
From source file:org.tcai.tasks.HistoryBookmarksExportTask.java
private String writeAsJSON(Cursor... params) { try {/*from w w w . j av a 2 s . c om*/ String fileName = mContext.getString(R.string.ApplicationName) + "-" + getNowForFileName() + ".json"; File file = new File(Environment.getExternalStorageDirectory(), fileName); FileWriter writer = new FileWriter(file); FoldersJSONArray foldersArray = new FoldersJSONArray(); BookmarksJSONArray bookmarksArray = new BookmarksJSONArray(); HistoryJSONArray historyArray = new HistoryJSONArray(); Cursor c = params[0]; if (c.moveToFirst()) { int current = 0; int total = c.getCount(); int idIndex = c.getColumnIndex(BookmarksProvider.Columns._ID); int titleIndex = c.getColumnIndex(BookmarksProvider.Columns.TITLE); int urlIndex = c.getColumnIndex(BookmarksProvider.Columns.URL); int creationDateIndex = c.getColumnIndex(BookmarksProvider.Columns.CREATION_DATE); int visitedDateIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITED_DATE); int visitsIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITS); int bookmarkIndex = c.getColumnIndex(BookmarksProvider.Columns.BOOKMARK); int folderIndex = c.getColumnIndex(BookmarksProvider.Columns.IS_FOLDER); int parentfolderIdIndex = c.getColumnIndex(BookmarksProvider.Columns.PARENT_FOLDER_ID); while (!c.isAfterLast()) { publishProgress(1, current, total); boolean isFolder = c.getInt(folderIndex) > 0 ? true : false; if (isFolder) { String title = c.getString(titleIndex); title = title != null ? URLEncoder.encode(title) : ""; foldersArray.add(title, c.getLong(idIndex), c.getLong(parentfolderIdIndex)); } else { boolean isBookmark = c.getInt(bookmarkIndex) > 0 ? true : false; String title = c.getString(titleIndex); title = title != null ? URLEncoder.encode(title) : ""; String url = c.getString(urlIndex); url = url != null ? URLEncoder.encode(url) : ""; if (isBookmark) { bookmarksArray.add(c.getLong(parentfolderIdIndex), title, url, c.getLong(creationDateIndex), c.getLong(visitedDateIndex), c.getInt(visitsIndex)); } else { historyArray.add(title, url, c.getLong(visitedDateIndex), c.getInt(visitsIndex)); } } current++; c.moveToNext(); } } JSONObject output = new JSONObject(); output.put("folders", foldersArray); output.put("bookmarks", bookmarksArray); output.put("history", historyArray); writer.write(output.toString(1)); writer.flush(); writer.close(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return null; }
From source file:com.acrutiapps.browser.tasks.HistoryBookmarksExportTask.java
private String writeAsJSON(Cursor... params) { try {// ww w . ja v a 2s.com String fileName = mContext.getString(R.string.ApplicationName) + "-" + getNowForFileName() + ".json"; File file = new File(Environment.getExternalStorageDirectory(), fileName); FileWriter writer = new FileWriter(file); FoldersJSONArray foldersArray = new FoldersJSONArray(); BookmarksJSONArray bookmarksArray = new BookmarksJSONArray(); HistoryJSONArray historyArray = new HistoryJSONArray(); Cursor c = params[0]; if (c.moveToFirst()) { int current = 0; int total = c.getCount(); int idIndex = c.getColumnIndex(BookmarksProvider.Columns._ID); int titleIndex = c.getColumnIndex(BookmarksProvider.Columns.TITLE); int urlIndex = c.getColumnIndex(BookmarksProvider.Columns.URL); int creationDateIndex = c.getColumnIndex(BookmarksProvider.Columns.CREATION_DATE); int visitedDateIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITED_DATE); int visitsIndex = c.getColumnIndex(BookmarksProvider.Columns.VISITS); int bookmarkIndex = c.getColumnIndex(BookmarksProvider.Columns.BOOKMARK); int folderIndex = c.getColumnIndex(BookmarksProvider.Columns.IS_FOLDER); int parentfolderIdIndex = c.getColumnIndex(BookmarksProvider.Columns.PARENT_FOLDER_ID); while (!c.isAfterLast()) { publishProgress(1, current, total); boolean isFolder = c.getInt(folderIndex) > 0 ? true : false; if (isFolder) { String title = c.getString(titleIndex); title = title != null ? URLEncoder.encode(title, "UTF-8") : ""; foldersArray.add(title, c.getLong(idIndex), c.getLong(parentfolderIdIndex)); } else { boolean isBookmark = c.getInt(bookmarkIndex) > 0 ? true : false; String title = c.getString(titleIndex); title = title != null ? URLEncoder.encode(title, "UTF-8") : ""; String url = c.getString(urlIndex); url = url != null ? URLEncoder.encode(url, "UTF-8") : ""; if (isBookmark) { bookmarksArray.add(c.getLong(parentfolderIdIndex), title, url, c.getLong(creationDateIndex), c.getLong(visitedDateIndex), c.getInt(visitsIndex)); } else { historyArray.add(title, url, c.getLong(visitedDateIndex), c.getInt(visitsIndex)); } } current++; c.moveToNext(); } } JSONObject output = new JSONObject(); output.put("folders", foldersArray); output.put("bookmarks", bookmarksArray); output.put("history", historyArray); writer.write(output.toString(1)); writer.flush(); writer.close(); } catch (JSONException e) { e.printStackTrace(); return e.getMessage(); } catch (IOException e) { e.printStackTrace(); return e.getMessage(); } return null; }
From source file:com.lance.commu.fragment.BaseActivity.java
private void getContactData() { Cursor phoneCursor = null; contactList = new HashMap<String, String>(); try {//from w w w . j a v a 2s.co m // URI Uri uContactsUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI; // String strProjection = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME; // phoneCursor = getContentResolver().query(uContactsUri, null, null, null, strProjection); phoneCursor.moveToFirst(); String name = ""; String phoneNumber = ""; // int nameColumn = phoneCursor.getColumnIndex(Phone.DISPLAY_NAME); // int phoneColumn = phoneCursor.getColumnIndex(Phone.NUMBER); while (!phoneCursor.isAfterLast()) { name = phoneCursor.getString(nameColumn); phoneNumber = phoneCursor.getString(phoneColumn); // HashMap data contactList.put(phoneNumber, name); phoneCursor.moveToNext(); } } catch (Exception e) { e.printStackTrace(); } finally { if (phoneCursor != null) { phoneCursor.close(); phoneCursor = null; for (Map.Entry<String, String> s : contactList.entrySet()) { String phone_number = s.getKey(); phone_number = phone_number.replaceAll("-", ""); String name = s.getValue(); // phone_Book_List[index++] = phone_number; phone_Book_List[index++] = name; } } } }
From source file:org.tomahawk.libtomahawk.database.DatabaseHelper.java
/** * @param playlistId the id by which to get the correct {@link org.tomahawk.libtomahawk.collection.Playlist} * @return the stored {@link org.tomahawk.libtomahawk.collection.Playlist} with playlistId as * its id//from w w w. j a va 2 s.c o m */ public Playlist getPlaylist(String playlistId, boolean reverseEntries) { String[] columns = new String[] { TomahawkSQLiteHelper.PLAYLISTS_COLUMN_NAME, TomahawkSQLiteHelper.PLAYLISTS_COLUMN_CURRENTREVISION, TomahawkSQLiteHelper.PLAYLISTS_COLUMN_HATCHETID }; Cursor playlistsCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_PLAYLISTS, columns, TomahawkSQLiteHelper.PLAYLISTS_COLUMN_ID + " = ?", new String[] { playlistId }, null, null, null); if (playlistsCursor.moveToFirst()) { columns = new String[] { TomahawkSQLiteHelper.TRACKS_COLUMN_TRACKNAME, TomahawkSQLiteHelper.TRACKS_COLUMN_ARTISTNAME, TomahawkSQLiteHelper.TRACKS_COLUMN_ALBUMNAME, TomahawkSQLiteHelper.TRACKS_COLUMN_RESULTHINT, TomahawkSQLiteHelper.TRACKS_COLUMN_ISFETCHEDVIAHATCHET, TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTENTRYID }; Cursor tracksCursor = mDatabase.query(TomahawkSQLiteHelper.TABLE_TRACKS, columns, TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTID + " = ?", new String[] { playlistId }, null, null, TomahawkSQLiteHelper.TRACKS_COLUMN_PLAYLISTENTRYINDEX + (reverseEntries ? " DESC" : " ASC")); ArrayList<PlaylistEntry> queries = new ArrayList<PlaylistEntry>(); tracksCursor.moveToFirst(); while (!tracksCursor.isAfterLast()) { String trackName = tracksCursor.getString(0); String artistName = tracksCursor.getString(1); String albumName = tracksCursor.getString(2); String resultHint = tracksCursor.getString(3); Query query = Query.get(trackName, albumName, artistName, resultHint, false, tracksCursor.getInt(4) == TRUE); String entryId; if (tracksCursor.getString(5) != null) { entryId = tracksCursor.getString(5); } else { entryId = TomahawkMainActivity.getLifetimeUniqueStringId(); } PlaylistEntry entry = PlaylistEntry.get(playlistId, query, entryId); queries.add(entry); tracksCursor.moveToNext(); } Playlist playlist = Playlist.fromEntriesList(playlistsCursor.getString(0), playlistsCursor.getString(1), queries); playlist.setId(playlistId); playlist.setHatchetId(playlistsCursor.getString(2)); playlist.setFilled(true); tracksCursor.close(); playlistsCursor.close(); return playlist; } playlistsCursor.close(); return null; }
From source file:com.crankworks.cycletracks.TripUploader.java
private JSONObject getCoordsJSON(long tripId) throws JSONException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mDb.openReadOnly();/*from www . j a v a2 s . c o m*/ Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId); // Build the map between JSON fieldname and phone db fieldname: Map<String, Integer> fieldMap = new HashMap<String, Integer>(); fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); // Build JSON objects for each coordinate: JSONObject tripCoords = new JSONObject(); while (!tripCoordsCursor.isAfterLast()) { JSONObject coord = new JSONObject(); coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME)))); coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT))); coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED))); coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); tripCoords.put(coord.getString("rec"), coord); tripCoordsCursor.moveToNext(); } tripCoordsCursor.close(); mDb.close(); return tripCoords; }
From source file:src.com.nustats.pacelogger.TripUploader.java
private JSONObject getCoordsJSON(long tripId) throws JSONException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss"); mDb.openReadOnly();//from ww w .j a v a 2 s . co m Cursor tripCoordsCursor = mDb.fetchAllCoordsForTrip(tripId); // Build the map between JSON fieldname and phone db fieldname: Map<String, Integer> fieldMap = new HashMap<String, Integer>(); fieldMap.put(TRIP_COORDS_TIME, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_TIME)); fieldMap.put(TRIP_COORDS_LAT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LAT)); fieldMap.put(TRIP_COORDS_LON, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_LGT)); fieldMap.put(TRIP_COORDS_ALT, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ALT)); fieldMap.put(TRIP_COORDS_SPEED, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_SPEED)); fieldMap.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); fieldMap.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getColumnIndex(DbAdapter.K_POINT_ACC)); // Build JSON objects for each coordinate: JSONObject tripCoords = new JSONObject(); while (!tripCoordsCursor.isAfterLast()) { JSONObject coord = new JSONObject(); coord.put(TRIP_COORDS_TIME, df.format(tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_TIME)))); coord.put(TRIP_COORDS_LAT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LAT)) / 1E6); coord.put(TRIP_COORDS_LON, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_LON)) / 1E6); coord.put(TRIP_COORDS_ALT, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_ALT))); coord.put(TRIP_COORDS_SPEED, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_SPEED))); coord.put(TRIP_COORDS_HACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_HACCURACY))); coord.put(TRIP_COORDS_VACCURACY, tripCoordsCursor.getDouble(fieldMap.get(TRIP_COORDS_VACCURACY))); tripCoords.put(coord.getString("rec"), coord); tripCoordsCursor.moveToNext(); } tripCoordsCursor.close(); mDb.close(); return tripCoords; }
From source file:com.facebook.stetho.inspector.protocol.module.Database.java
/** * Flatten all columns and all rows of a cursor to a single array. The array cannot be * interpreted meaningfully without the number of columns. * * @param cursor/*from w w w .j av a 2s . c om*/ * @param limit Maximum number of rows to process. * @return List of Java primitives matching the value type of each column. */ private List<Object> flattenRows(Cursor cursor, int limit) { Util.throwIfNot(limit >= 0); List<Object> flatList = new ArrayList<Object>(); final int numColumns = cursor.getColumnCount(); for (int row = 0; row < limit && cursor.moveToNext(); row++) { for (int column = 0; column < numColumns; column++) { switch (cursor.getType(column)) { case Cursor.FIELD_TYPE_NULL: flatList.add(null); break; case Cursor.FIELD_TYPE_INTEGER: flatList.add(cursor.getLong(column)); break; case Cursor.FIELD_TYPE_FLOAT: flatList.add(cursor.getDouble(column)); break; case Cursor.FIELD_TYPE_BLOB: flatList.add(cursor.getBlob(column)); break; case Cursor.FIELD_TYPE_STRING: default: flatList.add(cursor.getString(column)); break; } } } if (!cursor.isAfterLast()) { for (int column = 0; column < numColumns; column++) { flatList.add("{truncated}"); } } return flatList; }
From source file:com.dwdesign.tweetings.activity.HomeActivity.java
public void checkAndSendFailedTweets() { if (mPreferences.getBoolean(PREFERENCE_KEY_AUTOMATIC_RETRY, false)) { ContentResolver mResolver = getContentResolver(); final String[] cols = Drafts.COLUMNS; final Cursor cur = getContentResolver().query(Drafts.CONTENT_URI, cols, null, null, null); if (cur != null) { cur.moveToFirst();//from ww w . ja v a2 s . c om int i = 0; while (!cur.isAfterLast()) { final DraftItem draft = new DraftItem(cur, i); if (draft.is_queued) { final Uri image_uri = draft.media_uri == null ? null : Uri.parse(draft.media_uri); mService.updateStatus(draft.account_ids, draft.text, null, image_uri, draft.in_reply_to_status_id, draft.is_possibly_sensitive, draft.is_photo_attached && !draft.is_image_attached); mResolver.delete(Drafts.CONTENT_URI, Drafts._ID + " = " + draft._id, null); } i++; cur.moveToNext(); } cur.close(); } } }
From source file:com.aengbee.android.leanback.ui.PlaybackOverlayFragment.java
@Override public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (cursor != null && cursor.moveToFirst()) { if (cursor.getCount() == mBook.size() + 1) { //mQueue.clear(); while (!cursor.isAfterLast()) { Video v = (Video) mVideoCursorMapper.convert(cursor); // Set the queue index to the selected video. if (v.id == mSelectedVideo.id) { mQueueIndex = mQueue.size(); }// w w w.j a v a2 s .c o m // Add the video to the queue. MediaSessionCompat.QueueItem item = getQueueItem(v); if (!mQueue.contains(item)) mQueue.add(item); //mQueue.add(item); cursor.moveToNext(); } mSession.setQueue(mQueue); mSession.setQueueTitle(getString(R.string.queue_name)); mVideoCursorAdapter.changeCursor(cursor); } else { mVideoCursorAdapter.changeCursor(cursor); } } }