android.content.ContentResolver#query ( )源码实例Demo

下面列出了android.content.ContentResolver#query ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: TurboLauncher   文件: LauncherBackupHelper.java
private boolean launcherIsReady() {
    ContentResolver cr = mContext.getContentResolver();
    Cursor cursor = cr.query(Favorites.CONTENT_URI, FAVORITE_PROJECTION, null, null, null);
    if (cursor == null) {
        // launcher data has been wiped, do nothing
        return false;
    }
    cursor.close();

    if (!initializeIconCache()) {
        // launcher services are unavailable, try again later
        dataChanged();
        return false;
    }

    return true;
}
 
public static SearchWithRecipeRecord get(long id) {
    Cursor c = null;
    
    ContentResolver resolver = Mechanoid.getContentResolver();
    
    try {
        c = resolver.query(SearchWithRecipe.CONTENT_URI.buildUpon()
		.appendPath(String.valueOf(id)).build(), PROJECTION, null, null, null);
        
        if(!c.moveToFirst()) {
            return null;
        }
        
        return fromCursor(c);
    } finally {
        Closeables.closeSilently(c);
    }
}
 
源代码3 项目: ContactsList   文件: ContactsManager.java
/**
 * @param context
 * @return List
 */
@NonNull
public static ArrayList<ShareContactsBean> getPhoneContacts(Context context) {
    ArrayList<ShareContactsBean> result = new ArrayList<>();
    ContentResolver resolver = context.getContentResolver();
    Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
            new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME}, null, null, null);
    if (phoneCursor != null) {
        while (phoneCursor.moveToNext()) {
            String phoneNumber = phoneCursor.getString(0).replace(" ", "").replace("-", "");
            String contactName = phoneCursor.getString(1);
            result.add(new ShareContactsBean(contactName, phoneNumber));
        }
        phoneCursor.close();
    }

    Collections.sort(result, new Comparator<ShareContactsBean>() {
        @Override
        public int compare(ShareContactsBean l, ShareContactsBean r) {
            return l.compareTo(r);
        }
    });
    return result;
}
 
源代码4 项目: Android-Next   文件: BitmapUtils.java
public static int getExifOrientation(ContentResolver cr, Uri contentUri) {
    int returnValue = 0;
    String uriString = contentUri.toString();

    if (ContentResolver.SCHEME_CONTENT.equals(contentUri.getScheme())) {
        // can post image
        String[] proj = {MediaStore.Images.Media.ORIENTATION};
        Cursor cursor = cr.query(contentUri, proj, null, null, null);

        if (null != cursor) {
            if (cursor.moveToFirst()) {
                returnValue = cursor.getInt(cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.ORIENTATION));
            }
            cursor.close();
        }
    } else if (ContentResolver.SCHEME_FILE.equals(contentUri.getScheme())) {
        returnValue = getExifOrientation(contentUri.getPath());
    } else if (uriString.startsWith("/")) {
        returnValue = getExifOrientation(contentUri.getPath());
    }
    return returnValue;
}
 
源代码5 项目: coursera-android   文件: MediaPlaybackService.java
private boolean makeAutoShuffleList() {
    ContentResolver res = getContentResolver();
    Cursor c = null;
    try {
        c = res.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
                new String[] {MediaStore.Audio.Media._ID}, MediaStore.Audio.Media.IS_MUSIC + "=1",
                null, null);
        if (c == null || c.getCount() == 0) {
            return false;
        }
        int len = c.getCount();
        long [] list = new long[len];
        for (int i = 0; i < len; i++) {
            c.moveToNext();
            list[i] = c.getLong(0);
        }
        mAutoShuffleList = list;
        return true;
    } catch (RuntimeException ex) {
    } finally {
        if (c != null) {
            c.close();
        }
    }
    return false;
}
 
源代码6 项目: FireFiles   文件: DocumentsContractCompat.java
private static long queryForLong(Context context, Uri self, String column,
        long defaultValue) {
    final ContentResolver resolver = context.getContentResolver();

    Cursor c = null;
    try {
        c = resolver.query(self, new String[] { column }, null, null, null);
        if (c.moveToFirst() && !c.isNull(0)) {
            return c.getLong(0);
        } else {
            return defaultValue;
        }
    } catch (Exception e) {
        Log.w(TAG, "Failed query: " + e);
        return defaultValue;
    } finally {
        closeQuietly(c);
    }
}
 
源代码7 项目: NetEasyNews   文件: MediaStore.java
static void cancelThumbnailRequest(ContentResolver cr, long origId, Uri baseUri, long groupId) {
  Uri cancelUri = baseUri.buildUpon().appendQueryParameter("cancel", "1").appendQueryParameter("orig_id", String.valueOf(origId)).appendQueryParameter("group_id", String.valueOf(groupId)).build();
  Cursor c = null;
  try {
    c = cr.query(cancelUri, PROJECTION, null, null, null);
  } finally {
    if (c != null)
      c.close();
  }
}
 
源代码8 项目: Muzesto   文件: MusicPlayer.java
public static void addToPlaylist(final Context context, final long[] ids, final long playlistid) {
    final int size = ids.length;
    final ContentResolver resolver = context.getContentResolver();
    final String[] projection = new String[]{
            "max(" + "play_order" + ")",
    };
    final Uri uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlistid);
    Cursor cursor = null;
    int base = 0;

    try {
        cursor = resolver.query(uri, projection, null, null, null);

        if (cursor != null && cursor.moveToFirst()) {
            base = cursor.getInt(0) + 1;
        }
    } finally {
        if (cursor != null) {
            cursor.close();
            cursor = null;
        }
    }

    int numinserted = 0;
    for (int offSet = 0; offSet < size; offSet += 1000) {
        makeInsertItems(ids, offSet, 1000, base);
        numinserted += resolver.bulkInsert(uri, mContentValuesCache);
    }
    final String message = context.getResources().getQuantityString(
            R.plurals.NNNtrackstoplaylist, numinserted, numinserted);
    Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
}
 
源代码9 项目: Camera-Roll-Android-App   文件: StorageUtil.java
private static Uri getContentUriForImageFromMediaStore(Context context, String path) {
    ContentResolver resolver = context.getContentResolver();
    //Uri photoUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    // to handle hidden images
    Uri photoUri = MediaStore.Files.getContentUri("external");
    Cursor cursor = resolver.query(photoUri,
            new String[]{BaseColumns._ID},
            MediaStore.MediaColumns.DATA + " = ?",
            new String[]{path}, null);
    if (cursor == null) {
        return Uri.parse(path);
    }
    cursor.moveToFirst();
    if (cursor.isAfterLast()) {
        cursor.close();
        // insert system media db
        ContentValues values = new ContentValues();
        values.put(MediaStore.Images.Media.DATA, path);
        values.put(MediaStore.Images.Media.MIME_TYPE, MediaType.getMimeType(path));
        return context.getContentResolver().insert(photoUri, values);
    } else {
        long id = cursor.getLong(cursor.getColumnIndex(BaseColumns._ID));
        Uri uri = ContentUris.withAppendedId(photoUri, id);
        cursor.close();
        return uri;
    }
}
 
源代码10 项目: BaldPhone   文件: Contact.java
public static Contact fromLookupKey(@NonNull String lookupKey, @NonNull ContentResolver contentResolver) throws ContactNotFoundException {
    final Cursor contactsCursor =
            contentResolver.query(
                    ContactsContract.Contacts.CONTENT_URI,
                    PROJECTION,
                    ContactsContract.Contacts.LOOKUP_KEY + " = ?",
                    new String[]{lookupKey},
                    null);
    if (!contactsCursor.moveToFirst()) throw new ContactNotFoundException();
    return readContact(contactsCursor, contentResolver);
}
 
源代码11 项目: callerid-for-android   文件: NewContactsHelper.java
public boolean haveContactWithPhoneNumber(String phoneNumber) {
	final Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber));
	final ContentResolver contentResolver = application.getContentResolver();
	final Cursor cursor = contentResolver.query(uri,HAVE_CONTACT_PROJECTION,null,null,null);
	try{
		return cursor.moveToNext();
	}finally{
		cursor.close();
	}
}
 
源代码12 项目: TurboLauncher   文件: LauncherModel.java
/** Loads the workspace screens db into a map of Rank -> ScreenId */
private static TreeMap<Integer, Long> loadWorkspaceScreensDb(Context context) {
	final ContentResolver contentResolver = context.getContentResolver();
	final Uri screensUri = LauncherSettings.WorkspaceScreens.CONTENT_URI;
	final Cursor sc = contentResolver.query(screensUri, null, null, null,
			null);
	TreeMap<Integer, Long> orderedScreens = new TreeMap<Integer, Long>();

	try {
		final int idIndex = sc
				.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens._ID);
		final int rankIndex = sc
				.getColumnIndexOrThrow(LauncherSettings.WorkspaceScreens.SCREEN_RANK);
		while (sc.moveToNext()) {
			try {
				long screenId = sc.getLong(idIndex);
				int rank = sc.getInt(rankIndex);
				orderedScreens.put(rank, screenId);
			} catch (Exception e) {

			}
		}
	} finally {
		sc.close();
	}

	ArrayList<String> orderedScreensPairs = new ArrayList<String>();
	for (Integer i : orderedScreens.keySet()) {
		orderedScreensPairs.add("{ " + i + ": " + orderedScreens.get(i)
				+ " }");
	}

	return orderedScreens;
}
 
源代码13 项目: Telegram-FOSS   文件: ContactsController.java
public void deleteConnectionServiceContact() {
    if (!hasContactsPermission())
        return;
    try {
        ContentResolver resolver = ApplicationLoader.applicationContext.getContentResolver();

        Cursor cursor = resolver.query(ContactsContract.Groups.CONTENT_URI, new String[]{ContactsContract.Groups._ID},
                ContactsContract.Groups.TITLE + "=? AND " + ContactsContract.Groups.ACCOUNT_TYPE + "=? AND " + ContactsContract.Groups.ACCOUNT_NAME + "=?",
                new String[]{"TelegramConnectionService", systemAccount.type, systemAccount.name}, null);
        int groupID;
        if (cursor != null && cursor.moveToFirst()) {
            groupID = cursor.getInt(0);
            cursor.close();
        } else {
            if (cursor != null)
                cursor.close();
            return;
        }
        cursor = resolver.query(ContactsContract.Data.CONTENT_URI, new String[]{ContactsContract.Data.RAW_CONTACT_ID},
                ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID + "=?",
                new String[]{ContactsContract.CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE, groupID + ""}, null);
        int contactID;
        if (cursor != null && cursor.moveToFirst()) {
            contactID = cursor.getInt(0);
            cursor.close();
        } else {
            if (cursor != null)
                cursor.close();
            return;
        }
        resolver.delete(ContactsContract.RawContacts.CONTENT_URI, ContactsContract.RawContacts._ID + "=?", new String[]{contactID + ""});
        //resolver.delete(ContactsContract.Groups.CONTENT_URI, ContactsContract.Groups._ID+"=?", new String[]{groupID+""});
    } catch (Exception x) {
        FileLog.e(x);
    }
}
 
源代码14 项目: Camera2   文件: PlaceholderManager.java
/**
 * Create a new session instance from the given URI by querying the media
 * store.
 * <p>
 * TODO: Make sure this works with types other than images when needed.
 */
private Placeholder createSessionFromUri(Uri uri)
{
    ContentResolver resolver = mContext.getContentResolver();

    Cursor cursor = resolver.query(uri,
            new String[]{
                    MediaStore.Images.Media.DATE_TAKEN, MediaStore.Images.Media.DISPLAY_NAME,
            }, null, null, null);
    // The count could be 0 if the original media item was deleted before
    // the session was created.
    if (cursor == null || cursor.getCount() == 0)
    {
        return null;
    }
    int dateIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATE_TAKEN);
    int nameIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);

    cursor.moveToFirst();
    long date = cursor.getLong(dateIndex);
    String name = cursor.getString(nameIndex);

    if (name.toLowerCase().endsWith(Storage.JPEG_POSTFIX))
    {
        name = name.substring(0, name.length() - Storage.JPEG_POSTFIX.length());
    }

    return new Placeholder(name, uri, date);
}
 
源代码15 项目: Trebuchet   文件: AppWidgetsRestoredReceiver.java
/**
 * Updates the app widgets whose id has changed during the restore process.
 */
static void restoreAppWidgetIds(Context context, int[] oldWidgetIds, int[] newWidgetIds) {
    final ContentResolver cr = context.getContentResolver();
    final List<Integer> idsToRemove = new ArrayList<Integer>();
    final AppWidgetManager widgets = AppWidgetManager.getInstance(context);

    for (int i = 0; i < oldWidgetIds.length; i++) {
        Log.i(TAG, "Widget state restore id " + oldWidgetIds[i] + " => " + newWidgetIds[i]);

        final AppWidgetProviderInfo provider = widgets.getAppWidgetInfo(newWidgetIds[i]);
        final int state;
        if (LauncherModel.isValidProvider(provider)) {
            // This will ensure that we show 'Click to setup' UI if required.
            state = LauncherAppWidgetInfo.FLAG_UI_NOT_READY;
        } else {
            state = LauncherAppWidgetInfo.FLAG_PROVIDER_NOT_READY;
        }

        ContentValues values = new ContentValues();
        values.put(LauncherSettings.Favorites.APPWIDGET_ID, newWidgetIds[i]);
        values.put(LauncherSettings.Favorites.RESTORED, state);

        String[] widgetIdParams = new String[] { Integer.toString(oldWidgetIds[i]) };

        int result = cr.update(Favorites.CONTENT_URI, values,
                "appWidgetId=? and (restored & 1) = 1", widgetIdParams);
        if (result == 0) {
            Cursor cursor = cr.query(Favorites.CONTENT_URI,
                    new String[] {Favorites.APPWIDGET_ID},
                    "appWidgetId=?", widgetIdParams, null);
            try {
                if (!cursor.moveToFirst()) {
                    // The widget no long exists.
                    idsToRemove.add(newWidgetIds[i]);
                }
            } finally {
                cursor.close();
            }
        }
    }
    // Unregister the widget IDs which are not present on the workspace. This could happen
    // when a widget place holder is removed from workspace, before this method is called.
    if (!idsToRemove.isEmpty()) {
        final AppWidgetHost appWidgetHost =
                new AppWidgetHost(context, Launcher.APPWIDGET_HOST_ID);
        new AsyncTask<Void, Void, Void>() {
            public Void doInBackground(Void ... args) {
                for (Integer id : idsToRemove) {
                    appWidgetHost.deleteAppWidgetId(id);
                    Log.e(TAG, "Widget no longer present, appWidgetId=" + id);
                }
                return null;
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void) null);
    }

    LauncherAppState app = LauncherAppState.getInstanceNoCreate();
    if (app != null) {
        app.reloadWorkspace();
    }
}
 
源代码16 项目: zom-android-matrix   文件: AccountAdapter.java
private void runBindTask( final Activity context, final List<AccountInfo> accountInfoList ) {
    final Resources resources = context.getResources();
    final ContentResolver resolver = context.getContentResolver();

    // if called multiple times
    if (mBindTask != null)
        mBindTask.cancel(false);
    //


    mBindTask = new AsyncTask<Void, Void, List<AccountSetting>>() {

        @Override
        protected List<AccountSetting> doInBackground(Void... params) {
            List<AccountSetting> accountSettingList = new ArrayList<AccountSetting>();
            for( AccountInfo ai : accountInfoList ) {
                accountSettingList.add( getAccountSettings(ai) );
            }
            return accountSettingList;
        }

        private AccountSetting getAccountSettings(AccountInfo ai) {
            AccountSetting as = new AccountSetting();


            Cursor pCursor = resolver.query(Imps.ProviderSettings.CONTENT_URI,new String[] {Imps.ProviderSettings.NAME, Imps.ProviderSettings.VALUE},Imps.ProviderSettings.PROVIDER + "=?",new String[] { Long.toString(ai.providerId)},null);

            if (pCursor != null)
            {
                Imps.ProviderSettings.QueryMap settings =
                        new Imps.ProviderSettings.QueryMap(pCursor, resolver, ai.providerId, false , null);

                as.connectionStatus = ai.dbConnectionStatus;
                as.activeUserName = ai.activeUserName;
                as.domain = settings.getDomain();
                as.host = settings.getServer();
                as.port = settings.getPort();

                /**
                IImConnection conn = mApp.getConnection(ai.providerId,settings.get);
                if (conn == null) {
                    as.connectionStatus = ImConnection.DISCONNECTED;
                } else {
                    try {
                        as.connectionStatus = conn.getState();
                    } catch (RemoteException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }*/

                settings.close();
            }
            return as;
        }

        @Override
        protected void onPostExecute(List<AccountSetting> result) {
            // store
            mBindTask = null;
            // swap
            AccountAdapter.super.swapCursor(mStashCursor);
            if (mListener != null)
                mListener.onPopulate();
        }
    };
    mBindTask.execute();
}
 
private static long getCalendar(Context context) {

        ContentResolver contentResolver = context.getContentResolver();

        // Find the calendar if we've got one
        Uri calenderUri = CalendarContract.Calendars.CONTENT_URI.buildUpon().appendQueryParameter(CalendarContract.CALLER_IS_SYNCADAPTER, "true")
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME)
                .appendQueryParameter(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE).build();


        Cursor cursor = contentResolver.query(calenderUri, new String[]{BaseColumns._ID},
                CalendarContract.Calendars.ACCOUNT_NAME + " = ? AND " + CalendarContract.Calendars.ACCOUNT_TYPE + " = ?",
                new String[]{ACCOUNT_NAME, ACCOUNT_TYPE}, null);

        try {
            if (cursor != null && cursor.moveToNext()) {
                return cursor.getLong(0);
            } else {
                ArrayList<ContentProviderOperation> operationList = new ArrayList<>();

                ContentProviderOperation.Builder builder = ContentProviderOperation
                        .newInsert(calenderUri);
                builder.withValue(CalendarContract.Calendars.ACCOUNT_NAME, ACCOUNT_NAME);
                builder.withValue(CalendarContract.Calendars.ACCOUNT_TYPE, ACCOUNT_TYPE);
                builder.withValue(CalendarContract.Calendars.NAME, CALENDAR_COLUMN_NAME);
                builder.withValue(CalendarContract.Calendars.CALENDAR_DISPLAY_NAME,
                        context.getString(R.string.appName));
                builder.withValue(CalendarContract.Calendars.CALENDAR_COLOR, context.getResources().getColor(R.color.colorPrimary));
                builder.withValue(CalendarContract.Calendars.CALENDAR_ACCESS_LEVEL, CalendarContract.Calendars.CAL_ACCESS_READ);
                builder.withValue(CalendarContract.Calendars.SYNC_EVENTS, 0);
                builder.withValue(CalendarContract.Calendars.VISIBLE, 1);

                operationList.add(builder.build());
                try {
                    contentResolver.applyBatch(CalendarContract.AUTHORITY, operationList);
                } catch (Exception e) {
                    e.printStackTrace();
                    return -1;
                }
                return getCalendar(context);
            }
        } finally {
            if (cursor != null && !cursor.isClosed())
                cursor.close();
        }
    }
 
源代码18 项目: jpHolo   文件: ContentFilesystem.java
protected Cursor openCursorForURL(LocalFilesystemURL url) {
       ContentResolver contentResolver = this.cordova.getActivity().getContentResolver();
       Cursor cursor = contentResolver.query(url.URL, null, null, null, null);
       return cursor;
}
 
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    // Ensure that this call is the result of a successful PICK_CONTACT_REQUEST request
    if (resultCode == Activity.RESULT_OK
            && requestCode == PICK_CONTACT_REQUEST) {

        // These details are covered in the lesson on ContentProviders
        ContentResolver cr = getContentResolver();
        Cursor cursor = cr.query(data.getData(), null, null, null, null);

        if (null != cursor && cursor.moveToFirst()) {
            String id = cursor
                    .getString(cursor.getColumnIndex(CONTACTS_ID));
            String where = DATA_CONTACT_ID + " = ? AND " + DATA_MIMETYPE
                    + " = ?";
            String[] whereParameters = new String[]{id,
                    STRUCTURED_POSTAL_CONTENT_ITEM_TYPE};
            Cursor addrCur = cr.query(DATA_CONTENT_URI, null, where,
                    whereParameters, null);

            if (null != addrCur && addrCur.moveToFirst()) {
                String formattedAddress = addrCur
                        .getString(addrCur
                                .getColumnIndex(STRUCTURED_POSTAL_FORMATTED_ADDRESS));

                if (null != formattedAddress) {

                    // Process text for network transmission
                    formattedAddress = formattedAddress.replace(' ', '+');

                    // Create Intent object for starting Google Maps application
                    Intent geoIntent = new Intent(
                            android.content.Intent.ACTION_VIEW,
                            Uri.parse("geo:0,0?q=" + formattedAddress));

                    // Use the Intent to start Google Maps application using Activity.startActivity()
                    startActivity(geoIntent);
                }
            }
            if (null != addrCur)
                addrCur.close();
        }
        if (null != cursor)
            cursor.close();
    }
}
 
源代码20 项目: PreferencesProvider   文件: PreferencesSelection.java
/**
 * Query the given content resolver using this selection.
 *
 * @param contentResolver The content resolver to query.
 * @param projection      A list of which columns to return. Passing null will return all columns, which is inefficient.
 * @return A {@code PreferencesCursor} object, which is positioned before the first entry, or null.
 */
public PreferencesCursor query(ContentResolver contentResolver, String[] projection) {
    Cursor cursor = contentResolver.query(uri(), projection, sel(), args(), order());
    if (cursor == null) return null;
    return new PreferencesCursor(cursor);
}