Search Wikipedia

Search results

Showing posts with label records. Show all posts
Showing posts with label records. Show all posts

May 1, 2014

Accessing Data with Android Cursors (Part 2)

Retrieving Data

Retrieving data from SQLite databases in Android is done using Cursors. The Android SQLite query method returns a Cursor object containing the results of the query. To use Cursors android.database.Cursor must be imported.

About Cursor

Cursors store query result records in rows and grant many methods to access and iterate through the records. Cursors should be closed when no longer used, and will be deactivated with a call to Cursor.deactivate() when the application pauses or exists. On resume the Cursor.requery() statement is executed to re-enable the Cursor with fresh data. These functions can be managed by the parent Activity by calling startManagingCursor(). 

package com.kais.TestingData;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

public class TestingData extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        SQLiteDatabase db;
        
        db = openOrCreateDatabase(
         "TestingData.db"
         , SQLiteDatabase.CREATE_IF_NECESSARY
         , null
         );
        db.setVersion(1);
        db.setLocale(Locale.getDefault());
        db.setLockingEnabled(true);
        
        Cursor cur = db.query("tbl_countries", 
         null, null, null, null, null, null);
        
        cur.close();
    }
}

Open the database as before. The query performed will return all records from the table tbl_countries. Next we'll look at how to access the data returned.

}