Example usage for android.database Cursor moveToLast

List of usage examples for android.database Cursor moveToLast

Introduction

In this page you can find the example usage for android.database Cursor moveToLast.

Prototype

boolean moveToLast();

Source Link

Document

Move the cursor to the last row.

Usage

From source file:com.xorcode.andtweet.FriendTimeline.java

/**
 * Remove old records to ensure that the database does not grow too large.
 * Maximum number of records is configured in "history_size" preference
 * /*from  w w  w  . j av a2s .c o  m*/
 * @return Number of deleted records
 */
public int pruneOldRecords() {
    int nDeleted = 0;
    int nDeletedTime = 0;
    // We're using global preferences here
    SharedPreferences sp = MyPreferences.getDefaultSharedPreferences();
    int maxDays = Integer.parseInt(sp.getString(MyPreferences.KEY_HISTORY_TIME, "3"));
    long sinceTimestamp = 0;
    if (maxDays > 0) {
        sinceTimestamp = System.currentTimeMillis() - maxDays * (1000L * 60 * 60 * 24);

        SelectionAndArgs sa = new SelectionAndArgs();
        sa.addSelection(AndTweetDatabase.Tweets.SENT_DATE + " <  ?",
                new String[] { String.valueOf(sinceTimestamp) });

        if (mTimelineType != AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES) {
            // Don't delete Favorites!
            sa.addSelection(AndTweetDatabase.Tweets.FAVORITED + " = ?", new String[] { "0" });
        }
        nDeletedTime = mContentResolver.delete(mContentUri, sa.selection, sa.selectionArgs);
    }

    int nTweets = 0;
    int nToDeleteSize = 0;
    int nDeletedSize = 0;
    int maxSize = Integer.parseInt(sp.getString(MyPreferences.KEY_HISTORY_SIZE, "2000"));
    long sinceTimestampSize = 0;
    if (maxSize > 0) {
        try {

            nDeletedSize = 0;
            Cursor cursor = mContentResolver.query(mContentCountUri, null, null, null, null);
            if (cursor.moveToFirst()) {
                // Count is in the first column
                nTweets = cursor.getInt(0);
                nToDeleteSize = nTweets - maxSize;
            }
            cursor.close();
            if (nToDeleteSize > 0) {
                // Find SENT_DATE of the most recent tweet to delete
                cursor = mContentResolver.query(mContentUri, new String[] { AndTweetDatabase.Tweets.SENT_DATE },
                        null, null, "sent ASC LIMIT 0," + nToDeleteSize);
                if (cursor.moveToLast()) {
                    sinceTimestampSize = cursor.getLong(0);
                }
                cursor.close();
                if (sinceTimestampSize > 0) {
                    SelectionAndArgs sa = new SelectionAndArgs();
                    sa.addSelection(AndTweetDatabase.Tweets.SENT_DATE + " <=  ?",
                            new String[] { String.valueOf(sinceTimestampSize) });
                    if (mTimelineType != AndTweetDatabase.Tweets.TIMELINE_TYPE_MESSAGES) {
                        sa.addSelection(AndTweetDatabase.Tweets.FAVORITED + " = ?", new String[] { "0" });
                    }
                    nDeletedSize = mContentResolver.delete(mContentUri, sa.selection, sa.selectionArgs);
                }
            }
        } catch (Exception e) {
            Log.e(TAG, "pruneOldRecords failed");
            e.printStackTrace();
        }
    }
    nDeleted = nDeletedTime + nDeletedSize;
    if (MyLog.isLoggable(TAG, Log.VERBOSE)) {
        Log.v(TAG, "pruneOldRecords; History time=" + maxDays + " days; deleted " + nDeletedTime + " , since "
                + sinceTimestamp + ", now=" + System.currentTimeMillis());
        Log.v(TAG, "pruneOldRecords; History size=" + maxSize + " tweets; deleted " + nDeletedSize + " of "
                + nTweets + " tweets, since " + sinceTimestampSize);
    }

    return nDeleted;
}

From source file:cn.tangxb.imageselector.PhotoModelTaskLoader.java

@Override
public ArrayList<PhotoModel> loadInBackground() {
    synchronized (this) {
        if (isLoadInBackgroundCanceled()) {
            throw new OperationCanceledException();
        }//from  w ww.j a  v  a  2 s .c om
        mCancellationSignal = new CancellationSignal();
    }
    try {
        Cursor cursor = ContentResolverCompat.query(getContext().getContentResolver(),
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                new String[] { MediaStore.Images.ImageColumns.DATA, MediaStore.Images.ImageColumns.DATE_ADDED,
                        MediaStore.Images.ImageColumns.SIZE },
                null, null, MediaStore.Images.ImageColumns.DATE_ADDED, mCancellationSignal);
        if (cursor != null) {
            try {
                // Ensure the cursor window is filled.
                cursor.getCount();
                cursor.registerContentObserver(mObserver);
                mData = new ArrayList<>();

                if (cursor == null || !cursor.moveToNext())
                    return mData;
                cursor.moveToLast();
                do {
                    if (cursor.getLong(cursor.getColumnIndex(MediaStore.Images.ImageColumns.SIZE)) > 1024
                            * 10) {
                        PhotoModel photoModel = new PhotoModel();
                        photoModel.setOriginalPath(
                                cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)));
                        mData.add(photoModel);
                    }
                } while (cursor.moveToPrevious());
            } catch (RuntimeException ex) {
                cursor.close();
                throw ex;
            }
        }
        return mData;
    } finally {
        synchronized (this) {
            mCancellationSignal = null;
        }
    }
}

From source file:com.androzic.location.LocationService.java

public Track getTrack(long limit) {
    if (trackDB == null)
        openDatabase();//from  ww  w .  j  a va 2  s.  c  om
    Track track = new Track();
    if (trackDB == null)
        return track;
    String limitStr = limit > 0 ? " LIMIT " + limit : "";
    Cursor cursor = trackDB.rawQuery("SELECT * FROM track ORDER BY _id DESC" + limitStr, null);
    for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious()) {
        double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
        double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
        double elevation = cursor.getDouble(cursor.getColumnIndex("elevation"));
        double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
        double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
        double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
        int code = cursor.getInt(cursor.getColumnIndex("code"));
        long time = cursor.getLong(cursor.getColumnIndex("datetime"));
        track.addPoint(code == 0, latitude, longitude, elevation, speed, bearing, accuracy, time);
    }
    cursor.close();
    return track;
}

From source file:com.MustacheMonitor.MustacheMonitor.StacheCam.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL/*from  w  w w  .j  a v a  2s  .c  o  m*/
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}

From source file:com.android.mms.transaction.MessagingNotification.java

private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) {
    ContentResolver resolver = context.getContentResolver();
    Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI, SMS_STATUS_PROJECTION,
            NEW_DELIVERY_SM_CONSTRAINT, null, Sms.DATE);

    if (cursor == null) {
        return null;
    }/*from   ww w  . ja v  a2  s.c om*/

    try {
        if (!cursor.moveToLast()) {
            return null;
        }

        String address = cursor.getString(COLUMN_SMS_ADDRESS);
        long timeMillis = 3000;

        Contact contact = Contact.get(address, false);
        String name = contact.getNameAndNumber();

        return new MmsSmsDeliveryInfo(context.getString(R.string.delivery_toast_body, name), timeMillis);

    } finally {
        cursor.close();
    }
}

From source file:com.logilite.vision.camera.CameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL/*from   w  w w .  java 2 s  . c  o m*/
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}

From source file:com.androzic.location.LocationService.java

public Track getTrack(long start, long end) {
    if (trackDB == null)
        openDatabase();/*  w  w w .j a v a2 s  .  c  om*/
    Track track = new Track();
    if (trackDB == null)
        return track;
    Cursor cursor = trackDB.rawQuery(
            "SELECT * FROM track WHERE datetime >= ? AND datetime <= ? ORDER BY _id DESC",
            new String[] { String.valueOf(start), String.valueOf(end) });
    for (boolean hasItem = cursor.moveToLast(); hasItem; hasItem = cursor.moveToPrevious()) {
        double latitude = cursor.getDouble(cursor.getColumnIndex("latitude"));
        double longitude = cursor.getDouble(cursor.getColumnIndex("longitude"));
        double elevation = cursor.getDouble(cursor.getColumnIndex("elevation"));
        double speed = cursor.getDouble(cursor.getColumnIndex("speed"));
        double bearing = cursor.getDouble(cursor.getColumnIndex("track"));
        double accuracy = cursor.getDouble(cursor.getColumnIndex("accuracy"));
        int code = cursor.getInt(cursor.getColumnIndex("code"));
        long time = cursor.getLong(cursor.getColumnIndex("datetime"));
        track.addPoint(code == 0, latitude, longitude, elevation, speed, bearing, accuracy, time);
    }
    cursor.close();
    return track;
}

From source file:com.cordova.photo.CameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to images
 * to the content store. If we are using a FILE_URI and the number of images in the DB
 * increases by 2 we have a duplicate, when using a DATA_URL the number is 1.
 *
 * @param type FILE_URI or DATA_URL/*ww  w . j a  va  2  s . c  o m*/
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1 for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.activity.getContentResolver().delete(uri, null, null);
        cursor.close();
    }
}

From source file:com.nogago.android.tracks.services.TrackRecordingService.java

private void restoreStats(Track track) {
    Log.d(TAG, "Restoring stats of track with ID: " + track.getId());

    TripStatistics stats = track.getTripStatistics();
    statsBuilder = new TripStatisticsBuilder(stats.getStartTime());
    statsBuilder.setMinRecordingDistance(minRecordingDistance);

    length = 0;/*from  www . jav  a  2s.  c om*/
    lastValidLocation = null;

    Waypoint waypoint = providerUtils.getFirstWaypoint(recordingTrackId);
    if (waypoint != null && waypoint.getTripStatistics() != null) {
        currentWaypointId = waypoint.getId();
        waypointStatsBuilder = new TripStatisticsBuilder(waypoint.getTripStatistics());
    } else {
        // This should never happen, but we got to do something so life goes on:
        waypointStatsBuilder = new TripStatisticsBuilder(stats.getStartTime());
        currentWaypointId = -1;
    }
    waypointStatsBuilder.setMinRecordingDistance(minRecordingDistance);

    Cursor cursor = null;
    try {
        cursor = providerUtils.getLocationsCursor(recordingTrackId, -1, Constants.MAX_LOADED_TRACK_POINTS,
                true);
        if (cursor != null) {
            if (cursor.moveToLast()) {
                do {
                    Location location = providerUtils.createLocation(cursor);
                    if (LocationUtils.isValidLocation(location)) {
                        statsBuilder.addLocation(location, location.getTime());
                        if (lastValidLocation != null) {
                            length += location.distanceTo(lastValidLocation);
                        }
                        lastValidLocation = location;
                    }
                } while (cursor.moveToPrevious());
            }
            statsBuilder.getStatistics().setMovingTime(stats.getMovingTime());
            statsBuilder.pauseAt(stats.getStopTime());
            statsBuilder.resumeAt(System.currentTimeMillis());
        } else {
            Log.e(TAG, "Could not get track points cursor.");
        }
    } catch (RuntimeException e) {
        Log.e(TAG, "Error while restoring track.", e);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

    announcementExecutor.restore();
    splitExecutor.restore();
}

From source file:com.phonegap.plugins.wsiCameraLauncher.WsiCameraLauncher.java

/**
 * Used to find out if we are in a situation where the Camera Intent adds to
 * images to the content store. If we are using a FILE_URI and the number of
 * images in the DB increases by 2 we have a duplicate, when using a
 * DATA_URL the number is 1.//  w w w  .  j  a  v  a 2s. c o  m
 * 
 * @param type
 *            FILE_URI or DATA_URL
 */
private void checkForDuplicateImage(int type) {
    int diff = 1;
    Uri contentStore = whichContentStore();
    Cursor cursor = queryImgDB(contentStore);
    int currentNumOfImages = cursor.getCount();

    if (type == FILE_URI && this.saveToPhotoAlbum) {
        diff = 2;
    }

    // delete the duplicate file if the difference is 2 for file URI or 1
    // for Data URL
    if ((currentNumOfImages - numPics) == diff) {
        cursor.moveToLast();
        int id = Integer.valueOf(cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media._ID)));
        if (diff == 2) {
            id--;
        }
        Uri uri = Uri.parse(contentStore + "/" + id);
        this.cordova.getActivity().getContentResolver().delete(uri, null, null);
    }
}