Wednesday, February 4, 2015

Android beginner tutorial Part 69 Queries and Cursors

In this tutorial we will add our Content Provider to the Manifest xml and learn a bit about queries and cursors.

To make a Content Provider visible and usable by the system and your own application, we need to add it to the AndroidManifest.xml file of our project.

Add a new node provider to the application node, set values for two of its attributes - android:name and android:authorities. The name attribute points to the custom ContentProvider class, and the authorities value is the URI address of the provider:

        <provider 
android:name="com.kircode.codeforfood_test.myContentProvider"
android:authorities="com.kircode.codeforfood_test.contactprovider">
</provider>

To send SQL queries to the content provider from your application, use the ContentResolver object that is obtainable using getContentResolver() method.

For example, this way we can send a query that selects all names and phones of the people in our database.

String[] columns = new String[] {myDbHelper.NAME, myDbHelper.PHONE};
ContentResolver resolver = getContentResolver();
Cursor cursor = resolver.query(CONTENT_URI, columns, null, null, null);

The query() method, for instance, has 5 parameters. Those are the URI address of the provider, the projection (list of columns to return, if null - everything is returned), selection (what would normally be written after "WHERE" in an SQL command), selectionArgs (extra functionality for selection parameter) and sortOrder (what would normally be written after "ORDER BY").

The Cursor object thats returned to us is a helpful tool for navigating through the results of the query. It has a set of useful methods like moveToFirst(), moveToLast(), moveToNext(), moveToPrevious(), moveToPosition(), getToPosition() and more.

Since the Cursor lines up all the results in some sort of a row and moves back and forth displaying one at a time, there are a few methods that let us know where exactly the cursor is currently located. These methods are isFirst(), isLast(), isBeforeFirst() and isAfterLast().

The insert(), update() and delete() methods are also all called from the ContentResolver object, but they dont result any Cusors. They are even simpler commands that basically insert, update and delete rows in a table.

Thats all for today.

Thanks for reading!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.