DatabaseConnector Constructor and Methods open and close

DatabaseConnection’s constructor (Fig. 8.52, lines 22–27) creates a new object of class DatabaseOpenHelper (Fig. 8.58), which will be used to open or create the database. We discuss the details of the DatabaseOpenHelper constructor in Fig. 8.58. The open method (lines 30–34) attempts to establish a connection to the database and throws a SQLException if the connection attempt fails. Method getWritableDatabase (line 33), which is inherited from SQLiteOpenHelper, returns a SQLiteDatabase object. If the database has not yet been created, this method will create it; otherwise, the method will open it. Once the database is opened successfully, it will be cached by the operating system to improve the performance of future database interactions. The close method (lines 37–41) closes the database connection by calling the inherited SQLiteOpenHelper method close.


21   // public constructor for DatabaseConnector
22   public DatabaseConnector(Context context)
23   {
24      // create a new DatabaseOpenHelper
25      databaseOpenHelper =
26         new DatabaseOpenHelper(context, DATABASE_NAME, null, 1);
27   }
28
29   // open the database connection
30   public void open() throws SQLException
31   {
32      // create or open a database for reading/writing
33      database = databaseOpenHelper.getWritableDatabase();
34   }
35
36   // close the database connection
37   public void close()
38   {
39      if (database != null)
40         database.close(); // close the database connection
41   }
42


Fig. 8.52 | DatabaseConnector constructor and methods open and close.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset