Attention points for Android database upgrade, downgrade, Creation (OnCreate () Onupgrade () Ondowngrade ())

Source: Internet
Author: User
Tags throw exception

The following content can be used as interviewers in the interview when the problem, feel better, is a more commonly used knowledge points, can be used to investigate whether the foundation is solid.

You can also program apes to learn and develop the points of attention. Because a little attention is given, it can cause the database to be unavailable.

Dbadapter.java is a simple class that is used primarily for database operations.

1 package com.example.test_20131218; 2  3 import android.content.Context; 4 import android.database.sqlite.SQLiteDatabase; 5  6 public class Dbadapter {7     private static dbadapter INSTANCE  = null; 8     private Dbopenhelper mhelper = null; 9     Private Sqlitedatab ASE mdb = null;10     Private Dbadapter (context context) {One         mhelper = new Dbopenhelper (context);         mdb = Mhelper . Getwritabledatabase ();     }14 public     static Dbadapter getinstance (context context) {         if (INSTANCE = = NULL) {             dbadapter return new (context);         }18         return instance;19}20 public     Void Open () {21         if (mdb = = null) {$             mdb = Mhelper.getwritabledatabase ();         }24     }25     26}


DBHelper class:

 1 package com.example.test_20131218; 2 3 Import Android.content.Context; 4 Import Android.database.sqlite.SQLiteDatabase; 5 Import Android.database.sqlite.SQLiteOpenHelper; 6 Import Android.util.Log; 7 8 public class Dbopenhelper extends Sqliteopenhelper {9/***10 * Database version must be greater than 0, otherwise error: one * java.lang.Runtime Exception:unable to start activity * COMPONENTINFO{COM.EXAMPLE.TEST_20131218/13 * com.example.test_20131218. Mainactivity}: Java.lang.IllegalArgumentException:Version must be >= 1, is 014 */15 public static final int Db_version = 5;16 public static final String db_name = "test20131218.db"; all public dbopenhelper (Context con Text) {(context, db_name, NULL, db_version),}21 @Override23 public void OnCreate (sqlited Atabase db) {24/**25 * This method 26 * 1, the first time you open the database will walk 27 * 2, after clearing the data run again--open the database, this method will go 2    8 * 3, no clear data, will not go this method 29 * 4, the database upgrade when this method will not go 30      */31 log.i ("Xinye", "############ #数据库创建了 ##############:" + db_version);}33 @Override35 Pub           LIC void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {36/**37 * 1, the first time you create a database, this method does not go 38 * 2, clear the data after running again (equivalent to the first creation) This method does not go 39 * 3, the database already exists, and the version is raised, this method will call the */41 log.i ("Xinye", "############ #数据库升级了 ##############:" + db_version),}44 @Override45 public void Ondowngrade (sqlit          Edatabase db, int oldversion, int newversion) {46/**47 * Perform degraded operation of the database 48 * 1, only the new version is lower than the previous version will be executed 49         * 2, if do not perform demotion operation, will throw exception of */51 log.i ("Xinye", "############ #数据库降级了 ##############:" + db_version); 52 Super.ondowngrade (db, Oldversion, newversion); 53}54 55}


For more information, please refer to the translation of the Android document by Daniel Blog: http://blog.csdn.net/think_soft/article/details/7969122

can also self-Baidu, google!

Here's a copy of Daniel's blog for later reference:

Android class Reference---sqliteopenhelper

Public abstract class

Sqliteopenhelper

Inheritance relationship

Java.lang.Object

|____android.database.sqlite.sqliteopenhelper

class overview

This is an auxiliary class that is used to manage the creation of databases and the version of the database.

You will create a subclass of this class to implement the OnCreate (Sqlitedatabase), Onupgrade (Sqlitedatabase,int,int) method, and the optional OnOpen (sqlitedatabase) method, And this class wants to manage the state of the database, open the database if the database exists, or create the database, and update the database when needed. Use transactions to ensure that the database is always in the correct state.

This class makes the implementation of ContentProvider easy, delaying the opening and upgrading of the database to the first use, thus avoiding application blocking due to the long running of the upgrade database.

Note: This class assumes an incremental version number to upgrade.

Public constructor

Public Sqliteopenhelper (Context context, String name, Sqlitedatabase.curesorfactory factory, int version)

Creates a helper object that is used to create, open, and manage databases. This method is always quick to return. The database is not actually created until the getwriteabledatabase () or Getreadabledatabase () method is called.

Parameter description:

Context: Used to open or create a database;

Name: Specifies the file name of the database, NULL specifies an in-memory database

Factory: Used to create a cursor object, or default null;

Version: Specifies the build number of the database (starting at 1), and if the database is older, the Onupgrade (sqlitedatabase, int, int) method will be used to upgrade the database. If the database is relatively new, the Ondowngrade (sqlitedatabase, int, int) method is used to demote the database.

Public Sqliteopenhelper (Context context, String name, Sqlitedatabase.cursorfactory factory, int version, Databaseerrorhandler ErrorHandler)

Creates a helper object that is used to create, open, and manage databases. This method is always quick to return. The database is not actually created until the getwriteabledatabase () or Getreadabledatabase () method is called.

Receive input parameters: A specific Databaseerrorhandler example that is used to handle database errors reported by SQLite.

Parameter description:

Context: Used to open or create a database;

Name: Specifies the file name of the database, NULL specifies an in-memory database

Factory: Used to create a cursor object, or default null;

Version: Specifies the build number of the database (starting at 1), and if the database is older, the Onupgrade (sqlitedatabase, int, int) method will be used to upgrade the database. If the database is relatively new, the Ondowngrade (sqlitedatabase, int, int) method is used to demote the database.

ErrorHandler: This parameter is used for SQLite reporting database errors, or NULL, using the default error handler.

Public method

Public synchronized void Close ()

Close the Open database object.

Public String GetDatabaseName ()

Returns the name of the SQLite data that was passed in by the constructor and is being opened.

Public Sqlitedatabase getreadabledatabase ()

Create and/or open a database, except for some problems, the object returned by this method will be the same as the Getwritabledatabase () method, which, in the case of low disk space, requires the database to be opened in a read-only manner, in which case a read-only database is returned. If the problem is fixed, continuing the call to the Getwritabledatabase () method can also succeed, when the read-only database object is closed and a read-write object is returned.

The Getwritabledatabase () method may take a long time to return, so it should not be called in the application's main thread, including the Contentprovider.oncreate () method.

return Value: Returns a database object that is valid until the getwritabledatabase () or close () method is called.

exception: A Sqliteexception exception is thrown if the data cannot be opened.

Public Sqlitedatabase getwritabledatabase ()

Create and/or open a database for read-write. If this method is called for the first time, then the data will be opened and OnCreate (Sqlitedatabase), Onupgrade (sqlitedatabase, int, int) and/or OnOpen (sqlitedatabase) method is called.

Once the database is opened, the database is cached, so you can call this method every time you need to write a database. (Be sure to call the close () method when you do not need the database.) Errors such as unauthorized or no disk space may cause this method call to fail, but if these problems are corrected, the method will be successfully invoked.

Note: The database upgrade may take a long time, so do not call this method in the main thread of the application, including Contentprovider.oncreate ().

return value: A read-write database object that is not invalidated until the close () method is called.

exception: If the database cannot be opened for writing, a Sqliteexception exception is thrown.

public void Onconfigure ()

This method is called when configuring a data connection to ensure that features such as pre-write logs or foreign key support are available.

This method is in OnCreate (sqlitedatabase), Onupgrade (sqlitedatabase, int, int), Ondowngrade (sqlitedatabase, int, int) or OnOpen ( Sqlitedatabase) method is called before it is invoked. In addition to configuring the necessary database connections, it should not edit the database.

This method should only invoke the method that configures the database connection parameters, such as enablewriteaheadlogging (), Setforeignkeyconstraintsenabled (Boolean), SetLocale (Locale), Setmaximumsize (long), or execute the pragma statement.

Parameters:

DB: The database object being configured

public abstract void OnCreate (Sqlitedatabase db)

This method is called when the database is first created. This is where the database tables and table initialization are created.

Parameters:

DB: The database to be created.

public void Ondowngrade (sqlitedatabase db, int oldversion, int newversion)

This method is called when the database needs to be degraded. This method is very similar to the Onupgrade (sqlitedatabase, int, int) method, but it is only called when the current version is newer than the requested version. But this method is not abstract, so it is not mandatory to require the customer to implement it. If this method is not overridden, the default implementation rejects the demotion process and throws a Sqliteexception exception.

This method is executed in the transaction. If an exception is thrown, all changes will be rolled back.

Parameters:

DB: Specify the database to demote

Oldversion: Old database version

NewVersion: New Database version

public void OnOpen (Sqlitedatabase db)

This method is called when the database is opened. The implementation of this method should check if the database is read-only (call the IsReadOnly () method) before upgrading the database.

This method is called after the database connection is configured and the database policy is created, upgraded, or degraded as necessary. If the database connection must make certain settings before the policy is created, upgraded, or demoted, then do it in the Onconfigure (Sqlitedatabase) method.

Parameters:

DB: The database being opened.

public abstract void Onupgrade (sqlitedatabase db, int oldversion, int newversion)

This method is called when the database needs to be upgraded. You should use this method to implement deleting a table, adding a table, or doing something that requires a new version of the policy to be upgraded.

The documentation for SQLite ALTER table can be found in the following URLs:

Http://sqlite.org/lang_altertable.html

If you want to add a new column to the table, use ALTER TABLE to insert the new column into the table. If you want to rename or delete a column, you can use ALTER TABLE to rename the old table, then create a new table and copy the contents of the old table into the new table.

This method is executed in the transaction, and if an exception is thrown, all changes will be automatically rolled back.

Parameters:

DB: Specify the database to demote

Oldversion: Old database version

NewVersion: New Database version

public void Setwriteaheadloggingenabled (Boolean enabled)

Enables or disables the pre-write log for the database. The pre-write log cannot be used for a read-only database, so if the data is opened in a read-only manner, the tag value is ignored.

Parameters:

Enabled:true: Enable pre-write log, false: Disable pre-write log

Refer to: Enablewriteaheadlogging () method.

Http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#enableWriteAheadLogging ()

Attention points for Android database upgrade, downgrade, Creation (OnCreate () Onupgrade () Ondowngrade ())

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.