Android Development (51 Blogs) Become a Certified Professional

Introduction to Cursor in Android

Last updated on May 22,2019 19.1K Views


myMock Interview Service for Real Tech Jobs


myMock Interview Service for Real Tech Jobs

  • Mock interview in latest tech domains i.e JAVA, AI, DEVOPS,etc
  • Get interviewed by leading tech experts
  • Real time assessment report and video recording

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 + “
Result += “No of Rows: “+row + “
Result += “Name of Columns” “+”

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) + “		”</pre>
<pre style="text-align: justify;">+ cursor.getString(1) + “		”</pre>
<pre style="text-align: justify;">+ cursor.getString(2) + “
<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.

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


Browse Categories

Subscribe to our Newsletter, and get personalized recommendations.