SlideShare une entreprise Scribd logo
1  sur  12
Télécharger pour lire hors ligne
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

Data Integration and Transformation in Data mining
Data Integration and Transformation in Data miningData Integration and Transformation in Data mining
Data Integration and Transformation in Data miningkavitha muneeshwaran
 
Android Interview Questions And Answers | Android Tutorial | Android Online T...
Android Interview Questions And Answers | Android Tutorial | Android Online T...Android Interview Questions And Answers | Android Tutorial | Android Online T...
Android Interview Questions And Answers | Android Tutorial | Android Online T...Edureka!
 
Multidimensional Database Design & Architecture
Multidimensional Database Design & ArchitectureMultidimensional Database Design & Architecture
Multidimensional Database Design & Architecturehasanshan
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLEVraj Patel
 
Custom Controls in ASP.net
Custom Controls in ASP.netCustom Controls in ASP.net
Custom Controls in ASP.netkunj desai
 
Distributed Database Management System
Distributed Database Management SystemDistributed Database Management System
Distributed Database Management SystemHardik Patil
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vbSalim M
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual StudioMuhammad Aqeel
 
Data warehouse architecture
Data warehouse architecture Data warehouse architecture
Data warehouse architecture janani thirupathi
 

Tendances (20)

Object oriented programming
Object oriented programmingObject oriented programming
Object oriented programming
 
Data Integration and Transformation in Data mining
Data Integration and Transformation in Data miningData Integration and Transformation in Data mining
Data Integration and Transformation in Data mining
 
Hadoop
HadoopHadoop
Hadoop
 
Android Interview Questions And Answers | Android Tutorial | Android Online T...
Android Interview Questions And Answers | Android Tutorial | Android Online T...Android Interview Questions And Answers | Android Tutorial | Android Online T...
Android Interview Questions And Answers | Android Tutorial | Android Online T...
 
Dtd
DtdDtd
Dtd
 
Advanced Database System
Advanced Database SystemAdvanced Database System
Advanced Database System
 
Functional dependency
Functional dependencyFunctional dependency
Functional dependency
 
Multidimensional Database Design & Architecture
Multidimensional Database Design & ArchitectureMultidimensional Database Design & Architecture
Multidimensional Database Design & Architecture
 
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
FUNCTION DEPENDENCY  AND TYPES & EXAMPLEFUNCTION DEPENDENCY  AND TYPES & EXAMPLE
FUNCTION DEPENDENCY AND TYPES & EXAMPLE
 
Custom Controls in ASP.net
Custom Controls in ASP.netCustom Controls in ASP.net
Custom Controls in ASP.net
 
Advanced DBMS presentation
Advanced DBMS presentationAdvanced DBMS presentation
Advanced DBMS presentation
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Distributed Database Management System
Distributed Database Management SystemDistributed Database Management System
Distributed Database Management System
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
System design
System designSystem design
System design
 
Error handling and debugging in vb
Error handling and debugging in vbError handling and debugging in vb
Error handling and debugging in vb
 
Azure SQL Database
Azure SQL DatabaseAzure SQL Database
Azure SQL Database
 
Presentation on Visual Studio
Presentation on Visual StudioPresentation on Visual Studio
Presentation on Visual Studio
 
Data warehouse architecture
Data warehouse architecture Data warehouse architecture
Data warehouse architecture
 
Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)Enterprise JavaBeans(EJB)
Enterprise JavaBeans(EJB)
 

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
 
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
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 

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

M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxDr. Santhosh Kumar. N
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17Celine George
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxDr. Asif Anas
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...Nguyen Thanh Tu Collection
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational PhilosophyShuvankar Madhu
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...raviapr7
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?TechSoup
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapitolTechU
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphNetziValdelomar1
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...CaraSkikne1
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 

Dernier (20)

M-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptxM-2- General Reactions of amino acids.pptx
M-2- General Reactions of amino acids.pptx
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17How to Make a Field read-only in Odoo 17
How to Make a Field read-only in Odoo 17
 
Ultra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptxUltra structure and life cycle of Plasmodium.pptx
Ultra structure and life cycle of Plasmodium.pptx
 
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
CHUYÊN ĐỀ DẠY THÊM TIẾNG ANH LỚP 11 - GLOBAL SUCCESS - NĂM HỌC 2023-2024 - HK...
 
Philosophy of Education and Educational Philosophy
Philosophy of Education  and Educational PhilosophyPhilosophy of Education  and Educational Philosophy
Philosophy of Education and Educational Philosophy
 
Prelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quizPrelims of Kant get Marx 2.0: a general politics quiz
Prelims of Kant get Marx 2.0: a general politics quiz
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...Patient Counselling. Definition of patient counseling; steps involved in pati...
Patient Counselling. Definition of patient counseling; steps involved in pati...
 
What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?What is the Future of QuickBooks DeskTop?
What is the Future of QuickBooks DeskTop?
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
CapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptxCapTechU Doctoral Presentation -March 2024 slides.pptx
CapTechU Doctoral Presentation -March 2024 slides.pptx
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
Finals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quizFinals of Kant get Marx 2.0 : a general politics quiz
Finals of Kant get Marx 2.0 : a general politics quiz
 
Presentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a ParagraphPresentation on the Basics of Writing. Writing a Paragraph
Presentation on the Basics of Writing. Writing a Paragraph
 
5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...5 charts on South Africa as a source country for international student recrui...
5 charts on South Africa as a source country for international student recrui...
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 

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