SlideShare une entreprise Scribd logo
1  sur  12
Android Application Development Training Tutorial




                      For more info visit

                   http://www.zybotech.in




        A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Accessing Data With Android Cursors
What is SQLite
SQLite is an open-source server-less database engine. SQLite supports transacations and has no configuration
required. SQLite adds powerful data storage to mobile and embedded apps without a large footprint.

Creating and connecting to a database
First import android.databse.sqlite.SQLiteDatabase into your application. Then use the
openOrCreateDatabase() method to create or connect to a database. Create a new project in Eclipse called
TestingData and select the API version of your choice. Use the package name higherpass.TestingData with an
activity TestingData and click finish.

package higherpass.TestingData;

import android.app.Activity;
import android.os.Bundle;
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
                 );
      }
}



Add the android.database.sqlite.SQLiteDatabase to the standard imports from the new project. After the
standard layout setup initialize a SQLiteDatabase variable to hold the database instance. Next use the
openOrCreateDatabase() method to open the database. The openOrCreateDatabase() method expects the
database file first, followed by the permissions to open the database with, and an optional cursor factory
builder.

Where does Android store SQLite databases?

Android stores SQLite databases in /data/data/[application package name]/databases.

sqlite3 from adb shell
bash-3.1$ /usr/local/android-sdk-linux/tools/adb devices
List of devices attached
emulator-5554   device
bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell

                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
# ls /data/data/higherpass.TestingData/databases
TestingData.db
# sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> .tables
android_metadata tbl_countries      tbl_states



The Google Android SDK comes with a utility adb. The adb tool can be used to browse and modify the
filesystem of attached emulators and physical devices. This example is a bit ahead of where we are as we
haven't created the databases yet.

Setting database properties

There are a few database properties that should be set after connecting to the database. Use the setVersion(),
setLocale(), and setLockingEnabled() methods to set these properties. These will be demonstrated in the
creating tables example.

Creating Tables
Tables are created by executing statements on the database. The queries should be executed with the execSQL()
statement.

package higherpass.TestingData;

import java.util.Locale;

import android.app.Activity;
import android.os.Bundle;
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);

          final String CREATE_TABLE_COUNTRIES =
                 "CREATE TABLE tbl_countries ("
                 + "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                 + "country_name TEXT);";
          final String CREATE_TABLE_STATES =
                 "CREATE TABLE tbl_states ("
                 + "id INTEGER PRIMARY KEY AUTOINCREMENT,"

                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
+ "state_name TEXT,"
                 + "country_id INTEGER NOT NULL CONSTRAINT "
                 + "contry_id REFERENCES tbl_contries(id) "
                 + "ON DELETE CASCADE);";
          db.execSQL(CREATE_TABLE_COUNTRIES);
          db.execSQL(CREATE_TABLE_STATES);
          final String CREATE_TRIGGER_STATES =
                 "CREATE TRIGGER fk_insert_state BEFORE "
                 + "INSERT on tbl_states"
                 + "FOR EACH ROW "
                 + "BEGIN "
                 + "SELECT RAISE(ROLLBACK, 'insert on table "
                 + ""tbl_states" voilates foreign key constraint "
                 + ""fk_insert_state"') WHERE (SELECT id FROM "
                 + "tbl_countries WHERE id = NEW.country_id) IS NULL; "
                 + "END;";
          db.execSQL(CREATE_TRIGGER_STATES);
     }
}



As before open the database with openOrCreateDatabase(). Now configure the database connection with
setVersion to set the database version. The setLocale method sets the default locale for the database and
setLockingEnabled enables locking on the database. Next we setup final String variables to hold the SQLite
table creation statements and execute them with execSQL.

Additionally we manually have to create triggers to handle the foreign key relationships between the table. In a
production application there would also need to be foreign key triggers to handle row updates and deletes. The
foreign key triggers are executed with execSQL just like the table creation.

Inserting records
Android comes with a series of classes that simplify database usage. Use a ContentValues instance to create a
series of table field to data matchings that will be passed into an insert() method. Android has created similar
methods for updating and deleting records.

          ContentValues values = new ContentValues();
          values.put("country_name", "US");
          long countryId = db.insert("tbl_countries", null, values);
          ContentValues stateValues = new ContentValues();
          stateValues.put("state_name", "Texas");
          stateValues.put("country_id", Long.toString(countryId));
          try {
              db.insertOrThrow("tbl_states", null, stateValues);
          } catch (Exception e) {
              //catch code
          }



Append this code to the previous example. First create a ContentValues object to store the data to insert and use
the put method to load the data. Then use the insert() method to perform the insert query into SQLite. The
insert() function expects three parameters, the table name, null, and the ContentValues pairs. Also a long is
returned by the insert() function. This long will hold the primary key of the inserted row.



                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Next we create a new ContentValues pair for the state and perform a second insert using the insertOrThrow()
method. Using insertOrThrow() will throw an exception if the insert isn't successful and must be surrounded by
a try/catch block. You'll notice that currently the application dies with an unhandled exception because the
tables we're trying to create already exist. Go back into the adb shell and attach to the SQLite database for the
application and drop the tables.

sqlite> drop table tbl_countries;
sqlite> drop table tbl_states;


Updating data
Updating records is handled with the update() method. The update() function supports WHERE syntax similar
to other SQL engines. The update() method expects the table name, a ContentValues instance similar to insert
with the fields to update. Also allowed are optional WHERE syntax, add a String containing the WHERE
statement as parameter 3. Use the ? to designate an argument replacement in the WHERE clause with the
replacements passed as an array in parameter 4 to update.

       ContentValues updateCountry = new ContentValues();
       updateCountry.put("country_name", "United States");
       db.update("tbl_countries", updateCountry, "id=?", new String[]
{Long.toString(countryId)});
First remove the table create statements from the code. We don't need to keep creating and dropping tables.
Now create a new ContentValues instance, updateCountry, to hold the data to be updated. Then use the
update() method to update the table. The where clause in parameter 3 uses replacement of the ? with the values
stored in parameter 4. If multiple ? existed in the where statement they would be replaced in order by the values
of the array.

From the adb shell attach to the database and execute select * FROM tbl_countries; inside sqlite3.

bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell
# sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db
SQLite version 3.5.9
Enter ".help" for instructions
sqlite> select * FROM tbl_countries;
1|United States



Deleting data
Once data is no longer needed it can be removed from the database with the delete() method. The delete()
method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE
clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array.

        db.delete("tbl_states", "id=?", new String[] {Long.toString(countryId)});



Simply call the delete() method to remove records from the SQLite database. The delete method expects, the
table name, and optionally a where clause and where clause argument replacement arrays as parameters. The
where clause and argument replacement array work just as with update where ? is replaced by the values in the
array.



                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
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 Cursors

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 higherpass.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.

Iterating through records

The Cursor class provides a couple of simple methods to allow iterating through Cursor data easily. Use
moveToFirst() to position the Cursor pointer at the first record then use the moveToNext() function to iterate
                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
through the records. The isAfterLast() method performs a check to see if the cursor is pointed after the last
record. When looping through records break the loop when this becomes false.

First add the following attribute to the TextView element in the main layout. The main layout is the xml file
located at res/layouts/main.xml. We need to give this TextView element an ID that we can reference to update
the view.

    android:id="@+id/hello"



Java code to iterate through entries in a cursor:

package higherpass.TestingData;

import java.util.Locale;

import     android.app.Activity;
import     android.os.Bundle;
import     android.widget.TextView;
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);
        TextView view = (TextView) findViewById(R.id.hello);

            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.moveToFirst();
            while (cur.isAfterLast() == false) {
                view.append("n" + cur.getString(1));
                cur.moveToNext();
            }
            cur.close();
       }
}



This code simply creates a cursor querying all the records of the table tbl_countries. The moveToFirst() method
is used to position the cursor pointer at the beginning of the data set. Then loop through the records in the
cursor. The method isAfterLast() returns a boolean if the pointer is past the last record in the cursor. Use the
moveToNext() method to traverse through the records in the cursor.

                             A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Retrieving a specific record

The cursor also allows direct access to specific records.

           Cursor cur = db.query("tbl_countries",
                         null, null, null, null, null, null);
           cur.moveToPosition(0);
           view.append("n" + cur.getString(1));
           cur.close();



Transactions
SQLite also supports transactions when you need to perform a series of queries that either all complete or all
fail. When a SQLite transaction fails an exception will be thrown. The transaction methods are all part of the
database object. Start a transaction by calling the beginTransaction() method. Perform the queries and then call
the setTransactionSuccessful() when you wish to commit the transaction. Once the transaction is complete call
the endTransaction() function.

           db.beginTransaction();
           Cursor cur = null;
           try {
                 cur = db.query("tbl_countries",
                         null, null, null, null, null, null);
                 cur.moveToPosition(0);
                 ContentValues values = new ContentValues();
                 values.put("state_name", "Georgia");
                 values.put("country_id", cur.getString(0));
                 long stateId = db.insert("tbl_states", null, values);
                 db.setTransactionSuccessful();
                 view.append("n" + Long.toString(stateId));
           } catch (Exception e) {
                 Log.e("Error in transaction", e.toString());
           } finally {
                 db.endTransaction();
                 cur.close();
           }



Start off with a call to beginTransaction() to tell SQLite to perform the queries in transaction mode. Initiate a
try/catch block to handle exceptions thrown by a transaction failure. Perform the queries and then call
setTransactionSuccessful() to tell SQLite that our transaction is complete. If an error isn't thrown then
endTransaction() can be called to commit the transaction. Finally close the cursor when we're finished with it.

Built in android databases
The Android Operating-System provides several built-in databases to store and manage core phone application
data. Before external applications may access some of these data sources access must be granted in the
AndroidManifest.xml file in the root of the project. Some of the data applications can access are the
bookmarks, media player data, call log, and contact data. Contact data not covered due to changes in the API
between 1.x and 2.0 version of Android. See the Android Working With Contacts Tutorial. Android provides
built in variables to make working with the internal SQLite databases easy.


                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Access permissions

Before a program accesses any of the internal Android databases the application must be granted access. This
access is granted in the AndroidManifest.xml file. Before the application is installed from the market the user
will be prompted to allow the program to access this data.

        <uses-permission
android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" />
        <uses-permission
android:name="com.android.broswer.permission.WRITE_HISTORY_BOOKMARKS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />

These are some sample uses-permission statements to grant access to internal Android databases. These are
normally placed below the uses-sdk statement in the AndroidManifest.xml file. The first 2 grant read and write
access to the browser history and bookmarks. The third grants read access to the contacts. We'll need to grant
READ access to the bookmarks and contacts for the rest of the code samples to work.

Managed Query

Managed queries delegate control of the Cursor to the parent activity automatically. This is handy as it allows
the activity to control when to destroy and recreate the Cursor as the application changes state.

package higherpass.TestingData;

import   android.app.Activity;
import   android.os.Bundle;
import   android.provider.Browser;
import   android.widget.TextView;
import   android.database.Cursor;

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);
        TextView view = (TextView) findViewById(R.id.hello);
        Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
                       null, null, null, null
                       );
        mCur.moveToFirst();
        int index = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
        while (mCur.isAfterLast() == false) {
               view.append("n" + mCur.getString(index));
               mCur.moveToNext();
        }

     }
}



The managed query functions very similar to the query function we used before. When accessing Android built
in databases you should reference them by calling the associated SDK variable containing the correct database
URI. In this case the browser bookmarks are being accessed by pointing the managedQuery() statement at
android.provider.Browser.BOOKMARKS_URI. We left the rest of the parameters null to pull all results from
the table. Then we iterate through the cursor records. Each time through the loop we append the title of the
                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
bookmark to the TextView element. If you know the name of a column, but not it's index in the results use the
getColumnIndex() method to get the correct index. To get the value of a field use the getString() method
passing the index of the field to return.

Bookmarks
The first Android database we're going to explore is the browser bookmarks. When accessing the internal
Android databases use the managedQuery() method. Android includes some helper variables in
Browser.BookmarkColumns to designate column names. They are Browser.BookmarkColumns.TITLE,
BOOKMARK, FAVICON, CREATED, URL, DATE, VISITS. These contain the table column names for the
bookmarks SQLite table.

package higherpass.TestingData;

import   android.app.Activity;
import   android.os.Bundle;
import   android.provider.Browser;
import   android.widget.TextView;
import   android.database.Cursor;

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);
        TextView view = (TextView) findViewById(R.id.hello);
        String[] projection = new String[] {
               Browser.BookmarkColumns.TITLE
               , Browser.BookmarkColumns.URL
        };
        Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI,
               projection, null, null, null
               );
        mCur.moveToFirst();
        int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE);
        int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL);
        while (mCur.isAfterLast() == false) {
               view.append("n" + mCur.getString(titleIdx));
               view.append("n" + mCur.getString(urlIdx));
               mCur.moveToNext();
        }

     }
}



This code works as before, with the addition of limiting return columns with a projection. The projection is a
string array that holds a list of the columns to return. In this example we limited the columns to the bookmark
title (Browser.BookmarkColumns.TITLE) and URL (Browser.BookmarkColumns.URL). The projection array
is then passed into managedQuery as the second parameter.




                           A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
Media Player
The Android Media-player also uses SQLite to store the media information. Use this database to find media
stored on the device. Available fields are DATE_ADDED, DATE_MODIFIED, DISPLAY_NAME,
MIME_TYPE, SIZE, and TITLE.

package higherpass.TestingData;

import   android.app.Activity;
import   android.os.Bundle;
import   android.provider.MediaStore;
import   android.provider.MediaStore.Audio.Media;
import   android.widget.TextView;
import   android.database.Cursor;

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);
        TextView view = (TextView) findViewById(R.id.hello);
        String[] projection = new String[] {
               MediaStore.MediaColumns.DISPLAY_NAME
               , MediaStore.MediaColumns.DATE_ADDED
               , MediaStore.MediaColumns.MIME_TYPE
        };
        Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
               projection, null, null, null
               );
        mCur.moveToFirst();

          while (mCur.isAfterLast() == false) {
              for (int i=0; i<mCur.getColumnCount(); i++) {
                  view.append("n" + mCur.getString(i));
              }
              mCur.moveToNext();
          }

     }
}



The only differences here is that we use getColumnCount() to determine the number of columns in the returned
records and loop through displaying each column.

Call Log
If granted permission Android applications can access the call log. The call log is accessed like other
datastores.

package higherpass.TestingData;

import   android.app.Activity;
import   android.os.Bundle;
import   android.provider.CallLog;
import   android.provider.CallLog.Calls;

                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
import android.widget.TextView;
import android.database.Cursor;

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);
        TextView view = (TextView) findViewById(R.id.hello);
        String[] projection = new String[] {
                       Calls.DATE
                       , Calls.NUMBER
                       , Calls.DURATION
        };
       Cursor mCur = managedQuery(CallLog.Calls.CONTENT_URI,
                       projection, Calls.DURATION +"<?",
                        new String[] {"60"},
                        Calls.DURATION + " ASC");
        mCur.moveToFirst();

          while (mCur.isAfterLast() == false) {
                for (int i=0; i<mCur.getColumnCount(); i++) {
                    view.append("n" + mCur.getString(i));
                }
                mCur.moveToNext();
          }

     }
}

This final example introduces the rest of the managedQuery() parameters. After the projection we pass a
WHERE clause in the same way they were crafted in the update and delete sections earlier. After the where
clause comes the array of replacement arguments. Finally we pass in an order by clause to tell SQLite how to
sort the results. This query only retrieves records for phone calls lasting less than 60 seconds and sorts them by
duration ascending.




                            A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi

Contenu connexe

Tendances (20)

Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Applets in java
Applets in javaApplets in java
Applets in java
 
Introduction to fragments in android
Introduction to fragments in androidIntroduction to fragments in android
Introduction to fragments in android
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Synchronization in distributed computing
Synchronization in distributed computingSynchronization in distributed computing
Synchronization in distributed computing
 
Applet life cycle
Applet life cycleApplet life cycle
Applet life cycle
 
Javascript
JavascriptJavascript
Javascript
 
Calender in asp.net
Calender in asp.netCalender in asp.net
Calender in asp.net
 
Cocomo model
Cocomo modelCocomo model
Cocomo model
 
SOFTWARE PARADIGM
SOFTWARE PARADIGMSOFTWARE PARADIGM
SOFTWARE PARADIGM
 
COCOMO MODEL 1 And 2
COCOMO MODEL 1 And 2COCOMO MODEL 1 And 2
COCOMO MODEL 1 And 2
 
Fragment
Fragment Fragment
Fragment
 
CS6611 Mobile Application Development Lab Manual-2018-19
CS6611 Mobile Application Development Lab Manual-2018-19CS6611 Mobile Application Development Lab Manual-2018-19
CS6611 Mobile Application Development Lab Manual-2018-19
 
New Elements & Features in CSS3
New Elements & Features in CSS3New Elements & Features in CSS3
New Elements & Features in CSS3
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
XML
XMLXML
XML
 
Web Technology Lab File
Web Technology Lab FileWeb Technology Lab File
Web Technology Lab File
 
Responsive design: techniques and tricks to prepare your websites for the mul...
Responsive design: techniques and tricks to prepare your websites for the mul...Responsive design: techniques and tricks to prepare your websites for the mul...
Responsive design: techniques and tricks to prepare your websites for the mul...
 
Use case Diagram and Sequence Diagram
Use case Diagram and Sequence DiagramUse case Diagram and Sequence Diagram
Use case Diagram and Sequence Diagram
 
Xml presentation
Xml presentationXml presentation
Xml presentation
 

Similaire à Accessing data with android cursors

Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...TAISEEREISA
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfConint29
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on AndroidEric Maxwell
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptxvishal choudhary
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml datakendyhuu
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsphanleson
 

Similaire à Accessing data with android cursors (20)

Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Sql lite android
Sql lite androidSql lite android
Sql lite android
 
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
Chapter 3.pptx Oracle SQL or local Android database setup SQL, SQL-Lite, codi...
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
Python database access
Python database accessPython database access
Python database access
 
I am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdfI am looking for some assistance with SQLite database. I have tried se.pdf
I am looking for some assistance with SQLite database. I have tried se.pdf
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on Android
 
Create an android app for database creation using.pptx
Create an android app for database creation using.pptxCreate an android app for database creation using.pptx
Create an android app for database creation using.pptx
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
 
Session06 handling xml data
Session06  handling xml dataSession06  handling xml data
Session06 handling xml data
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Plus de info_zybotech

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activitiesinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid drawinfo_zybotech
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorialinfo_zybotech
 

Plus de info_zybotech (7)

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
 
Java and xml
Java and xmlJava and xml
Java and xml
 
How to create ui using droid draw
How to create ui using droid drawHow to create ui using droid draw
How to create ui using droid draw
 
Applications
ApplicationsApplications
Applications
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
 

Dernier

Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxRosabel UA
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxJanEmmanBrigoli
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...Postal Advocate Inc.
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxruthvilladarez
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Celine George
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSJoshuaGantuangco2
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsRommel Regala
 

Dernier (20)

Presentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptxPresentation Activity 2. Unit 3 transv.pptx
Presentation Activity 2. Unit 3 transv.pptx
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Millenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptxMillenials and Fillennials (Ethical Challenge and Responses).pptx
Millenials and Fillennials (Ethical Challenge and Responses).pptx
 
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
USPS® Forced Meter Migration - How to Know if Your Postage Meter Will Soon be...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
TEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docxTEACHER REFLECTION FORM (NEW SET........).docx
TEACHER REFLECTION FORM (NEW SET........).docx
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Paradigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTAParadigm shift in nursing research by RS MEHTA
Paradigm shift in nursing research by RS MEHTA
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 3 STEPS Using Odoo 17
 
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTSGRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
GRADE 4 - SUMMATIVE TEST QUARTER 4 ALL SUBJECTS
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
The Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World PoliticsThe Contemporary World: The Globalization of World Politics
The Contemporary World: The Globalization of World Politics
 

Accessing data with android cursors

  • 1. Android Application Development Training Tutorial For more info visit http://www.zybotech.in A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 2. Accessing Data With Android Cursors What is SQLite SQLite is an open-source server-less database engine. SQLite supports transacations and has no configuration required. SQLite adds powerful data storage to mobile and embedded apps without a large footprint. Creating and connecting to a database First import android.databse.sqlite.SQLiteDatabase into your application. Then use the openOrCreateDatabase() method to create or connect to a database. Create a new project in Eclipse called TestingData and select the API version of your choice. Use the package name higherpass.TestingData with an activity TestingData and click finish. package higherpass.TestingData; import android.app.Activity; import android.os.Bundle; 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 ); } } Add the android.database.sqlite.SQLiteDatabase to the standard imports from the new project. After the standard layout setup initialize a SQLiteDatabase variable to hold the database instance. Next use the openOrCreateDatabase() method to open the database. The openOrCreateDatabase() method expects the database file first, followed by the permissions to open the database with, and an optional cursor factory builder. Where does Android store SQLite databases? Android stores SQLite databases in /data/data/[application package name]/databases. sqlite3 from adb shell bash-3.1$ /usr/local/android-sdk-linux/tools/adb devices List of devices attached emulator-5554 device bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 3. # ls /data/data/higherpass.TestingData/databases TestingData.db # sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db SQLite version 3.5.9 Enter ".help" for instructions sqlite> .tables android_metadata tbl_countries tbl_states The Google Android SDK comes with a utility adb. The adb tool can be used to browse and modify the filesystem of attached emulators and physical devices. This example is a bit ahead of where we are as we haven't created the databases yet. Setting database properties There are a few database properties that should be set after connecting to the database. Use the setVersion(), setLocale(), and setLockingEnabled() methods to set these properties. These will be demonstrated in the creating tables example. Creating Tables Tables are created by executing statements on the database. The queries should be executed with the execSQL() statement. package higherpass.TestingData; import java.util.Locale; import android.app.Activity; import android.os.Bundle; 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); final String CREATE_TABLE_COUNTRIES = "CREATE TABLE tbl_countries (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," + "country_name TEXT);"; final String CREATE_TABLE_STATES = "CREATE TABLE tbl_states (" + "id INTEGER PRIMARY KEY AUTOINCREMENT," A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 4. + "state_name TEXT," + "country_id INTEGER NOT NULL CONSTRAINT " + "contry_id REFERENCES tbl_contries(id) " + "ON DELETE CASCADE);"; db.execSQL(CREATE_TABLE_COUNTRIES); db.execSQL(CREATE_TABLE_STATES); final String CREATE_TRIGGER_STATES = "CREATE TRIGGER fk_insert_state BEFORE " + "INSERT on tbl_states" + "FOR EACH ROW " + "BEGIN " + "SELECT RAISE(ROLLBACK, 'insert on table " + ""tbl_states" voilates foreign key constraint " + ""fk_insert_state"') WHERE (SELECT id FROM " + "tbl_countries WHERE id = NEW.country_id) IS NULL; " + "END;"; db.execSQL(CREATE_TRIGGER_STATES); } } As before open the database with openOrCreateDatabase(). Now configure the database connection with setVersion to set the database version. The setLocale method sets the default locale for the database and setLockingEnabled enables locking on the database. Next we setup final String variables to hold the SQLite table creation statements and execute them with execSQL. Additionally we manually have to create triggers to handle the foreign key relationships between the table. In a production application there would also need to be foreign key triggers to handle row updates and deletes. The foreign key triggers are executed with execSQL just like the table creation. Inserting records Android comes with a series of classes that simplify database usage. Use a ContentValues instance to create a series of table field to data matchings that will be passed into an insert() method. Android has created similar methods for updating and deleting records. ContentValues values = new ContentValues(); values.put("country_name", "US"); long countryId = db.insert("tbl_countries", null, values); ContentValues stateValues = new ContentValues(); stateValues.put("state_name", "Texas"); stateValues.put("country_id", Long.toString(countryId)); try { db.insertOrThrow("tbl_states", null, stateValues); } catch (Exception e) { //catch code } Append this code to the previous example. First create a ContentValues object to store the data to insert and use the put method to load the data. Then use the insert() method to perform the insert query into SQLite. The insert() function expects three parameters, the table name, null, and the ContentValues pairs. Also a long is returned by the insert() function. This long will hold the primary key of the inserted row. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 5. Next we create a new ContentValues pair for the state and perform a second insert using the insertOrThrow() method. Using insertOrThrow() will throw an exception if the insert isn't successful and must be surrounded by a try/catch block. You'll notice that currently the application dies with an unhandled exception because the tables we're trying to create already exist. Go back into the adb shell and attach to the SQLite database for the application and drop the tables. sqlite> drop table tbl_countries; sqlite> drop table tbl_states; Updating data Updating records is handled with the update() method. The update() function supports WHERE syntax similar to other SQL engines. The update() method expects the table name, a ContentValues instance similar to insert with the fields to update. Also allowed are optional WHERE syntax, add a String containing the WHERE statement as parameter 3. Use the ? to designate an argument replacement in the WHERE clause with the replacements passed as an array in parameter 4 to update. ContentValues updateCountry = new ContentValues(); updateCountry.put("country_name", "United States"); db.update("tbl_countries", updateCountry, "id=?", new String[] {Long.toString(countryId)}); First remove the table create statements from the code. We don't need to keep creating and dropping tables. Now create a new ContentValues instance, updateCountry, to hold the data to be updated. Then use the update() method to update the table. The where clause in parameter 3 uses replacement of the ? with the values stored in parameter 4. If multiple ? existed in the where statement they would be replaced in order by the values of the array. From the adb shell attach to the database and execute select * FROM tbl_countries; inside sqlite3. bash-3.1$ /usr/local/android-sdk-linux/tools/adb -s emulator-5554 shell # sqlite3 /data/data/higherpass.TestingData/databases/TestingData.db SQLite version 3.5.9 Enter ".help" for instructions sqlite> select * FROM tbl_countries; 1|United States Deleting data Once data is no longer needed it can be removed from the database with the delete() method. The delete() method expects 3 parameters, the database name, a WHERE clause, and an argument array for the WHERE clause. To delete all records from a table pass null for the WHERE clause and WHERE clause argument array. db.delete("tbl_states", "id=?", new String[] {Long.toString(countryId)}); Simply call the delete() method to remove records from the SQLite database. The delete method expects, the table name, and optionally a where clause and where clause argument replacement arrays as parameters. The where clause and argument replacement array work just as with update where ? is replaced by the values in the array. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 6. 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 Cursors 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 higherpass.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. Iterating through records The Cursor class provides a couple of simple methods to allow iterating through Cursor data easily. Use moveToFirst() to position the Cursor pointer at the first record then use the moveToNext() function to iterate A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 7. through the records. The isAfterLast() method performs a check to see if the cursor is pointed after the last record. When looping through records break the loop when this becomes false. First add the following attribute to the TextView element in the main layout. The main layout is the xml file located at res/layouts/main.xml. We need to give this TextView element an ID that we can reference to update the view. android:id="@+id/hello" Java code to iterate through entries in a cursor: package higherpass.TestingData; import java.util.Locale; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; 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); TextView view = (TextView) findViewById(R.id.hello); 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.moveToFirst(); while (cur.isAfterLast() == false) { view.append("n" + cur.getString(1)); cur.moveToNext(); } cur.close(); } } This code simply creates a cursor querying all the records of the table tbl_countries. The moveToFirst() method is used to position the cursor pointer at the beginning of the data set. Then loop through the records in the cursor. The method isAfterLast() returns a boolean if the pointer is past the last record in the cursor. Use the moveToNext() method to traverse through the records in the cursor. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 8. Retrieving a specific record The cursor also allows direct access to specific records. Cursor cur = db.query("tbl_countries", null, null, null, null, null, null); cur.moveToPosition(0); view.append("n" + cur.getString(1)); cur.close(); Transactions SQLite also supports transactions when you need to perform a series of queries that either all complete or all fail. When a SQLite transaction fails an exception will be thrown. The transaction methods are all part of the database object. Start a transaction by calling the beginTransaction() method. Perform the queries and then call the setTransactionSuccessful() when you wish to commit the transaction. Once the transaction is complete call the endTransaction() function. db.beginTransaction(); Cursor cur = null; try { cur = db.query("tbl_countries", null, null, null, null, null, null); cur.moveToPosition(0); ContentValues values = new ContentValues(); values.put("state_name", "Georgia"); values.put("country_id", cur.getString(0)); long stateId = db.insert("tbl_states", null, values); db.setTransactionSuccessful(); view.append("n" + Long.toString(stateId)); } catch (Exception e) { Log.e("Error in transaction", e.toString()); } finally { db.endTransaction(); cur.close(); } Start off with a call to beginTransaction() to tell SQLite to perform the queries in transaction mode. Initiate a try/catch block to handle exceptions thrown by a transaction failure. Perform the queries and then call setTransactionSuccessful() to tell SQLite that our transaction is complete. If an error isn't thrown then endTransaction() can be called to commit the transaction. Finally close the cursor when we're finished with it. Built in android databases The Android Operating-System provides several built-in databases to store and manage core phone application data. Before external applications may access some of these data sources access must be granted in the AndroidManifest.xml file in the root of the project. Some of the data applications can access are the bookmarks, media player data, call log, and contact data. Contact data not covered due to changes in the API between 1.x and 2.0 version of Android. See the Android Working With Contacts Tutorial. Android provides built in variables to make working with the internal SQLite databases easy. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 9. Access permissions Before a program accesses any of the internal Android databases the application must be granted access. This access is granted in the AndroidManifest.xml file. Before the application is installed from the market the user will be prompted to allow the program to access this data. <uses-permission android:name="com.android.browser.permission.READ_HISTORY_BOOKMARKS" /> <uses-permission android:name="com.android.broswer.permission.WRITE_HISTORY_BOOKMARKS" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> These are some sample uses-permission statements to grant access to internal Android databases. These are normally placed below the uses-sdk statement in the AndroidManifest.xml file. The first 2 grant read and write access to the browser history and bookmarks. The third grants read access to the contacts. We'll need to grant READ access to the bookmarks and contacts for the rest of the code samples to work. Managed Query Managed queries delegate control of the Cursor to the parent activity automatically. This is handy as it allows the activity to control when to destroy and recreate the Cursor as the application changes state. package higherpass.TestingData; import android.app.Activity; import android.os.Bundle; import android.provider.Browser; import android.widget.TextView; import android.database.Cursor; 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); TextView view = (TextView) findViewById(R.id.hello); Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI, null, null, null, null ); mCur.moveToFirst(); int index = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE); while (mCur.isAfterLast() == false) { view.append("n" + mCur.getString(index)); mCur.moveToNext(); } } } The managed query functions very similar to the query function we used before. When accessing Android built in databases you should reference them by calling the associated SDK variable containing the correct database URI. In this case the browser bookmarks are being accessed by pointing the managedQuery() statement at android.provider.Browser.BOOKMARKS_URI. We left the rest of the parameters null to pull all results from the table. Then we iterate through the cursor records. Each time through the loop we append the title of the A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 10. bookmark to the TextView element. If you know the name of a column, but not it's index in the results use the getColumnIndex() method to get the correct index. To get the value of a field use the getString() method passing the index of the field to return. Bookmarks The first Android database we're going to explore is the browser bookmarks. When accessing the internal Android databases use the managedQuery() method. Android includes some helper variables in Browser.BookmarkColumns to designate column names. They are Browser.BookmarkColumns.TITLE, BOOKMARK, FAVICON, CREATED, URL, DATE, VISITS. These contain the table column names for the bookmarks SQLite table. package higherpass.TestingData; import android.app.Activity; import android.os.Bundle; import android.provider.Browser; import android.widget.TextView; import android.database.Cursor; 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); TextView view = (TextView) findViewById(R.id.hello); String[] projection = new String[] { Browser.BookmarkColumns.TITLE , Browser.BookmarkColumns.URL }; Cursor mCur = managedQuery(android.provider.Browser.BOOKMARKS_URI, projection, null, null, null ); mCur.moveToFirst(); int titleIdx = mCur.getColumnIndex(Browser.BookmarkColumns.TITLE); int urlIdx = mCur.getColumnIndex(Browser.BookmarkColumns.URL); while (mCur.isAfterLast() == false) { view.append("n" + mCur.getString(titleIdx)); view.append("n" + mCur.getString(urlIdx)); mCur.moveToNext(); } } } This code works as before, with the addition of limiting return columns with a projection. The projection is a string array that holds a list of the columns to return. In this example we limited the columns to the bookmark title (Browser.BookmarkColumns.TITLE) and URL (Browser.BookmarkColumns.URL). The projection array is then passed into managedQuery as the second parameter. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 11. Media Player The Android Media-player also uses SQLite to store the media information. Use this database to find media stored on the device. Available fields are DATE_ADDED, DATE_MODIFIED, DISPLAY_NAME, MIME_TYPE, SIZE, and TITLE. package higherpass.TestingData; import android.app.Activity; import android.os.Bundle; import android.provider.MediaStore; import android.provider.MediaStore.Audio.Media; import android.widget.TextView; import android.database.Cursor; 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); TextView view = (TextView) findViewById(R.id.hello); String[] projection = new String[] { MediaStore.MediaColumns.DISPLAY_NAME , MediaStore.MediaColumns.DATE_ADDED , MediaStore.MediaColumns.MIME_TYPE }; Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI, projection, null, null, null ); mCur.moveToFirst(); while (mCur.isAfterLast() == false) { for (int i=0; i<mCur.getColumnCount(); i++) { view.append("n" + mCur.getString(i)); } mCur.moveToNext(); } } } The only differences here is that we use getColumnCount() to determine the number of columns in the returned records and loop through displaying each column. Call Log If granted permission Android applications can access the call log. The call log is accessed like other datastores. package higherpass.TestingData; import android.app.Activity; import android.os.Bundle; import android.provider.CallLog; import android.provider.CallLog.Calls; A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi
  • 12. import android.widget.TextView; import android.database.Cursor; 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); TextView view = (TextView) findViewById(R.id.hello); String[] projection = new String[] { Calls.DATE , Calls.NUMBER , Calls.DURATION }; Cursor mCur = managedQuery(CallLog.Calls.CONTENT_URI, projection, Calls.DURATION +"<?", new String[] {"60"}, Calls.DURATION + " ASC"); mCur.moveToFirst(); while (mCur.isAfterLast() == false) { for (int i=0; i<mCur.getColumnCount(); i++) { view.append("n" + mCur.getString(i)); } mCur.moveToNext(); } } } This final example introduces the rest of the managedQuery() parameters. After the projection we pass a WHERE clause in the same way they were crafted in the update and delete sections earlier. After the where clause comes the array of replacement arguments. Finally we pass in an order by clause to tell SQLite how to sort the results. This query only retrieves records for phone calls lasting less than 60 seconds and sorts them by duration ascending. A7, Stephanos Tower, Eachamukku, Kakkanadu,Kochi