KIO
Kreative Ideen online
Database cursor

Database cursor

A cursor lets you read from and write tot the database.Youe specify what data you want access to, and the cursor brings back the relevant records from the databse. You can then avagate through the recors spuplied by the cursor.

You create a crsor using a database query. A database query lets you specify which records you want access to from the database. As an example, you can say you want ato access all the records from a DRINK table, or just one particular record. These records are then returned in the cursor.

//The query() method returns a Cursor object
Cursor cursor = db.query(...);

An example – return all the records fram a table:

Return the values in the _id, NAME, and DESCRIPTION columns for every record in the DRINK table

/*We want to return the values in these columns
/*_id|NAME|DESCRIPTION
/*Set the last parameters to null
Cursor cursor = db.query("DRINK", new String[] {"_id", "NAME", "DESCRIPTION"},null,null,null,null,null);

To return all the records from a particualr table, you pass the name of the table as the query() methods first parameter, and aString array of the coumn names as the second.You set all of the other paramtetes to null, as you dont need them for this type of query.

Cursor cursor = db.query("TABLE_NAME", new String[]{"COLUMN1","COLUMN2"},null,null ,null,null,null);

Retrun records in a particualar order

If you want to display data in your app in a particular order, youo use the query to sort the data by a particular column.This can be useful if, for example, you want to display drink names in alphabetical order.

By default, the data in the table appears in _id order, as this was the order in which data was entered.

Return selected records

You can filter your data by declaring conditions the dat must meet.

As an example:

Cursor cursor = db.query("DRINK", new STRING[]{"_id","NAME","DESCRIPTION"}, "NAME = ?", new String[] {"Latte"},null,null,null);

The third and fourth parameters in the query describe the conditins the data must meet.

The third parameter specifies the column in the conditin.In the above example we want to return records where the value of the NAME column is “Latte”, so we use “NAME = ?”.
We want the value in the NAME column to be equal to some value, and the ? symbol is a placeholder for this value.

The fourth parameter is an array of Strings that specifies what the value of the conditin should be.In the above example we want to update records where the value of the NAME comlumn is “Latte” , so we use:

new String[]{"Latte"};

The valu of the condition must be anarray of Strings, even if the column youure applayin te condition to contains some other type of data.

An example:

Cursor cursor = db.query("DRINK", new String[]{2_id", "NAME","DESCRPTION"},"_id = ?",new String[]{Integer.toString(1)},null,null,null);

To read a record from a cursor, you first need to navigae to it

Once you have a cursor, yu need to read values from it…

Whenever you need to retrieve avlues from a particular record in acursor, you first need to navigate to that record.

Navigate cursors

Ther are four manin methods you use to navigate through the records in a cursor:

  • moveToFirst()
  • moveToLast()
  • moveToPrevious()
  • moveToNext()

moveToFirst()
To go to the first record in a curso, you use its moveToFirst() method.This method returns a value of true if it finds a record, and false if the cursor hasnt retruned any records.

if(cursor.moveToFirst()){

}

moveToLast()
To go to the last record, you use the moveToLast() method. Just like the moveToFirst() mehthod, it returns a value of true if it finds a record and false if it doesnt:

if(cursor.moveToLast()){

}

To move through the records in the cursor, you use the moveToPrevious() and moveToNext() methods.
The moveToPrevious() method moves you to the preivous record in the cursor.

if(cursor.moveToPrevius()){

}

The moveToNext() method works in a similar way to the moveToPrevious() method, except that it moves you to the next record in the cursor instead:

if(cursor.moveToNext()){

}

Get cursor values

You retrieve values from a cursors current record using the cursors get*() methods:

  • getString()
  • getInt()

The exact method you use depends on the type of value you want to retrieve. To get a aString, youd use the getString() method. Each of the methods takes a single parameter. The index of the column whose vale ou want to retrive, starting at 0.

An example(full code for context):


package eu.kio.starbuzz;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;

public class DrinkActivity extends Activity {

    public static final String EXTRA_DRINKID = "drinkId";

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

        //Get the drink from the intent
        int drinkId = (Integer)getIntent().getExtras().get(EXTRA_DRINKID);

        //Drink drink = Drink.drinks[drinkId];

        //Create a cursor
        SQLiteOpenHelper starbuzzDatabaseHelper = new StarbuzzDatabaseHelper(this);
        try {
            SQLiteDatabase db = starbuzzDatabaseHelper.getReadableDatabase();
            Cursor cursor = db.query("DRINK", new String[]{"NAME","DESCRIPTION","IMAGE_RESOURCE_ID"},"_id = ? ", new String[] {Integer.toString(drinkId)},null,null,null);
            if(cursor.moveToFirst()){

                //Get the drink details from the cursor
                String nameText = cursor.getString(0);
                String descriptionText = cursor.getString(1);
                int photoId = cursor.getInt(2);

                //Populate the drink name
                TextView name = (TextView)findViewById(R.id.description);
                /*name.setText(drink.getName());*/
                name.setText(nameText);

                //Populate the drink description
                TextView description = (TextView)findViewById(R.id.description);
                /*description.setText(drink.getDescription());*/
                description.setText(descriptionText);

                //Populate the drink image
                ImageView photo = (ImageView)findViewById(R.id.photo);
                /*photo.setImageResource(drink.getImageResourceId());
                photo.setContentDescription(drink.getName());*/
                photo.setImageResource(photoId);
                photo.setContentDescription(nameText);

                cursor.close();
                db.close();
            }
        } catch (SQLiteException e) {
            Toast toast = Toast.makeText(this, "Database unavailable", Toast.LENGTH_SHORT);
            toast.show();
        }
    }
}

To find out more of queery() method:

https://developer.android.com/reference/android/databse/sqlite/SQLiteDatabse.html

Leave a Reply

Your email address will not be published. Required fields are marked *