Example usage for android.database Cursor getLong

List of usage examples for android.database Cursor getLong

Introduction

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

Prototype

long getLong(int columnIndex);

Source Link

Document

Returns the value of the requested column as a long.

Usage

From source file:com.fvd.nimbus.MainActivity.java

String getImagePath() {

    String[] projection = { MediaStore.Images.Thumbnails._ID, // The columns we want
            MediaStore.Images.Thumbnails.IMAGE_ID, MediaStore.Images.Thumbnails.KIND,
            MediaStore.Images.Thumbnails.DATA };
    String selection = MediaStore.Images.Thumbnails.KIND + "=" + // Select only mini's
            MediaStore.Images.Thumbnails.MINI_KIND;

    String sort = MediaStore.Images.Thumbnails._ID + " DESC";

    //At the moment, this is a bit of a hack, as I'm returning ALL images, and just taking the latest one. There is a better way to narrow this down I think with a WHERE clause which is currently the selection variable
    Cursor myCursor = this.managedQuery(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection,
            selection, null, sort);/*from  w ww . j  a v  a 2s  .  co  m*/

    long imageId = 0l;
    long thumbnailImageId = 0l;
    String thumbnailPath = "";

    try {
        myCursor.moveToFirst();
        imageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.IMAGE_ID));
        thumbnailImageId = myCursor.getLong(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID));
        thumbnailPath = myCursor.getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails.DATA));
    } finally {
        myCursor.close();
    }

    //Create new Cursor to obtain the file Path for the large image

    String[] largeFileProjection = { MediaStore.Images.ImageColumns._ID, MediaStore.Images.ImageColumns.DATA };

    String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
    myCursor = this.managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, largeFileProjection, null, null,
            largeFileSort);
    String largeImagePath = "";

    try {
        myCursor.moveToFirst();

        largeImagePath = myCursor
                .getString(myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
    } finally {
        myCursor.close();
    }
    // These are the two URI's you'll be interested in. They give you a handle to the actual images
    Uri uriLargeImage = Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
            String.valueOf(imageId));
    Uri uriThumbnailImage = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
            String.valueOf(thumbnailImageId));

    if (largeImagePath.length() > 0)
        return largeImagePath;
    else if (uriLargeImage != null)
        return uriLargeImage.getPath();
    else if (uriThumbnailImage != null)
        return uriThumbnailImage.getPath();
    else
        return "";

}

From source file:it.gmariotti.android.examples.googleaccount.SmsBackupGDriveActivity.java

private JSONObject readSmsInbox() throws JSONException {
    Cursor cursor = getSmsInboxCursor();
    // StringBuilder messages = new StringBuilder();
    JSONArray messages = new JSONArray();

    String and = "";

    if (cursor != null) {
        final String[] columns = cursor.getColumnNames();
        while (cursor.moveToNext()) {
            // messages.append(and);
            JSONObject msg = new JSONObject();
            // long id = cursor.getLong(SmsQuery._ID);
            long contactId = cursor.getLong(SmsQuery.PERSON);
            String address = cursor.getString(SmsQuery.ADDRESS);
            // long threadId = cursor.getLong(SmsQuery.THREAD_ID);
            // final long date = cursor.getLong(SmsQuery.DATE);

            final Map<String, String> msgMap = new HashMap<String, String>(columns.length);

            for (int i = 0; i < columns.length; i++) {
                String value = cursor.getString(i);
                msgMap.put(columns[i], cursor.getString(i));
                /*/*from w  w w.j av a2 s.  c o  m*/
                 * messages.append(columns[i]); messages.append("=");
                 * messages.append(value); messages.append(";;");
                 */
                msg.put(columns[i], value);

            }
            // and = "\n";

            /**
             * Retrieve display name
             * 
             */
            String displayName = address;

            if (contactId > 0) {
                // Retrieve from Contacts with contact id
                Cursor contactCursor = tryOpenContactsCursorById(contactId);
                if (contactCursor != null) {
                    if (contactCursor.moveToFirst()) {
                        displayName = contactCursor.getString(RawContactsQuery.DISPLAY_NAME);
                    } else {
                        contactId = 0;
                    }
                    contactCursor.close();
                }
            } else {
                if (contactId <= 0) {
                    // Retrieve with address
                    Cursor contactCursor = tryOpenContactsCursorByAddress(address);
                    if (contactCursor != null) {
                        if (contactCursor.moveToFirst()) {
                            displayName = contactCursor.getString(ContactsQuery.DISPLAY_NAME);
                        }
                        contactCursor.close();
                    }
                }
            }
            /*
             * messages.append("displayName"); messages.append("=");
             * messages.append(displayName); messages.append(";;");
             * messages.append("||");
             */
            msg.put("displayName", displayName);

            messages.put(msg);

        }
    }

    JSONObject fileBackupTest = new JSONObject();
    fileBackupTest.put("messages", messages);
    return fileBackupTest;
}

From source file:cn.code.notes.gtask.data.Task.java

public int getSyncAction(Cursor c) {
    try {//from  www .j a  v a  2  s.com
        JSONObject noteInfo = null;
        if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
            noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        }

        if (noteInfo == null) {
            Log.w(TAG, "it seems that note meta has been deleted");
            return SYNC_ACTION_UPDATE_REMOTE;
        }

        if (!noteInfo.has(NoteColumns.ID)) {
            Log.w(TAG, "remote note id seems to be deleted");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        // validate the note id now
        if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
            Log.w(TAG, "note id doesn't match");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
            // there is no local update
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // no update both side
                return SYNC_ACTION_NONE;
            } else {
                // apply remote to local
                return SYNC_ACTION_UPDATE_LOCAL;
            }
        } else {
            // validate gtask id
            if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
                Log.e(TAG, "gtask id doesn't match");
                return SYNC_ACTION_ERROR;
            }
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // local modification only
                return SYNC_ACTION_UPDATE_REMOTE;
            } else {
                return SYNC_ACTION_UPDATE_CONFLICT;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    return SYNC_ACTION_ERROR;
}

From source file:edu.stanford.mobisocial.dungbeetle.MessagingManagerThread.java

private List<Long> getFeedSubscribers(Uri feedUri) {
    if (feedUri == null) {
        throw new NullPointerException("Feed cannot be null");
    }/*from w  w w .  ja v a  2  s .  co  m*/
    String feedName = feedUri.getLastPathSegment();
    switch (Feed.typeOf(feedUri)) {
    case FRIEND:
        String personId = Feed.friendIdForFeed(feedUri);
        if (personId == null) {
            return new ArrayList<Long>(0);
        }
        String table = Contact.TABLE;
        String[] columns = new String[] { Contact._ID };
        String selection = Contact.PERSON_ID + " = ?";
        String[] selectionArgs = new String[] { personId };
        String groupBy = null;
        String having = null;
        String orderBy = null;
        Cursor c = mHelper.getReadableDatabase().query(table, columns, selection, selectionArgs, groupBy,
                having, orderBy);
        if (c == null || !c.moveToFirst()) {
            Log.w(TAG, "Could not find user for id " + personId);
            return new ArrayList<Long>(0);
        }
        return Collections.singletonList(c.getLong(0));
    case APP:
        // Currently, we send app messages to all users, which are registered
        // as subscribers to the "friend" feed. The subscribers model needs to
        // be reworked, and further the "app" feed needs further thinking.
        // Messages should be lossy, and encryption should not require keys
        // for each recipient.
        feedName = "friend";
        // No break:
    case GROUP:
        Cursor subs = mHelper.querySubscribers(feedName);
        List<Long> recipientIds = new ArrayList<Long>(subs.getCount());
        subs.moveToFirst();
        while (!subs.isAfterLast()) {
            long id = subs.getLong(subs.getColumnIndexOrThrow(Subscriber.CONTACT_ID));
            recipientIds.add(id);
            subs.moveToNext();
        }
        subs.close();
        return recipientIds;
    default:
        Log.w(TAG, "unmatched feed type for " + feedUri);
        return new ArrayList<Long>();
    }
}

From source file:edu.cens.loci.ui.VisitDetailActivity.java

private void updateData(Uri visitUri) {
    ContentResolver resolver = getContentResolver();
    Cursor visitCursor = resolver.query(visitUri, VISIT_LOG_PROJECTION, null, null, null);
    try {/* w w w .  j av a2  s .c om*/
        if (visitCursor != null && visitCursor.moveToFirst()) {
            long placeId = visitCursor.getLong(PLACE_ID_INDEX);
            long enter = visitCursor.getLong(ENTER_INDEX);
            long exit = visitCursor.getLong(EXIT_INDEX);
            int type = visitCursor.getInt(TYPE);
            String extra1 = visitCursor.getString(EXTRA1_INDEX);
            String extra2 = visitCursor.getString(EXTRA2_INDEX);

            MyLog.d(LociConfig.D.UI.DEBUG, TAG,
                    String.format("[updateData] placeId=%d enter=%s exit=%s type=%d extra1=%s extra2=%s",
                            placeId, MyDateUtils.getTimeFormatLong(enter), MyDateUtils.getTimeFormatLong(exit),
                            type, extra1, extra2));

            // Place name
            String place_name = "";
            int place_state = 0;

            if (placeId > 0) {
                String placeSelection = Places._ID + "=" + placeId;
                Uri placeUri = ContentUris.withAppendedId(Places.CONTENT_URI, placeId);
                Cursor placeCursor = resolver.query(placeUri, PLACE_PROJECTION, placeSelection, null, null);

                if (placeCursor != null && placeCursor.moveToFirst()) {
                    place_name = placeCursor.getString(PLACE_NAME_INDEX);
                    place_state = placeCursor.getInt(PLACE_STATE_INDEX);
                    placeCursor.close();
                } else {
                    place_name = "Unknown";
                }
            } else {
                place_name = "Unknown";
            }
            mPlaceName.setText(place_name);

            // Pull out string in format [relative], [date]
            CharSequence dateClause = DateUtils.formatDateRange(this, enter, enter, DateUtils.FORMAT_SHOW_TIME
                    | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_SHOW_YEAR);

            mVisitTime.setText(dateClause);

            // Set the duration
            mVisitDuration.setText(formatDuration((exit - enter) / 1000));

            switch (type) {
            case Visits.TYPE_GPS:
                mPlaceTypeIcon.setImageResource(R.drawable.icon_satellite);
                break;
            case Visits.TYPE_WIFI:
                mPlaceTypeIcon.setImageResource(R.drawable.icon_wifi);
                break;
            }

            List<ViewEntry> actions = new ArrayList<ViewEntry>();

            // View place
            Intent viewPlaceIntent = new Intent(Intent.ACTION_VIEW,
                    ContentUris.withAppendedId(Places.CONTENT_URI, placeId));
            String placeViewLabel = "";

            MyLog.d(LociConfig.D.UI.DEBUG, TAG,
                    String.format("[updateData] placename=%s placestate=%d", place_name, place_state));

            switch (place_state) {
            case Places.STATE_SUGGESTED:
                placeViewLabel = "Handle Suggested Place";
                break;
            case Places.STATE_REGISTERED:
                placeViewLabel = "View " + place_name;
                break;
            default:
                placeViewLabel = null;//place_name + " state " + place_state;
            }

            if (placeViewLabel != null) {
                ViewEntry entry = new ViewEntry(LIST_ACTION_VIEW_PLACE, R.drawable.sym_action_map,
                        placeViewLabel, null, null);
                entry.intent = viewPlaceIntent;
                actions.add(entry);
            }

            // View Wifi APs
            if (type == Visits.TYPE_WIFI && extra1 != null) {

                LociWifiFingerprint wifi;
                String apsAbstract = "Not available";

                try {
                    wifi = new LociWifiFingerprint(extra1);
                    apsAbstract = wifi.getWifiInfoSubstring(5);
                    ViewEntry wifiEntry = new ViewEntry(LIST_ACTION_VIEW_WIFIS, R.drawable.ic_settings_wireless,
                            "View Wi-Fi APs", apsAbstract, null);
                    wifiEntry.extra_string = extra1;

                    actions.add(wifiEntry);
                } catch (JSONException e) {
                    MyLog.e(LociConfig.D.JSON, TAG, "wifi json failed : " + extra1);
                    e.printStackTrace();
                }
            }

            // Additional Actions
            if (placeId > 0) {
                if (place_state == Places.STATE_REGISTERED || place_state == Places.STATE_BLOCKED) {
                    if (type == Visits.TYPE_WIFI && extra1 != null) {
                        ViewEntry entry = new ViewEntry(LIST_ACTION_CHANGE_PLACE,
                                android.R.drawable.ic_menu_edit, "Change Place", null, null);
                        entry.intent = new Intent(Intents.UI.ACTION_INSERT);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_KEY,
                                PlacesList.LIST_ORDER_TYPE_WIFI_SIMILARITY);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_KEY, extra1);
                        entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_TIME_KEY, String.valueOf(enter));
                        entry.intent.putExtra(Intents.UI.PLACE_ENTRY_TYPE_EXTRA_KEY,
                                Places.ENTRY_WIFI_OVERWRITE_WRONG_RECOGNITION);
                        actions.add(entry);
                    }
                }
            } else {
                ViewEntry entry = new ViewEntry(LIST_ACTION_ADD_PLACE, R.drawable.sym_action_add, "Add Place",
                        null, null);
                entry.intent = new Intent(Intents.UI.ACTION_INSERT);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_KEY,
                        PlacesList.LIST_ORDER_TYPE_WIFI_SIMILARITY);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_KEY, extra1);
                entry.intent.putExtra(Intents.UI.LIST_ORDER_EXTRA_WIFI_TIME_KEY, String.valueOf(enter));
                entry.intent.putExtra(Intents.UI.PLACE_ENTRY_TYPE_EXTRA_KEY, Places.ENTRY_WIFI_USE_SHORT_VISIT);
                actions.add(entry);
            }

            // View Recognition Results
            //Log.d(TAG, "recog: " + extra2);
            if (extra2 != null && !TextUtils.isEmpty(extra2)) {
                ViewEntry recogEntry = new ViewEntry(LIST_ACTION_VIEW_RECOGNITION,
                        R.drawable.ic_clock_strip_desk_clock, "View Recogntion Results", "", null);
                recogEntry.extra_string = extra2;
                actions.add(recogEntry);
            }

            ViewAdapter adapter = new ViewAdapter(this, actions);
            setListAdapter(adapter);

            //Log.d(TAG, String.format("placeId=%d enter=%s exit=%s", placeId, MyDateUtils.getDateFormatLong(enter), MyDateUtils.getDateFormatLong(exit)));
            //Log.d(TAG, String.format("extra1=%s", extra1));
            //Log.d(TAG, String.format("extra2=%s", extra2));
        }

    } finally {
        if (visitCursor != null) {
            visitCursor.close();
        }
    }
}

From source file:com.example.whetzel.sunshine.FetchWeatherTask.java

/**
 * Helper method to handle insertion of a new location in the weather database.
 *
 * @param locationSetting The location string used to request updates from the server.
 * @param cityName A human-readable city name, e.g "Mountain View"
 * @param lat the latitude of the city/*from ww w .ja v  a2 s  .  co m*/
 * @param lon the longitude of the city
 * @return the row ID of the added location.
 */
long addLocation(String locationSetting, String cityName, double lat, double lon) {
    long locationId;
    // Students: First, check if the location with this city name exists in the db
    Cursor locationCursor = mContext.getContentResolver().query(WeatherContract.LocationEntry.CONTENT_URI,
            new String[] { WeatherContract.LocationEntry._ID },
            WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING + " =? ", new String[] { locationSetting },
            null);

    // If it exists, return the current ID
    // Otherwise, insert it using the content resolver and the base URI
    if (locationCursor.moveToFirst()) {
        int locationIdIndex = locationCursor.getColumnIndex(WeatherContract.LocationEntry._ID);
        locationId = locationCursor.getLong(locationIdIndex);
    } else {
        // Now that the content provider is set up, inserting rows of data is pretty simple.
        // First create a ContentValues object to hold the data you want to insert.
        ContentValues locationValues = new ContentValues();
        // Then add the data, along with the corresponding name of the data type,
        // so the content provider knows what kind of value is being inserted.
        locationValues.put(WeatherContract.LocationEntry.COLUMN_CITY_NAME, cityName);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_LOCATION_SETTING, locationSetting);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LAT, lat);
        locationValues.put(WeatherContract.LocationEntry.COLUMN_COORD_LONG, lon);
        // Finally, insert location data into the database.
        Uri insertedUri = mContext.getContentResolver().insert(WeatherContract.LocationEntry.CONTENT_URI,
                locationValues);
        // The resulting URI contains the ID for the row. Extract the locationId from the Uri.
        locationId = ContentUris.parseId(insertedUri);
    }
    locationCursor.close();

    return locationId;
}

From source file:com.asd.littleprincesbeauty.data.Task.java

@Override
public int getSyncAction(Cursor c) {
    try {/*  w ww  .ja v  a  2s .  c o m*/
        JSONObject noteInfo = null;
        if (mMetaInfo != null && mMetaInfo.has(GTaskStringUtils.META_HEAD_NOTE)) {
            noteInfo = mMetaInfo.getJSONObject(GTaskStringUtils.META_HEAD_NOTE);
        }

        if (noteInfo == null) {
            Log.w(TAG, "it seems that note meta has been deleted");
            return SYNC_ACTION_UPDATE_REMOTE;
        }

        if (!noteInfo.has(NoteColumns.ID)) {
            Log.w(TAG, "remote note id seems to be deleted");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        // validate the note id now
        if (c.getLong(SqlNote.ID_COLUMN) != noteInfo.getLong(NoteColumns.ID)) {
            Log.w(TAG, "note id doesn't match");
            return SYNC_ACTION_UPDATE_LOCAL;
        }

        if (c.getInt(SqlNote.LOCAL_MODIFIED_COLUMN) == 0) {
            // there is no local update
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // no update both side
                return SYNC_ACTION_NONE;
            } else {
                // apply remote to local
                return SYNC_ACTION_UPDATE_LOCAL;
            }
        } else {
            // validate gtask id
            if (!c.getString(SqlNote.GTASK_ID_COLUMN).equals(getGid())) {
                Log.e(TAG, "gtask id doesn't match");
                return SYNC_ACTION_ERROR;
            }
            if (c.getLong(SqlNote.SYNC_ID_COLUMN) == getLastModified()) {
                // local modification only
                return SYNC_ACTION_UPDATE_REMOTE;
            } else {
                return SYNC_ACTION_UPDATE_CONFLICT;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }

    return SYNC_ACTION_ERROR;
}

From source file:mobisocial.socialkit.musubi.Musubi.java

public DbObj objForCursor(Cursor cursor) {
    try {// w  w  w .jav  a  2  s.co  m
        long localId = -1;
        String appId = null;
        String type = null;
        String name = null;
        JSONObject json = null;
        long senderId = -1;
        byte[] hash = null;
        long feedId = -1;
        Integer intKey = null;
        long timestamp = -1;
        Long parentId = null;

        try {
            localId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_ID));
        } catch (IllegalArgumentException e) {
        }
        try {
            appId = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_APP_ID));
        } catch (IllegalArgumentException e) {
        }
        try {
            type = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_TYPE));
        } catch (IllegalArgumentException e) {
        }
        try {
            name = cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_STRING_KEY));
        } catch (IllegalArgumentException e) {
        }
        try {
            json = new JSONObject(cursor.getString(cursor.getColumnIndexOrThrow(DbObj.COL_JSON)));
        } catch (IllegalArgumentException e) {
        }
        try {
            senderId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_IDENTITY_ID));
        } catch (IllegalArgumentException e) {
        }
        try {
            hash = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_UNIVERSAL_HASH));
        } catch (IllegalArgumentException e) {
        }
        try {
            feedId = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_FEED_ID));
        } catch (IllegalArgumentException e) {
        }
        try {
            intKey = cursor.getInt(cursor.getColumnIndexOrThrow(DbObj.COL_INT_KEY));
        } catch (IllegalArgumentException e) {
        }
        try {
            timestamp = cursor.getLong(cursor.getColumnIndexOrThrow(DbObj.COL_TIMESTAMP));
        } catch (IllegalArgumentException e) {
        }
        try {
            int pIndex = cursor.getColumnIndexOrThrow(DbObj.COL_PARENT_ID);
            if (!cursor.isNull(pIndex)) {
                parentId = cursor.getLong(pIndex);
            }
        } catch (IllegalArgumentException e) {
        }

        // Don't require raw field.
        final byte[] raw;
        int rawIndex = cursor.getColumnIndex(DbObj.COL_RAW);
        if (rawIndex == -1 || cursor.isNull(rawIndex)) {
            raw = null;
        } else {
            raw = cursor.getBlob(cursor.getColumnIndexOrThrow(DbObj.COL_RAW));
        }
        return new DbObj(this, appId, feedId, parentId, senderId, localId, type, json, raw, intKey, name,
                timestamp, hash);
    } catch (JSONException e) {
        Log.e(TAG, "Couldn't parse obj.", e);
        return null;
    }
}

From source file:edu.mit.mobile.android.locast.data.MediaSync.java

/**
 * Scans the media database to see if the given item is currently there. If
 * it is, update the cast media to point to the local content: URI for it.
 *
 * @param context/*w  w  w.j  av a 2 s . c o  m*/
 * @param castMedia
 *            Local URI to the cast.
 * @param pubUri
 *            public URI to the media file.
 * @return local URI if it exists.
 * @throws SyncException
 */
public String checkForMediaEntry(Uri castMedia, Uri pubUri, String mimeType) throws SyncException {
    final ContentResolver cr = getContentResolver();

    String newLocUri = null;
    final File destfile = getFilePath(pubUri);

    if (mimeType == null) {
        throw new SyncException("missing MIME type");
    }

    String[] projection;
    String selection;
    Uri contentUri;

    if (mimeType.startsWith("image/")) {
        projection = new String[] { Images.Media._ID, Images.Media.DATA };
        selection = Images.Media.DATA + "=?";
        contentUri = Images.Media.EXTERNAL_CONTENT_URI;

    } else if (mimeType.startsWith("video/")) {
        projection = new String[] { Video.Media._ID, Video.Media.DATA };
        selection = Video.Media.DATA + "=?";
        contentUri = Video.Media.EXTERNAL_CONTENT_URI;

    } else {
        throw new SyncException("unknown MIME type: '" + mimeType + "'");
    }

    final String[] selectionArgs = { destfile.getAbsolutePath() };

    final Cursor mediaEntry = cr.query(contentUri, projection, selection, selectionArgs, null);
    try {
        if (mediaEntry.moveToFirst()) {
            newLocUri = ContentUris
                    .withAppendedId(contentUri, mediaEntry.getLong(mediaEntry.getColumnIndex(BaseColumns._ID)))
                    .toString();
        }
    } finally {
        mediaEntry.close();
    }

    if (newLocUri != null) {
        updateCastMediaLocalUri(castMedia, newLocUri, mimeType);
    } else {
        Log.e(TAG, "The media provider doesn't seem to know about " + destfile.getAbsolutePath()
                + " which is on the filesystem. Strange...");
    }
    return newLocUri;
}

From source file:com.google.android.apps.gutenberg.provider.SyncAdapter.java

private void syncCheckins(ContentProviderClient provider, String cookie) {
    Cursor cursor = null;
    try {/*from  w  ww  .j a  va 2  s.  com*/
        cursor = provider.query(Table.ATTENDEE.getBaseUri(),
                new String[] { Table.Attendee.ID, Table.Attendee.CHECKIN, Table.Attendee.EVENT_ID, },
                Table.Attendee.CHECKIN_MODIFIED, null, null);
        if (0 == cursor.getCount()) {
            Log.d(TAG, "No checkin to sync.");
            return;
        }
        int syncCount = 0;
        while (cursor.moveToNext()) {
            String attendeeId = cursor.getString(cursor.getColumnIndexOrThrow(Table.Attendee.ID));
            String eventId = cursor.getString(cursor.getColumnIndexOrThrow(Table.Attendee.EVENT_ID));
            long checkin = cursor.getLong(cursor.getColumnIndexOrThrow(Table.Attendee.CHECKIN));
            long serverCheckin = postCheckIn(attendeeId, eventId, checkin == 0, cookie);
            if (serverCheckin >= 0) {
                ContentValues values = new ContentValues();
                values.put(Table.Attendee.CHECKIN_MODIFIED, false);
                if (0 == serverCheckin) {
                    values.putNull(Table.Attendee.CHECKIN);
                } else {
                    values.put(Table.Attendee.CHECKIN, serverCheckin);
                }
                provider.update(Table.ATTENDEE.getItemUri(eventId, attendeeId), values, null, null);
                ++syncCount;
            }
        }
        Log.d(TAG, syncCount + " checkin(s) synced.");
    } catch (RemoteException e) {
        e.printStackTrace();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}