Example usage for android.content ContentResolver query

List of usage examples for android.content ContentResolver query

Introduction

In this page you can find the example usage for android.content ContentResolver query.

Prototype

public final @Nullable Cursor query(@RequiresPermission.Read @NonNull Uri uri, @Nullable String[] projection,
        @Nullable String selection, @Nullable String[] selectionArgs, @Nullable String sortOrder) 

Source Link

Document

Query the given URI, returning a Cursor over the result set.

Usage

From source file:com.facebook.Settings.java

/**
 * Acquire the current attribution id from the facebook app.
 * @return returns null if the facebook app is not present on the phone.
 *//*from  ww  w .jav a2 s .c o  m*/
public static String getAttributionId(ContentResolver contentResolver) {
    Cursor c = null;
    try {
        String[] projection = { ATTRIBUTION_ID_COLUMN_NAME };
        c = contentResolver.query(ATTRIBUTION_ID_CONTENT_URI, projection, null, null, null);
        if (c == null || !c.moveToFirst()) {
            return null;
        }
        String attributionId = c.getString(c.getColumnIndex(ATTRIBUTION_ID_COLUMN_NAME));
        return attributionId;
    } catch (Exception e) {
        Log.d(TAG, "Caught unexpected exception in getAttributionId(): " + e.toString());
        return null;
    } finally {
        if (c != null) {
            c.close();
        }
    }
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static void updateContactPhotoHd(Context context, ContentResolver resolver, long rawContactId,
        ContactPhoto photo, BatchOperation batchOperation) {
    final Cursor c = resolver.query(DataQuery.CONTENT_URI, DataQuery.PROJECTION,
            Data.RAW_CONTACT_ID + "=? AND " + Data.MIMETYPE + "=?",
            new String[] { String.valueOf(rawContactId), Photo.CONTENT_ITEM_TYPE }, null);
    final ContactOperations contactOp = ContactOperations.updateExistingContact(context, rawContactId, true,
            batchOperation);// w  w  w . ja  v  a2  s  . c  o m

    if ((c != null) && c.moveToFirst()) {
        final long id = c.getLong(DataQuery.COLUMN_ID);
        final Uri uri = ContentUris.withAppendedId(Data.CONTENT_URI, id);
        contactOp.updateAvatar(c.getString(DataQuery.COLUMN_DATA1), photo.getPhotoUrl(), uri);
        c.close();
    } else {
        Log.i(TAG, "creating row, count: " + c.getCount());
        contactOp.addAvatar(photo.getPhotoUrl());
    }
    Log.d(TAG, "updating check timestamp");
    final Uri uri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
    contactOp.updateSyncTimestamp1(System.currentTimeMillis(), uri);
}

From source file:com.example.android.sunshine.sync.SunshineSyncTask.java

private static void sendWearWeatherData(Context context) {
    final String LOG_TAG = "SunshineWearSync";

    /*//from   w w  w. ja v  a2  s .c o  m
    * The columns of data that we are interested in displaying within our DetailActivity's
    * weather display.
    */
    final String[] WEATHER_DETAIL_PROJECTION = { WeatherContract.WeatherEntry.COLUMN_DATE,
            WeatherContract.WeatherEntry.COLUMN_MAX_TEMP, WeatherContract.WeatherEntry.COLUMN_MIN_TEMP,
            WeatherContract.WeatherEntry.COLUMN_HUMIDITY, WeatherContract.WeatherEntry.COLUMN_PRESSURE,
            WeatherContract.WeatherEntry.COLUMN_WIND_SPEED, WeatherContract.WeatherEntry.COLUMN_DEGREES,
            WeatherContract.WeatherEntry.COLUMN_WEATHER_ID };

    /*
    * We store the indices of the values in the array of Strings above to more quickly be able
    * to access the data from our query. If the order of the Strings above changes, these
    * indices must be adjusted to match the order of the Strings.
    */
    final int INDEX_WEATHER_DATE = 0;
    final int INDEX_WEATHER_MAX_TEMP = 1;
    final int INDEX_WEATHER_MIN_TEMP = 2;
    final int INDEX_WEATHER_HUMIDITY = 3;
    final int INDEX_WEATHER_PRESSURE = 4;
    final int INDEX_WEATHER_WIND_SPEED = 5;
    final int INDEX_WEATHER_DEGREES = 6;
    final int INDEX_WEATHER_CONDITION_ID = 7;

    /*
     * Query weather data to send
     */
    ContentResolver sunshineContentResolver = context.getContentResolver();

    /*
     * A SELECTION in SQL declares which rows you'd like to return. In our case, we
     * want all weather data from today onwards that is stored in our weather table.
     * We created a handy method to do that in our WeatherEntry class.
     */
    String selection = WeatherContract.WeatherEntry.getSqlSelectForToday();

    // Get cursor
    Cursor myCursor = sunshineContentResolver.query(WeatherContract.WeatherEntry.CONTENT_URI,
            WEATHER_DETAIL_PROJECTION, selection, null, null);

    // Check if cursor contains data
    if (myCursor == null) {
        Log.d(LOG_TAG, "Error: No weather data found.");
        return;
    }

    // Format data
    myCursor.moveToFirst();
    Long highInCelsius = myCursor.getLong(INDEX_WEATHER_MAX_TEMP);
    Long lowInCelsius = myCursor.getLong(INDEX_WEATHER_MIN_TEMP);
    int weatherCondition = myCursor.getInt(INDEX_WEATHER_CONDITION_ID);

    Log.d(LOG_TAG, "Pulled cursor high temp " + highInCelsius + " low " + lowInCelsius);

    String highString = SunshineWeatherUtils.formatTemperature(context, highInCelsius);
    String lowString = SunshineWeatherUtils.formatTemperature(context, lowInCelsius);

    Log.d(LOG_TAG, "Weather condition is " + weatherCondition + ".");

    // Send data to Wear Data Layer
    GoogleApiClient mGoogleApiClient;
    mGoogleApiClient = new GoogleApiClient.Builder(context).addApi(Wearable.API).build();
    mGoogleApiClient.connect();

    double random = Math.floor(Math.random() * 10);
    Log.d(LOG_TAG, "Sending the number " + random + " to Android Wear.");
    PutDataMapRequest putDataMapReq = PutDataMapRequest.create(context.getString(R.string.PATH_WEAR_DATA));

    putDataMapReq.getDataMap().putString(context.getString(R.string.DATAMAP_TEMP_HIGH), highString);
    putDataMapReq.getDataMap().putString(context.getString(R.string.DATAMAP_TEMP_LOW), lowString);
    putDataMapReq.getDataMap().putInt(context.getString(R.string.DATAMAP_WEATHER_CONDITION), weatherCondition);
    // Sending current time so a change is detected every time for debug
    putDataMapReq.getDataMap().putLong(context.getString(R.string.DATAMAP_LAST_UPDATED),
            System.currentTimeMillis());

    putDataMapReq.setUrgent();
    PutDataRequest putDataReq = putDataMapReq.asPutDataRequest();

    // Send DataItem to Android Wear Buffer to be synced when possible
    PendingResult<DataApi.DataItemResult> pendingResult = Wearable.DataApi.putDataItem(mGoogleApiClient,
            putDataReq);

    pendingResult.setResultCallback(new ResultCallback<DataApi.DataItemResult>() {
        @Override
        public void onResult(@NonNull DataApi.DataItemResult dataItemResult) {
            Log.d(LOG_TAG, "Result is " + dataItemResult.getStatus() + ".");
        }
    });

    // cleanup
    myCursor.close();
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static long ensureGroupExists(Context context, Account account) {
    final ContentResolver resolver = context.getContentResolver();

    // Lookup the group
    long groupId = 0;
    final Cursor cursor = resolver.query(Groups.CONTENT_URI, new String[] { Groups._ID },
            Groups.ACCOUNT_NAME + "=? AND " + Groups.ACCOUNT_TYPE + "=? AND " + Groups.TITLE + "=?",
            new String[] { account.name, account.type, GROUP_NAME }, null);
    if (cursor != null) {
        try {/*from w  w  w. jav  a2 s . c o  m*/
            if (cursor.moveToFirst()) {
                groupId = cursor.getLong(0);
            }
        } finally {
            cursor.close();
        }
    }

    if (groupId == 0) {
        // Group doesn't exist yet, so create it
        final ContentValues contentValues = new ContentValues();
        contentValues.put(Groups.ACCOUNT_NAME, account.name);
        contentValues.put(Groups.ACCOUNT_TYPE, account.type);
        contentValues.put(Groups.TITLE, GROUP_NAME);
        //   contentValues.put(Groups.GROUP_IS_READ_ONLY, true);
        contentValues.put(Groups.GROUP_VISIBLE, true);

        final Uri newGroupUri = resolver.insert(Groups.CONTENT_URI, contentValues);
        groupId = ContentUris.parseId(newGroupUri);
    }
    return groupId;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

public static List<RawContact> getStarredContacts(Context context, Uri uri) {
    Log.i(TAG, "*** Looking for starred contacts");

    final ContentResolver resolver = context.getContentResolver();

    Set<Long> contactIds = new HashSet<Long>();
    Cursor c = resolver.query(RawContacts.CONTENT_URI, new String[] { RawContacts.CONTACT_ID },
            RawContacts.STARRED + "!=0", null, null);
    try {/* w  w w .  j av a  2 s .c o m*/
        while (c.moveToNext()) {
            contactIds.add(c.getLong(0));
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }
    Log.i(TAG, "*** ... found " + contactIds.size() + " starred");

    int i = 0;
    StringBuilder sb = new StringBuilder();
    for (Long s : contactIds) {
        sb.append(s);
        if (++i >= Math.min(contactIds.size(), 50)) {
            break;
        }
        sb.append(",");
    }

    List<RawContact> contacts = new ArrayList<RawContact>();
    c = resolver.query(uri, new String[] { Contacts._ID, RawContacts.SOURCE_ID },
            RawContacts.CONTACT_ID + " IN (" + sb.toString() + ")", null, null);
    try {
        while (c.moveToNext()) {
            final long rawContactId = c.getLong(0);
            final String serverContactId = c.getString(1);
            RawContact rawContact = RawContact.create(rawContactId, serverContactId);
            contacts.add(rawContact);
        }
    } catch (Exception e) {
        Log.i(TAG, "failing .. " + e.toString());
    } finally {
        if (c != null) {
            c.close();
        }
    }

    Log.i(TAG, "*** ... and " + contacts.size() + " of mine " + sb.toString());
    return contacts;
}

From source file:ro.weednet.contactssync.platform.ContactManager.java

private static long lookupContact(ContentResolver resolver, String name, String fb_id, boolean joinById,
        boolean syncAll) {
    Cursor c;//from   www .  j  ava2 s  .  c o m

    if (joinById) {
        c = resolver.query(ContactsContract.Data.CONTENT_URI, //table
                new String[] { ContactsContract.Data.RAW_CONTACT_ID }, //select (projection)
                ContactsContract.Data.MIMETYPE + "=? AND " + CommonDataKinds.Note.NOTE + " LIKE ?", //where
                new String[] { ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE, "%" + fb_id + "%" }, //params
                null //sort
        );
        try {
            if (c != null && c.moveToFirst()) {
                return c.getLong(0);
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
    }

    if (syncAll) {
        return -1;
    }

    c = resolver.query(Contacts.CONTENT_URI, //table
            new String[] { Contacts._ID }, //select (projection)
            Contacts.DISPLAY_NAME + "=?", //where
            new String[] { name }, //params
            null //sort
    );
    try {
        if (c != null && c.getCount() > 0) {
            return 0;
        }
    } finally {
        if (c != null) {
            c.close();
        }
    }

    return -1;
}

From source file:Main.java

/**
 * Return text content of clipboard as individual lines 
 * @param ctx/*from   w ww  .  java 2  s  . c om*/
 * @return
 */
@SuppressLint("NewApi")
private static ArrayList<String> getTextLines(Context ctx) {

    String EOL = "\\r?\\n|\\r";

    if (checkForText(ctx)) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            ClipData.Item item = clipboard.getPrimaryClip().getItemAt(0);

            // Gets the clipboard as text.
            CharSequence cs = item.getText();
            if (cs == null) { // item might be an URI
                Uri pasteUri = item.getUri();
                if (pasteUri != null) { // FIXME untested
                    try {
                        Log.d("ClipboardUtils", "Clipboard contains an uri");
                        ContentResolver cr = ctx.getContentResolver();
                        String uriMimeType = cr.getType(pasteUri);
                        //               pasteData = resolveUri(pasteUri);
                        // If the return value is not null, the Uri is a content Uri
                        if (uriMimeType != null) {

                            // Does the content provider offer a MIME type that the current application can use?
                            if (uriMimeType.equals(ClipDescription.MIMETYPE_TEXT_PLAIN)) {

                                // Get the data from the content provider.
                                Cursor pasteCursor = cr.query(pasteUri, null, null, null, null);

                                // If the Cursor contains data, move to the first record
                                if (pasteCursor != null) {
                                    if (pasteCursor.moveToFirst()) {
                                        String pasteData = pasteCursor.getString(0);
                                        return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
                                    }
                                    // close the Cursor
                                    pasteCursor.close();
                                }
                            }
                        }
                    } catch (Exception e) { // FIXME given that the above is unteted, cath all here
                        Log.e("ClipboardUtils", "Resolving URI failed " + e);
                        e.printStackTrace();
                        return null;
                    }
                }
            } else {
                Log.d("ClipboardUtils", "Clipboard contains text");
                String pasteData = cs.toString();
                return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
            }
        } else {
            // Gets the clipboard as text.
            @SuppressWarnings("deprecation")
            CharSequence cs = oldClipboard.getText();
            if (cs != null) {
                String pasteData = cs.toString();
                if (pasteData != null) { // should always be the case
                    return new ArrayList<String>(Arrays.asList(pasteData.split(EOL)));
                }
            }
        }
        Log.e("ClipboardUtils", "Clipboard contains an invalid data type");
    }
    return null;
}

From source file:com.android.providers.downloads.DownloadInfo.java

/**
 * Query and return status of requested download.
 *///w w  w .  j ava  2s  .c  om
public static int queryDownloadStatus(ContentResolver resolver, long id) {
    final Cursor cursor = resolver.query(
            ContentUris.withAppendedId(Downloads.Impl.ALL_DOWNLOADS_CONTENT_URI, id),
            new String[] { Downloads.Impl.COLUMN_STATUS }, null, null, null);
    try {
        if (cursor.moveToFirst()) {
            return cursor.getInt(0);
        } else {
            // TODO: increase strictness of value returned for unknown
            // downloads; this is safe default for now.
            return Downloads.Impl.STATUS_PENDING;
        }
    } finally {
        cursor.close();
    }
}

From source file:com.visva.voicerecorder.utils.Utils.java

public static ArrayList<String> getContactUriTypeFromContactId(ContentResolver resolver, String contactId) {
    ArrayList<String> phones = new ArrayList<String>();

    Cursor cursor = resolver.query(CommonDataKinds.Phone.CONTENT_URI, null,
            CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { contactId }, null);

    while (cursor.moveToNext()) {
        phones.add(cursor.getString(cursor.getColumnIndex(CommonDataKinds.Phone.NUMBER)));
    }//from   www  .  j  a v  a  2s .  c  om
    if (cursor != null) {
        cursor.close();
        cursor = null;
    }
    return (phones);
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

/**
 * Get display name from the uri//from  w  w  w.j  a v  a  2s  .c om
 *
 * @param context
 * @param uri
 * @return
 */
@TargetApi(Build.VERSION_CODES.KITKAT)
public static String getDisplayName(Context context, Uri uri) {

    String name = null;

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        ContentResolver resolver = context.getContentResolver();
        Cursor nameCursor = resolver.query(uri, null, null, null, null);
        try {
            if (nameCursor.getCount() > 0) {
                int displayNameIndex = nameCursor
                        .getColumnIndex(DocumentsContract.Document.COLUMN_DISPLAY_NAME);
                if (displayNameIndex >= 0 && nameCursor.moveToFirst()) {
                    name = nameCursor.getString(displayNameIndex);
                }
            }
        } finally {
            nameCursor.close();
        }
    }

    return name;
}