SlideShare a Scribd company logo
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
Ad

More Related Content

What's hot (20)

DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
charsbar
 
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
anysql
 
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
LGS, GBHS&IC, University Of South-Asia, TARA-Technologies
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
Taming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeTaming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a time
Susanna Wong
 
Disconnected data
Disconnected dataDisconnected data
Disconnected data
aspnet123
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
Dave Stokes
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
info_zybotech
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
Mark Lester Navarro
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
Perfect APK
 
spring-tutorial
spring-tutorialspring-tutorial
spring-tutorial
Arjun Shanka
 
Apache Cassandra & Data Modeling
Apache Cassandra & Data ModelingApache Cassandra & Data Modeling
Apache Cassandra & Data Modeling
Massimiliano Tomassi
 
Data herding
Data herdingData herding
Data herding
unbracketed
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
Dr. Ramkumar Lakshminarayanan
 
Multiple files single target single interface
Multiple files single target single interfaceMultiple files single target single interface
Multiple files single target single interface
Dharmaraj Borse
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
MySQL lecture
MySQL lectureMySQL lecture
MySQL lecture
webhostingguy
 
Table partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + RailsTable partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + Rails
Agnieszka Figiel
 
MySql:Introduction
MySql:IntroductionMySql:Introduction
MySql:Introduction
DataminingTools Inc
 
MySql:Basics
MySql:BasicsMySql:Basics
MySql:Basics
DataminingTools Inc
 
DBD::SQLite
DBD::SQLiteDBD::SQLite
DBD::SQLite
charsbar
 
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
The Tools for Data Migration Between Oracle , MySQL and Flat Text File.
anysql
 
07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete07.3. Android Alert message, List, Dropdown, and Auto Complete
07.3. Android Alert message, List, Dropdown, and Auto Complete
Oum Saokosal
 
Taming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a timeTaming the beast - how to tame React & GraphQL, one error at a time
Taming the beast - how to tame React & GraphQL, one error at a time
Susanna Wong
 
Disconnected data
Disconnected dataDisconnected data
Disconnected data
aspnet123
 
Validating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentationValidating JSON -- Percona Live 2021 presentation
Validating JSON -- Percona Live 2021 presentation
Dave Stokes
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
info_zybotech
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
Mark Lester Navarro
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
Perfect APK
 
Multiple files single target single interface
Multiple files single target single interfaceMultiple files single target single interface
Multiple files single target single interface
Dharmaraj Borse
 
cPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven FeaturescPanel now supports MySQL 8.0 - My Top Seven Features
cPanel now supports MySQL 8.0 - My Top Seven Features
Dave Stokes
 
Table partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + RailsTable partitioning in PostgreSQL + Rails
Table partitioning in PostgreSQL + Rails
Agnieszka Figiel
 

Viewers also liked (17)

Teste 123
Teste 123Teste 123
Teste 123
citrus7
 
Наталья Виноградская
Наталья ВиноградскаяНаталья Виноградская
Наталья Виноградская
Oleg Samoilow
 
ระบบย่อยอาหาร
ระบบย่อยอาหารระบบย่อยอาหาร
ระบบย่อยอาหาร
kunakorn_chittangura
 
Fin.354 lecture notes
Fin.354 lecture notesFin.354 lecture notes
Fin.354 lecture notes
Ganesh Joshi
 
Валентин Калашник
Валентин КалашникВалентин Калашник
Валентин Калашник
Oleg Samoilow
 
Health Inequities
Health InequitiesHealth Inequities
Health Inequities
AaronMcCarthy
 
Halloween
HalloweenHalloween
Halloween
ibencam
 
Trabajo 4
Trabajo 4Trabajo 4
Trabajo 4
norbertoromerolerma
 
Map Skills
Map SkillsMap Skills
Map Skills
leslielong109
 
SA’EY
SA’EYSA’EY
SA’EY
Hafiz Amir Aslam
 
putting cars in their place
putting cars in their placeputting cars in their place
putting cars in their place
sneapa
 
Trabalho de estatística (Matemática)
Trabalho de estatística (Matemática) Trabalho de estatística (Matemática)
Trabalho de estatística (Matemática)
Andlice
 
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
Piotr Nalepa
 
School magazine
School magazineSchool magazine
School magazine
hanzypoo
 
Jaroslav Pelykh
Jaroslav PelykhJaroslav Pelykh
Jaroslav Pelykh
Oleg Samoilow
 
service project
service project service project
service project
kendall48
 
Carlos Erasto Romero Martinez
Carlos Erasto Romero MartinezCarlos Erasto Romero Martinez
Carlos Erasto Romero Martinez
Charlie Log
 
Teste 123
Teste 123Teste 123
Teste 123
citrus7
 
Наталья Виноградская
Наталья ВиноградскаяНаталья Виноградская
Наталья Виноградская
Oleg Samoilow
 
ระบบย่อยอาหาร
ระบบย่อยอาหารระบบย่อยอาหาร
ระบบย่อยอาหาร
kunakorn_chittangura
 
Fin.354 lecture notes
Fin.354 lecture notesFin.354 lecture notes
Fin.354 lecture notes
Ganesh Joshi
 
Валентин Калашник
Валентин КалашникВалентин Калашник
Валентин Калашник
Oleg Samoilow
 
Halloween
HalloweenHalloween
Halloween
ibencam
 
putting cars in their place
putting cars in their placeputting cars in their place
putting cars in their place
sneapa
 
Trabalho de estatística (Matemática)
Trabalho de estatística (Matemática) Trabalho de estatística (Matemática)
Trabalho de estatística (Matemática)
Andlice
 
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
JAK TESTOWAĆ CZYSTY KOD JAVASCRIPT?
Piotr Nalepa
 
School magazine
School magazineSchool magazine
School magazine
hanzypoo
 
service project
service project service project
service project
kendall48
 
Carlos Erasto Romero Martinez
Carlos Erasto Romero MartinezCarlos Erasto Romero Martinez
Carlos Erasto Romero Martinez
Charlie Log
 
Ad

Similar to Accessing data with android cursors (20)

Sql lite android
Sql lite androidSql lite android
Sql lite android
Dushyant Nasit
 
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
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
jitendral
 
Python database access
Python database accessPython database access
Python database access
Smt. Indira Gandhi College of Engineering, Navi Mumbai, Mumbai
 
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
Conint29
 
Lecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptxLecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptx
Yousef Alamir
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Android-Chapter17-SQL-Data persistency in android databases
Android-Chapter17-SQL-Data persistency in android databasesAndroid-Chapter17-SQL-Data persistency in android databases
Android-Chapter17-SQL-Data persistency in android databases
RyanAguirre5
 
Databases with SQLite3.pdf
Databases with SQLite3.pdfDatabases with SQLite3.pdf
Databases with SQLite3.pdf
Deepika,Assistant Professor,PES College of Engineering ,Mandya
 
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
kamal kotecha
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on Android
Eric 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.pptx
vishal choudhary
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Session 2- day 3
Session 2- day 3Session 2- day 3
Session 2- day 3
Vivek Bhusal
 
9 Python programming notes for ktu physics and computer application semester 4
9 Python programming notes for ktu  physics and computer application semester 49 Python programming notes for ktu  physics and computer application semester 4
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
Android SQLite database oriented application development
Android SQLite database oriented application developmentAndroid SQLite database oriented application development
Android SQLite database oriented application development
Kongu Engineering College, Perundurai, Erode
 
MAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptxMAD UNIT 5 FINAL.pptx
MAD UNIT 5 FINAL.pptx
Siva Krishna Prasad
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
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.pdf
Conint29
 
Lecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptxLecture 10: Android SQLite database.pptx
Lecture 10: Android SQLite database.pptx
Yousef Alamir
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
jitendral
 
Android-Chapter17-SQL-Data persistency in android databases
Android-Chapter17-SQL-Data persistency in android databasesAndroid-Chapter17-SQL-Data persistency in android databases
Android-Chapter17-SQL-Data persistency in android databases
RyanAguirre5
 
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
kamal kotecha
 
Better Data Persistence on Android
Better Data Persistence on AndroidBetter Data Persistence on Android
Better Data Persistence on Android
Eric 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.pptx
vishal choudhary
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
Ivano Malavolta
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
Aravindharamanan S
 
9 Python programming notes for ktu physics and computer application semester 4
9 Python programming notes for ktu  physics and computer application semester 49 Python programming notes for ktu  physics and computer application semester 4
9 Python programming notes for ktu physics and computer application semester 4
ebindboby1
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
phanleson
 
Ad

More from info_zybotech (6)

Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
info_zybotech
 
Notepad tutorial
Notepad tutorialNotepad tutorial
Notepad tutorial
info_zybotech
 
Java and xml
Java and xmlJava and xml
Java and xml
info_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 draw
info_zybotech
 
Applications
ApplicationsApplications
Applications
info_zybotech
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
info_zybotech
 
Android basics – dialogs and floating activities
Android basics – dialogs and floating activitiesAndroid basics – dialogs and floating activities
Android basics – dialogs and floating activities
info_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 draw
info_zybotech
 
Android accelerometer sensor tutorial
Android accelerometer sensor tutorialAndroid accelerometer sensor tutorial
Android accelerometer sensor tutorial
info_zybotech
 

Recently uploaded (20)

To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
To study the nervous system of insect.pptx
To study the nervous system of insect.pptxTo study the nervous system of insect.pptx
To study the nervous system of insect.pptx
Arshad Shaikh
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
How to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POSHow to Manage Opening & Closing Controls in Odoo 17 POS
How to Manage Opening & Closing Controls in Odoo 17 POS
Celine George
 
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptxSCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
SCI BIZ TECH QUIZ (OPEN) PRELIMS XTASY 2025.pptx
Ronisha Das
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
New Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptxNew Microsoft PowerPoint Presentation.pptx
New Microsoft PowerPoint Presentation.pptx
milanasargsyan5
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 

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