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:android.example.com.dictionaryproviderexample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the TextView which will be populated with the Dictionary ContentProvider data.
    ListView dictListView = (ListView) findViewById(R.id.dictionary_list_view);

    // Get the ContentResolver which will send a message to the ContentProvider.
    ContentResolver resolver = getContentResolver();

    // Get a Cursor containing all of the rows in the Words table.
    Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, null, null, null, null);

    // Set the Adapter to fill the standard two_line_list_item layout with data from the Cursor.
    SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.two_line_list_item, cursor,
            COLUMNS_TO_BE_BOUND, LAYOUT_ITEMS_TO_FILL, 0);

    // Attach the adapter to the ListView.
    dictListView.setAdapter(adapter);//  ww w  .j a v a  2  s .  co m
}

From source file:com.alchemiasoft.book.service.SuggestionService.java

@Override
protected void onHandleIntent(Intent intent) {
    Log.d(TAG_LOG, "Starting a new book suggestion...");
    final ContentResolver cr = getContentResolver();
    final Cursor c = cr.query(BookDB.Book.CONTENT_URI, null, SELECTION, SELECT_NOT_OWNED, null);
    Book book = null;//from   w  ww .  j av  a  2 s  .  c  o m
    try {
        if (c.moveToNext()) {
            book = Book.oneFrom(c);
        }
    } finally {
        c.close();
    }
    // Showing a notification if a not owned book is found
    if (book != null) {
        Log.d(TAG_LOG, "Found book that can be suggested: " + book);
        final String content = getString(R.string.content_book_suggestion, book.getTitle(), book.getAuthor());
        final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setSmallIcon(R.drawable.ic_launcher).setAutoCancel(true)
                .setContentTitle(getString(R.string.title_book_suggestion)).setContentText(content);
        builder.setStyle(new NotificationCompat.BigTextStyle().bigText(content));
        builder.setContentIntent(PendingIntent.getActivity(this, 0, HomeActivity.createFor(this, book),
                PendingIntent.FLAG_UPDATE_CURRENT));

        // ONLY 4 WEARABLE(s)
        final NotificationCompat.WearableExtender wearableExtender = new NotificationCompat.WearableExtender();
        // SECOND PAGE WITH BOOK DESCRIPTION
        wearableExtender
                .addPage(new NotificationCompat.Builder(this).setContentTitle(getString(R.string.description))
                        .setStyle(new NotificationCompat.BigTextStyle().bigText(book.getDescrition())).build());
        wearableExtender.setBackground(BitmapFactory.decodeResource(getResources(), R.drawable.background));
        // ACTION TO PURCHASE A BOOK FROM A WEARABLE
        final PendingIntent purchaseIntent = PendingIntent.getService(this, 0, BookActionService.IntentBuilder
                .buy(this, book).notificationId(ID_SUGGESTION).wearableInput().build(),
                PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_buy,
                getString(R.string.action_buy), purchaseIntent).build());
        // ACTION TO ADD NOTES VIA VOICE REPLY
        final RemoteInput input = BookActionService.RemoteInputBuilder.create(this)
                .options(R.array.note_options).build();
        final PendingIntent notesIntent = PendingIntent
                .getService(
                        this, 0, BookActionService.IntentBuilder.addNote(this, book)
                                .notificationId(ID_SUGGESTION).wearableInput().build(),
                        PendingIntent.FLAG_UPDATE_CURRENT);
        wearableExtender.addAction(new NotificationCompat.Action.Builder(R.drawable.ic_action_notes,
                getString(R.string.action_notes), notesIntent).addRemoteInput(input).build());
        // Finally extending the notification
        builder.extend(wearableExtender);

        // Sending the notification
        NotificationManagerCompat.from(this).notify(ID_SUGGESTION, builder.build());
    }
    // Completing the Wakeful Intent
    SuggestionReceiver.completeWakefulIntent(intent);
}

From source file:com.vrj.udacity.dictionaryproviderexample.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Get the ListView which will be populated with the Dictionary ContentProvider data.
    ListView listView = (ListView) findViewById(R.id.dictionary_list_view);

    // Get the ContentResolver which will send a message to the ContentProvider
    ContentResolver resolver = getContentResolver();

    // Get a Cursor containing all of the rows in the Words table
    Cursor cursor = resolver.query(UserDictionary.Words.CONTENT_URI, null, null, null, null);

    SimpleCursorAdapter sca = new SimpleCursorAdapter(
            // Context
            this,
            // TextView type that will populate this listview
            android.R.layout.two_line_list_item,
            // The Cursor
            cursor,//from w  w w.  j a  v  a2  s . c o  m
            // String[] of the headers from the table that we want to display
            HEADERS,
            // int[] of the TextViews that we want to display the table values in, in order
            VIEWS,
            // Flags
            0);

    // Set the CursorAdapter for this ListView
    listView.setAdapter(sca);

}

From source file:au.com.cybersearch2.classyfy.ClassyfyLogic.java

/**
 * Perform content provider query for fast text search, Must be executed on background thread. 
 * @param searchQuery Query string//from   w w w  .  ja  va2  s. co  m
 * @return
 */
public List<ListItem> doSearchQuery(String searchQuery) {
    // Perform the search, passing in the search query as an argument to the Cursor Loader
    SuggestionCursorParameters params = new SuggestionCursorParameters(searchQuery,
            ClassyFySearchEngine.LEX_CONTENT_URI, ClassyFyProvider.SEARCH_RESULTS_LIMIT);

    ContentResolver contentResolver = context.getContentResolver();
    Cursor cursor = contentResolver.query(params.getUri(), params.getProjection(), params.getSelection(),
            params.getSelectionArgs(), params.getSortOrder());
    List<ListItem> fieldList = new ArrayList<ListItem>();
    int nameColumnId = cursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_1);
    int valueColumnId = cursor.getColumnIndexOrThrow(SearchManager.SUGGEST_COLUMN_TEXT_2);
    // Id column name set in android.support.v4.widget.CursorAdaptor
    int idColumnId = cursor.getColumnIndexOrThrow("_id");
    if (cursor.getCount() > 0) {
        cursor.moveToPosition(-1);
        while (cursor.moveToNext()) {
            String name = cursor.getString(nameColumnId);
            String value = cursor.getString(valueColumnId);
            long id = cursor.getLong(idColumnId);
            fieldList.add(new ListItem(name, value, id));
        }
    }
    cursor.close();
    return fieldList;
}

From source file:cm.aptoide.com.facebook.android.Facebook.java

/**
 * Get Attribution ID for app install conversion tracking.
 * @param contentResolver/* w w  w.  ja v a  2s  . co  m*/
 * @return Attribution ID that will be used for conversion tracking. It will be null only if
 *         the user has not installed or logged in to the Facebook app.
 */
public static String getAttributionId(ContentResolver contentResolver) {
    String[] projection = { ATTRIBUTION_ID_COLUMN_NAME };
    Cursor 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;
}

From source file:com.tcl.lzhang1.mymusic.MusicUtil.java

/**
 * get the music info//from   www  .j  a v  a2s  .c  o m
 * 
 * @param musicFile
 * @return
 */
public static SongModel getMusicInfo(File musicFile) {
    SongModel model = new SongModel();
    // retrun null if music file is null or is or directory
    if (musicFile == null || !musicFile.isFile()) {
        return null;
    }

    byte[] buf = new byte[128];
    try {
        Log.d(LOG_TAG, "process music file{" + musicFile.getAbsolutePath() + "}");
        // tag_v1
        RandomAccessFile music = new RandomAccessFile(musicFile, "r");

        music.seek(music.length() - 128);
        music.read(buf);// read tag to buffer
        // tag_v2
        byte[] header = new byte[10];
        music.seek(0);
        music.read(header, 0, 10);
        // if ("ID3".equalsIgnoreCase(new String(header, 0, 3))) {
        // int ID3V2_frame_size = (int) (header[6] & 0x7F) * 0x200000
        // | (int) (header[7] & 0x7F) * 0x400
        // | (int) (header[8] & 0x7F) * 0x80
        // | (int) (header[9] & 0x7F);
        // byte[] FrameHeader = new byte[4];
        // music.seek(ID3V2_frame_size + 10);
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, ID3V2_frame_size, musicFile);
        // } else {
        // byte[] FrameHeader = new byte[4];
        // music.read(FrameHeader, 0, 4);
        // model = getTimeInfo(FrameHeader, 0, musicFile);
        // }

        music.close();// close file
        // check length
        // if (buf.length != 128) {
        // throw new
        // ErrorMusicLength(String.format("error music info length, length is:%i",
        // buf.length));
        // }
        //
        // if (!"TAG".equalsIgnoreCase(new String(buf, 0, 3))) {
        // throw new UnknownTagException("unknown tag exception");
        // }
        String songName = null;
        // try {
        // songName = new String(buf, 3, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // e.printStackTrace();
        // songName = new String(buf, 3, 30).trim();
        // }
        String singerName = "";
        // try {
        // singerName = new String(buf, 33, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // singerName = new String(buf, 33, 30).trim();
        // }
        String ablum = "";
        // try {
        // ablum = new String(buf, 63, 30, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // // TODO: handle exception
        // ablum = new String(buf, 63, 30).trim();
        // }
        String year = "";
        // try {
        // year = new String(buf, 93, 4, "gbk").trim();
        // } catch (UnsupportedEncodingException e) {
        // year = new String(buf, 93, 4).trim();
        // // TODO: handle exception
        // }

        String reamrk = "";
        ContentResolver contentResolver = sContext.getContentResolver();
        Cursor cursor = contentResolver.query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, "_data=?",
                new String[] { musicFile.getAbsolutePath() }, null);
        cursor.moveToFirst();
        if (cursor != null && cursor.getCount() != 0) {
            try {
                if (TextUtils.isEmpty(songName)) {
                    songName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE));
                    singerName = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST));
                    ablum = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.ALBUM));
                    year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
                }

                long secs = cursor.getLong(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION));
                model.setTime(secs);
                secs /= 1000;
                model.setHours((int) secs / 3600);
                model.setMinutes(((int) secs % 3600) / 60);
                model.setSeconds(((int) secs % 3600) % 60);
                cursor.close();
            } catch (CursorIndexOutOfBoundsException e) {
                // TODO: handle exception
                if (null != cursor) {
                    cursor.close();
                    cursor = null;
                }
                Log.d(LOG_TAG, "CursorIndexOutOfBoundsException:" + e.getMessage());
                try {
                    songName = new String(buf, 3, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e0) {
                    // TODO: handle exception
                    e.printStackTrace();
                    songName = new String(buf, 3, 30).trim();
                }
                try {
                    singerName = new String(buf, 33, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e1) {
                    // TODO: handle exception
                    singerName = new String(buf, 33, 30).trim();
                }
                try {
                    ablum = new String(buf, 63, 30, "gbk").trim();
                } catch (UnsupportedEncodingException e2) {
                    // TODO: handle exception
                    ablum = new String(buf, 63, 30).trim();
                }
                try {
                    year = new String(buf, 93, 4, "gbk").trim();
                } catch (UnsupportedEncodingException e3) {
                    year = new String(buf, 93, 4).trim();
                    // TODO: handle exception
                }

                try {
                    reamrk = new String(buf, 97, 28, "gbk").trim();
                } catch (UnsupportedEncodingException e4) {
                    // TODO: handle exception
                    reamrk = new String(buf, 97, 28).trim();
                }

            }
        }

        //

        // get the time len

        model.setSongName(songName);
        model.setSingerName(singerName);
        model.setAblumName(ablum);
        model.setFile(musicFile.getAbsolutePath());
        model.setRemark("");
        Log.d(LOG_TAG, String.format("scaned music file[%s],album name[%s],song name[%s],singer name[%s]",
                model.getFile(), model.getAblumName(), model.getSingerName(), model.getSingerName()));

        mSongs.add(model);

        return model;
    } catch (IOException e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    return model;
}

From source file:com.bilibili.boxing.model.task.impl.AlbumTask.java

private void buildDefaultAlbum(ContentResolver cr) {
    Cursor cursor = null;//  ww  w.j a  va 2 s .  c  o m
    try {
        cursor = cr.query(Media.EXTERNAL_CONTENT_URI, new String[] { Media.BUCKET_ID }, null, null, null);
        if (cursor != null) {
            mDefaultAlbum.mCount = cursor.getCount();
        }
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

From source file:com.manning.androidhacks.hack023.dao.TodoDAO.java

public int getTodoStatus(ContentResolver contentResolver, Long id) {
    Cursor c = contentResolver.query(TodoContentProvider.CONTENT_URI, null,
            TodoContentProvider.COLUMN_ID + "=" + id, null, null);

    int status = 0;

    try {//from  w ww  . j  a va2 s . c  om
        if (c.moveToNext()) {
            status = c.getInt(c.getColumnIndexOrThrow(TodoContentProvider.COLUMN_STATUS_FLAG));

        } else {
            throw new RuntimeException("Tried to delete a non existent todo");
        }
    } finally {
        c.close();
    }

    return status;
}

From source file:com.pursuer.reader.easyrss.network.SubscriptionDataSyncer.java

private void syncSubscriptionIcons() throws DataSyncerException {
    final Context context = dataMgr.getContext();
    if (!NetworkUtils.checkSyncingNetworkStatus(context, networkConfig)) {
        return;//  w ww .ja v a2 s .c om
    }
    final ContentResolver resolver = context.getContentResolver();
    final Cursor cur = resolver.query(Subscription.CONTENT_URI,
            new String[] { Subscription._UID, Subscription._ICON, Subscription._URL }, null, null, null);
    for (cur.moveToFirst(); !cur.isAfterLast(); cur.moveToNext()) {
        final String uid = cur.getString(0);
        final byte[] data = cur.getBlob(1);
        final String subUrl = cur.getString(2);
        if (subUrl != null && data == null) {
            final SubscriptionIconUrl fetchUrl = new SubscriptionIconUrl(isHttpsConnection, subUrl);
            try {
                final byte[] iconData = httpGetQueryByte(fetchUrl);
                final Bitmap icon = BitmapFactory.decodeByteArray(iconData, 0, iconData.length);
                final int size = icon.getWidth() * icon.getHeight() * 2;
                final ByteArrayOutputStream output = new ByteArrayOutputStream(size);
                icon.compress(Bitmap.CompressFormat.PNG, 100, output);
                output.flush();
                output.close();
                dataMgr.updateSubscriptionIconByUid(uid, output.toByteArray());
            } catch (final IOException exception) {
                cur.close();
                throw new DataSyncerException(exception);
            }
        }
    }
    cur.close();
}

From source file:com.github.shareme.gwschips.library.BaseRecipientAdapter.java

protected static void fetchPhoto(final RecipientEntry entry, final Uri photoThumbnailUri,
        final ContentResolver mContentResolver) {
    byte[] photoBytes = mPhotoCacheMap.get(photoThumbnailUri);
    if (photoBytes != null) {
        entry.setPhotoBytes(photoBytes);
        return;/*from  w w  w. ja v a2  s. c o  m*/
    }
    final Cursor photoCursor = mContentResolver.query(photoThumbnailUri, PhotoQuery.PROJECTION, null, null,
            null);
    if (photoCursor != null) {
        try {
            if (photoCursor.moveToFirst()) {
                photoBytes = photoCursor.getBlob(PhotoQuery.PHOTO);
                entry.setPhotoBytes(photoBytes);
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
            }
        } finally {
            photoCursor.close();
        }
    } else {
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;
        try {
            inputStream = mContentResolver.openInputStream(photoThumbnailUri);
            final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);

            if (bitmap != null) {
                outputStream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                photoBytes = outputStream.toByteArray();

                entry.setPhotoBytes(photoBytes);
                mPhotoCacheMap.put(photoThumbnailUri, photoBytes);
            }
        } catch (final FileNotFoundException e) {
            Log.w(TAG, "Error opening InputStream for photo", e);
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error closing photo input stream", e);
            }
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                Log.e(TAG, "Error closing photo output stream", e);
            }
        }
    }
}