Introduction to Cursor in Android

Recommended by 5 users

Oct 7, 2014
Introduction to Cursor in Android
Add to Bookmark Email this Post 12.1K    1

The basic purpose of a cursor is to point to a single row of the result fetched by the query. We load the row pointed by the cursor object. By using cursor we can save lot of ram and memory.

The cursor is defined in the following code:

Public Cursor getString(String[] columnNames}{
Cursor cursor = database.query(table_name, columnName, null, null,
Return cursor;

Here, we pass the table name, column name only then we receive the cursor.

In order to get the columns and rows, we use the statement:

Int col = cursor.getColumnCount();
Int row =  cursor.getCount();
In order to get the column names, we use:
String[] columnNames = cursor.getColumnNames();

We then display the results through the statement:

Result += “No of Columns: “+col + “\n”;
Result += “No of Rows: “+row + “\n”;
Result += “Name of Columns” “+”\n”;

Any query in the SQLite database returns a cursor object and the cursor points to a single row. Lets take the following code:

Cursor cursor = database.query(TABLE_NAME, columnNames, null, null, null, null, null);
Return cursor;

When we define the cursor it will point to the first row. Using the cursor we define a ‘for row’ with the code:

for( cursor.moveTofirst(); !cursor.isAfterLast(); cursor</pre>
<pre style="text-align: justify;">moveToNext()) {</pre>
<pre style="text-align: justify;">Result += cursor.getString(0) + “\t\t”</pre>
<pre style="text-align: justify;">+ cursor.getString(1) + “\t\t”</pre>
<pre style="text-align: justify;">+ cursor.getString(2) + “\n”;</pre>
<pre style="text-align: justify;">}

When we call ‘Movetonext’ method it keeps going to the next row. If the Method is ‘afterlast’ it will go to NULL.

Be an Android Expert

In order to check the database, we go to the File Explore tab and click the data folder. The folder ‘com.edureka.sqliteexample’ will have the db file.  We then use the SQLite manager and connect the database by loading the db file stored in the desktop. This will in turn show the database table. It will have elements such as row ID, name and numbers.

Got a question for us? Mention them in the comments section and we will get back to you.

Related Posts:

Beginner’s Guide to Android Architecture

Android Development Course

Share on
1 Comment
  • This is a good introduction to Cursor. However, why do you say it returns only a single row? There can me many rows returned by the cursor, depending on your SQL query.

24 X 7 Customer Support X

  • us flag 1-800-275-9730 (Toll Free)
  • india flag +91 88808 62004