List of usage examples for android.database Cursor isAfterLast
boolean isAfterLast();
From source file:org.mozilla.gecko.sync.repositories.android.AndroidBrowserBookmarksRepositorySession.java
/** * Retrieve the child array for a record, repositioning and updating the database as necessary. * * @param folderID// w w w . j a va 2 s .c o m * The database ID of the folder. * @param persist * True if generated positions should be written to the database. The modified * time of the parent folder is only bumped if this is true. * @return * An array of GUIDs. * @throws NullCursorException */ @SuppressWarnings("unchecked") private JSONArray getChildrenArray(long folderID, boolean persist) throws NullCursorException { trace("Calling getChildren for androidID " + folderID); JSONArray childArray = new JSONArray(); Cursor children = dataAccessor.getChildren(folderID); try { if (!children.moveToFirst()) { trace("No children: empty cursor."); return childArray; } final int positionIndex = children.getColumnIndex(BrowserContract.Bookmarks.POSITION); final int count = children.getCount(); Logger.debug(LOG_TAG, "Expecting " + count + " children."); // Sorted by requested position. TreeMap<Long, ArrayList<String>> guids = new TreeMap<Long, ArrayList<String>>(); while (!children.isAfterLast()) { final String childGuid = getGUID(children); final long childPosition = getPosition(children, positionIndex); trace(" Child GUID: " + childGuid); trace(" Child position: " + childPosition); Utils.addToIndexBucketMap(guids, Math.abs(childPosition), childGuid); children.moveToNext(); } // This will suffice for taking a jumble of records and indices and // producing a sorted sequence that preserves some kind of order -- // from the abs of the position, falling back on cursor order (that // is, creation time and ID). // Note that this code is not intended to merge values from two sources! boolean changed = false; int i = 0; for (Entry<Long, ArrayList<String>> entry : guids.entrySet()) { long pos = entry.getKey().longValue(); int atPos = entry.getValue().size(); // If every element has a different index, and the indices are // in strict natural order, then changed will be false. if (atPos > 1 || pos != i) { changed = true; } for (String guid : entry.getValue()) { if (!forbiddenGUID(guid)) { childArray.add(guid); } } } if (Logger.logVerbose(LOG_TAG)) { // Don't JSON-encode unless we're logging. Logger.trace(LOG_TAG, "Output child array: " + childArray.toJSONString()); } if (!changed) { Logger.debug(LOG_TAG, "Nothing moved! Database reflects child array."); return childArray; } if (!persist) { return childArray; } Logger.debug(LOG_TAG, "Generating child array required moving records. Updating DB."); final long time = now(); if (0 < dataAccessor.updatePositions(childArray)) { Logger.debug(LOG_TAG, "Bumping parent time to " + time + "."); dataAccessor.bumpModified(folderID, time); } } finally { children.close(); } return childArray; }
From source file:de.elanev.studip.android.app.frontend.news.NewsListFragment.java
public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) { if (getActivity() == null) { return;/*from w w w.java 2s .c om*/ } int idColumnIdx = 0; int titleColumnIdx = 0; int newsSelector = loader.getId(); switch (newsSelector) { case NewsTabsAdapter.NEWS_COURSES: idColumnIdx = cursor.getColumnIndex(CoursesContract.Columns.Courses.COURSE_ID); titleColumnIdx = cursor.getColumnIndex(CoursesContract.Columns.Courses.COURSE_TITLE); break; case NewsTabsAdapter.NEWS_INSTITUTES: idColumnIdx = cursor.getColumnIndex(InstitutesContract.Columns.INSTITUTE_ID); titleColumnIdx = cursor.getColumnIndex(InstitutesContract.Columns.INSTITUTE_NAME); break; case NewsTabsAdapter.NEWS_GLOBAL: idColumnIdx = -1; titleColumnIdx = -1; break; } List<SectionedCursorAdapter.Section> sections = new ArrayList<SectionedCursorAdapter.Section>(); if (idColumnIdx != -1 || titleColumnIdx != -1) { cursor.moveToFirst(); String previousId = null; String currentId; while (!cursor.isAfterLast()) { currentId = cursor.getString(idColumnIdx); if (!TextUtils.equals(previousId, currentId)) { SectionedCursorAdapter.Section section = new SectionedCursorAdapter.Section( cursor.getPosition(), cursor.getString(titleColumnIdx)); sections.add(section); } previousId = currentId; cursor.moveToNext(); } } mNewsAdapter.setSections(sections); mNewsAdapter.swapCursor(cursor); setLoadingViewVisible(false); }
From source file:com.openerp.orm.ORM.java
/** * Database tables.//from w w w . j a v a2 s . com * * @return the string[] */ public String[] databaseTables() { String[] tables_list = null; List<String> tables = new ArrayList<String>(); SQLiteDatabase db = getWritableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM sqlite_master WHERE type='table';", null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { String tableName = cursor.getString(1); if (!tableName.equals("android_metadata") && !tableName.equals("sqlite_sequence")) tables.add(tableName); cursor.moveToNext(); } cursor.close(); tables_list = tables.toArray(new String[tables.size()]); return tables_list; }
From source file:com.hughes.android.dictionary.DictionaryManagerActivity.java
private synchronized void downloadDictionary(final String downloadUrl, long bytes, Button downloadButton) { String destFile;//from ww w . j a v a2s.c om try { destFile = new File(new URL(downloadUrl).getPath()).getName(); } catch (MalformedURLException e) { throw new RuntimeException("Invalid download URL!", e); } DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE); final DownloadManager.Query query = new DownloadManager.Query(); query.setFilterByStatus( DownloadManager.STATUS_PAUSED | DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING); final Cursor cursor = downloadManager.query(query); // Due to a bug, cursor is null instead of empty when // the download manager is disabled. if (cursor == null) { new AlertDialog.Builder(DictionaryManagerActivity.this).setTitle(getString(R.string.error)) .setMessage(getString(R.string.downloadFailed, R.string.downloadManagerQueryFailed)) .setNeutralButton("Close", null).show(); return; } while (cursor.moveToNext()) { if (downloadUrl.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI)))) break; if (destFile.equals(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_TITLE)))) break; } if (!cursor.isAfterLast()) { downloadManager.remove(cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID))); downloadButton.setText(getString(R.string.downloadButton, bytes / 1024.0 / 1024.0)); cursor.close(); return; } cursor.close(); Request request = new Request(Uri.parse(downloadUrl)); Log.d(LOG, "Downloading to: " + destFile); request.setTitle(destFile); File destFilePath = new File(application.getDictDir(), destFile); destFilePath.delete(); try { request.setDestinationUri(Uri.fromFile(destFilePath)); } catch (Exception e) { } try { downloadManager.enqueue(request); } catch (SecurityException e) { request = new Request(Uri.parse(downloadUrl)); request.setTitle(destFile); downloadManager.enqueue(request); } Log.w(LOG, "Download started: " + destFile); downloadButton.setText("X"); }
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
private int deleteArtwork(@NonNull final Uri uri, final String selection, final String[] selectionArgs) { // Opens the database object in "write" mode. final SQLiteDatabase db = databaseHelper.getWritableDatabase(); String finalWhere = selection; if (MuzeiProvider.uriMatcher.match(uri) == ARTWORK_ID) { finalWhere = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " = " + uri.getLastPathSegment(); // If there were additional selection criteria, append them to the final WHERE clause if (selection != null) finalWhere = finalWhere + " AND " + selection; }/*from www .jav a2s . co m*/ // We can't just simply delete the rows as that won't free up the space occupied by the // artwork image files associated with each row being deleted. Instead we have to query // and manually delete each artwork file String[] projection = new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI, MuzeiContract.Artwork.COLUMN_NAME_TOKEN }; Cursor rowsToDelete = queryArtwork(uri, projection, finalWhere, selectionArgs, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI); if (rowsToDelete == null) { return 0; } // First we build a list of IDs to be deleted. This will be used if we need to determine // if a given image URI needs to be deleted List<String> idsToDelete = new ArrayList<>(); rowsToDelete.moveToFirst(); while (!rowsToDelete.isAfterLast()) { idsToDelete.add(Long.toString(rowsToDelete.getLong(0))); rowsToDelete.moveToNext(); } String notInDeleteIds = MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID + " NOT IN (" + TextUtils.join(",", idsToDelete) + ")"; // Now we actually go through the list of rows to be deleted // and check if we can delete the artwork image file associated with each one rowsToDelete.moveToFirst(); while (!rowsToDelete.isAfterLast()) { Uri artworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, rowsToDelete.getLong(0)); String imageUri = rowsToDelete.getString(1); String token = rowsToDelete.getString(2); if (TextUtils.isEmpty(imageUri) && TextUtils.isEmpty(token)) { // An empty image URI and token means the artwork is unique to this specific row // so we can always delete it when the associated row is deleted File artwork = getCacheFileForArtworkUri(artworkUri); if (artwork != null && artwork.exists()) { artwork.delete(); } } else if (TextUtils.isEmpty(imageUri)) { // Check if there are other rows using this same token that aren't // in the list of ids to delete Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID }, MuzeiContract.Artwork.COLUMN_NAME_TOKEN + "=? AND " + notInDeleteIds, new String[] { token }, null); if (otherArtwork == null) { continue; } if (otherArtwork.getCount() == 0) { // There's no non-deleted rows that reference this same artwork URI // so we can delete the artwork File artwork = getCacheFileForArtworkUri(artworkUri); if (artwork != null && artwork.exists()) { artwork.delete(); } } otherArtwork.close(); } else { // Check if there are other rows using this same image URI that aren't // in the list of ids to delete Cursor otherArtwork = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, new String[] { MuzeiContract.Artwork.TABLE_NAME + "." + BaseColumns._ID }, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI + "=? AND " + notInDeleteIds, new String[] { imageUri }, null); if (otherArtwork == null) { continue; } if (otherArtwork.getCount() == 0) { // There's no non-deleted rows that reference this same artwork URI // so we can delete the artwork File artwork = getCacheFileForArtworkUri(artworkUri); if (artwork != null && artwork.exists()) { artwork.delete(); } } otherArtwork.close(); } rowsToDelete.moveToNext(); } rowsToDelete.close(); int count = db.delete(MuzeiContract.Artwork.TABLE_NAME, finalWhere, selectionArgs); if (count > 0) { notifyChange(uri); } return count; }
From source file:com.piusvelte.sonet.core.SonetCreatePost.java
protected void chooseAccounts() { // don't limit accounts to the widget... Cursor c = this.getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID, ACCOUNTS_QUERY, Accounts.SERVICE }, null, null, null); if (c.moveToFirst()) { int i = 0; ;// w w w . j av a2s .com int count = c.getCount(); final long[] accountIndexes = new long[count]; final String[] accounts = new String[count]; final boolean[] defaults = new boolean[count]; final int[] accountServices = new int[count]; while (!c.isAfterLast()) { long id = c.getLong(0); accountIndexes[i] = id; accounts[i] = c.getString(1); accountServices[i] = c.getInt(2); defaults[i++] = mAccountsService.containsKey(id); c.moveToNext(); } mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts) .setMultiChoiceItems(accounts, defaults, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { final long accountId = accountIndexes[which]; mAccountsService.put(accountId, accountServices[which]); if (sLocationSupported.contains(accountServices[which])) { if (mLat == null) { LocationManager locationManager = (LocationManager) SonetCreatePost.this .getSystemService(Context.LOCATION_SERVICE); Location location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { mLat = Double.toString(location.getLatitude()); mLong = Double.toString(location.getLongitude()); } } if ((mLat != null) && (mLong != null)) { dialog.cancel(); mDialog = (new AlertDialog.Builder(SonetCreatePost.this)) .setTitle(R.string.set_location) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setLocation(accountId); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); mDialog.show(); } } } else { mAccountsService.remove(accountIndexes[which]); mAccountsLocation.remove(accountIndexes[which]); mAccountsTags.remove(accountIndexes[which]); } } }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); mDialog.show(); } c.close(); }
From source file:com.samknows.measurement.storage.DBHelper.java
public JSONObject getArchiveDataSummary() { synchronized (sync) { List<Integer> batches = getTestBatchesByPassiveMetric(getPassiveMetricsFilter()); open();//from w w w .j a v a 2 s.c o m JSONObject ret = new JSONObject(); // test batch counter String counterColumn = "COUNT(*)"; String minDate = "MIN(" + SKSQLiteHelper.TB_COLUMN_DTIME + ")"; String maxDate = "MAX(" + SKSQLiteHelper.TB_COLUMN_DTIME + ")"; String[] columns = { counterColumn, minDate, maxDate }; Cursor cursor = database.query(SKSQLiteHelper.TABLE_TESTBATCH, columns, null, null, null, null, null); cursor.moveToFirst(); String counter = cursor.getLong(0) + ""; String min = cursor.getLong(1) + ""; String max = cursor.getLong(2) + ""; cursor.close(); // test results counter columns = new String[] { SKSQLiteHelper.TR_COLUMN_TYPE, counterColumn }; String groupBy = SKSQLiteHelper.TR_COLUMN_TYPE; String selection = getInClause(SKSQLiteHelper.TR_COLUMN_BATCH_ID, batches); cursor = database.query(SKSQLiteHelper.TABLE_TESTRESULT, columns, selection, null, groupBy, null, null); cursor.moveToFirst(); JSONObject test_counter = new JSONObject(); while (!cursor.isAfterLast()) { try { test_counter.put(TestResult.testStringToId(cursor.getString(0)) + "", cursor.getInt(1) + ""); } catch (JSONException je) { Logger.e(this, "Error in creating a JSONObject: " + je.getMessage()); } cursor.moveToNext(); } cursor.close(); try { ret.put(ARCHIVEDATASUMMARY_COUNTER, counter); ret.put(ARCHIVEDATASUMMARY_STARTDATE, min); ret.put(ARCHIVEDATASUMMARY_ENDDATE, max); ret.put(ARCHIVEDATASUMMARY_TESTCOUNTER, test_counter); } catch (JSONException je) { Logger.e(this, "Error in creating a JSONObject: " + je.getMessage()); } close(); return ret; } }
From source file:com.google.android.apps.muzei.provider.MuzeiProvider.java
private ParcelFileDescriptor openFileArtwork(@NonNull final Uri uri, @NonNull final String mode) throws FileNotFoundException { String[] projection = { BaseColumns._ID, MuzeiContract.Artwork.COLUMN_NAME_IMAGE_URI }; final boolean isWriteOperation = mode.contains("w"); final File file; if (!UserManagerCompat.isUserUnlocked(getContext())) { if (isWriteOperation) { Log.w(TAG, "Wallpaper is read only until the user is unlocked"); return null; }//from w ww . j av a 2s . co m file = DirectBootCacheJobService.getCachedArtwork(getContext()); } else if (!isWriteOperation && MuzeiProvider.uriMatcher.match(uri) == MuzeiProvider.ARTWORK) { // If it isn't a write operation, then we should attempt to find the latest artwork // that does have a cached artwork file. This prevents race conditions where // an external app attempts to load the latest artwork while an art source is inserting a // new artwork Cursor data = queryArtwork(MuzeiContract.Artwork.CONTENT_URI, projection, null, null, null); if (data == null) { return null; } if (!data.moveToFirst()) { if (!getContext().getPackageName().equals(getCallingPackage())) { Log.w(TAG, "You must insert at least one row to read or write artwork"); } return null; } File foundFile = null; while (!data.isAfterLast()) { Uri possibleArtworkUri = ContentUris.withAppendedId(MuzeiContract.Artwork.CONTENT_URI, data.getLong(0)); File possibleFile = getCacheFileForArtworkUri(possibleArtworkUri); if (possibleFile != null && possibleFile.exists()) { foundFile = possibleFile; break; } data.moveToNext(); } file = foundFile; } else { file = getCacheFileForArtworkUri(uri); } if (file == null) { throw new FileNotFoundException("Could not create artwork file"); } if (file.exists() && file.length() > 0 && isWriteOperation) { Context context = getContext(); if (context == null) { return null; } if (!context.getPackageName().equals(getCallingPackage())) { Log.w(TAG, "Writing to an existing artwork file is not allowed: insert a new row"); } cleanupCachedFiles(); return null; } try { return ParcelFileDescriptor.open(file, ParcelFileDescriptor.parseMode(mode), openFileHandler, new ParcelFileDescriptor.OnCloseListener() { @Override public void onClose(final IOException e) { if (isWriteOperation) { if (e != null) { Log.e(TAG, "Error closing " + file + " for " + uri, e); if (file.exists()) { if (!file.delete()) { Log.w(TAG, "Unable to delete " + file); } } } else { // The file was successfully written, notify listeners of the new artwork notifyChange(uri); cleanupCachedFiles(); } } } }); } catch (IOException e) { Log.e(TAG, "Error opening artwork " + uri, e); throw new FileNotFoundException("Error opening artwork " + uri); } }
From source file:edu.auburn.ppl.cyclecolumbus.TripUploader.java
/****************************************************************************************** * Gets each coordinate that was set during a trip and the info that goes along with it. ****************************************************************************************** * @param tripId Unique trip ID// w ww .j a v a2 s . com * @return JSONObject representing all of the points set during trip * @throws JSONException ******************************************************************************************/ private JSONObject getCoordsJSON(long tripId) throws JSONException { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mDb.openReadOnly(); 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("r"), coord); tripCoordsCursor.moveToNext(); } tripCoordsCursor.close(); mDb.close(); return tripCoords; }
From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java
protected void chooseAccounts() { // don't limit accounts to the widget... Cursor c = this.getContentResolver().query(Accounts.getContentUri(this), new String[] { Accounts._ID, ACCOUNTS_QUERY, Accounts.SERVICE }, null, null, null); if (c.moveToFirst()) { int i = 0; ;//from w ww . j a va 2 s . co m int count = c.getCount(); final long[] accountIndexes = new long[count]; final String[] accounts = new String[count]; final boolean[] defaults = new boolean[count]; final int[] accountServices = new int[count]; while (!c.isAfterLast()) { long id = c.getLong(0); accountIndexes[i] = id; accounts[i] = c.getString(1); accountServices[i] = c.getInt(2); defaults[i++] = mAccountsService.containsKey(id); c.moveToNext(); } mDialog = (new AlertDialog.Builder(this)).setTitle(R.string.accounts) .setMultiChoiceItems(accounts, defaults, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { if (isChecked) { final long accountId = accountIndexes[which]; mAccountsService.put(accountId, accountServices[which]); if (sLocationSupported.contains(accountServices[which])) { if (mLat == null) { LocationManager locationManager = (LocationManager) MyfeedleCreatePost.this .getSystemService(Context.LOCATION_SERVICE); Location location = locationManager .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { mLat = Double.toString(location.getLatitude()); mLong = Double.toString(location.getLongitude()); } } if ((mLat != null) && (mLong != null)) { dialog.cancel(); mDialog = (new AlertDialog.Builder(MyfeedleCreatePost.this)) .setTitle(R.string.set_location) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setLocation(accountId); dialog.dismiss(); } }) .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .create(); mDialog.show(); } } } else { mAccountsService.remove(accountIndexes[which]); mAccountsLocation.remove(accountIndexes[which]); mAccountsTags.remove(accountIndexes[which]); } } }).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); mDialog.show(); } c.close(); }