In Android, what should we do when the database needs to be updated ?, Android Database

Source: Internet
Author: User

In Android, what should we do when the database needs to be updated ?, Android Database

Question: How can I update and retain the original data in the Android database?

Andoird'sSQLiteOpenHelperClass hasOnUpgradeMethod. This method is triggered when the database is upgraded. After practice, I solved a series

Question:
1. What does "Database Upgrade" refer to in the help document?
You have developed an application. The current version is 1.0. The program uses the database. By 1.1, you have added a field to a table in the database. Then the database used for Software Version 1.0 will be upgraded in Software Version 1.1 (of course, the upgrade here includes two concepts: application upgrade and Database Upgrade)

For application updates, you can directly modify them in the AndroidManifest. xml file.

To upgrade the database, we need to modify it in the Code:

private static final String DBNAME = "ads.db";private static final int VERSION = 1;public DBOpenHelper(Context context) {super(context, DBNAME, null, VERSION);}
When using the database, we will define a Helper class. We need to implement the SQLiteOpenHelper class (which is an abstract class) and then implement its onCreate and onUpgrade methods. The above code snippet is in our custom Helper class. Here we will see that in the constructor method, we will call the parent class (that is, the constructor of the SQLiteOpenHelper class ), the Context variable, database name, and database version number must be passed here (the third parameter is a factory class and null can be passed ). So we can upgrade the database in this place. Of course, we usually set the database version number to 1 for the first time and then increase progressively. This is the reason, the source code will be analyzed later.

2. What should I pay attention to when upgrading the database?

When the Software Version 1.0 is upgraded to Version 1.1, the old data in the database cannot be lost. In the application of Version 1.1, it is necessary to detect that the new database is incompatible with the old database. In addition, it is possible to upgrade the database in the 1.0 application to the database that can be used in the 1.1 Application. In other words, add the field to the table in the database of the 1.0 application and assign the field default value.


3. How does the application know that the database needs to be upgraded?
The constructor of the SQLiteOpenHelper class has a parameter: Int versionIt indicates the database version number. For example, in application 1.0, we use
When SQLiteOpenHelper accesses the database, this parameter is 1, so the database version 1 will be written in our database. In Version 1.1, our database needs to change. In our 1.1 program, we need to use an integer greater than 1 to construct the SQLiteOpenHelper class for accessing new databases, such as 2. When our new program 1.1 reads the old database of version 1.0, it finds that the database version stored in the old database is 1, and the version number entered when our new program accesses it is 2, the system knows that the database needs to be upgraded.


4. When will the Database Upgrade be triggered? How to upgrade?

When the system constructs an object of the SQLiteOpenHelper class, it automatically callsOnUpgradeFunction, let you upgrade the database here. Based on the above scenario, add fields to the corresponding tables of the old database version in this function and add the default values for each record.

Both the new and old versions are passed in as parameters of the onUpgrade function, so that developers can know which version the database should be upgraded.

After the upgrade, the database automatically stores the latest version number as the current database version number.


The following describes the process from the source code perspective:

First, let's take a look at the SQLiteOpenHelper. java class.

    public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {        this(context, name, factory, version, null);    }

We can see that this constructor is called in the subclass. The third parameter is a cursor factory class, which can pass null. Let's take a look at his other constructor methods:

    public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version,            DatabaseErrorHandler errorHandler) {        if (version < 1) throw new IllegalArgumentException("Version must be >= 1, was " + version);        mContext = context;        mName = name;        mFactory = factory;        mNewVersion = version;        mErrorHandler = errorHandler;    }

Here we will see a message that determines the version number. if the version number is smaller than 1, an exception is thrown. Therefore, we generally set the version number to 1. The construction is over. Let's take a look at his onCreate and onUpgrade methods:

    public abstract void onCreate(SQLiteDatabase db);    public abstract void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion);

Both methods are abstract and must be implemented by sub-classes.

Well, which method should we look at below? Of course, it depends on the method we used. The code we usually use when using the database:

DBOpenHelper openHelper = new DBOpenHelper(this);SQLiteDatabase db = openHelper.getWritableDatabase();

Initialize the custom Helper class and obtain a database object SQLiteDatabase. Let's take a look at your getWritableDatabase method:

    public SQLiteDatabase getWritableDatabase() {        synchronized (this) {            return getDatabaseLocked(true);        }    }

The synchronization mechanism is used here. Next we can see the getDatabaseLocked method:

private SQLiteDatabase getDatabaseLocked(boolean writable) {        if (mDatabase != null) {            if (!mDatabase.isOpen()) {                // Darn!  The user closed the database by calling mDatabase.close().                mDatabase = null;            } else if (!writable || !mDatabase.isReadOnly()) {                // The database is already open for business.                return mDatabase;            }        }        if (mIsInitializing) {            throw new IllegalStateException("getDatabase called recursively");        }        SQLiteDatabase db = mDatabase;        try {            mIsInitializing = true;            if (db != null) {                if (writable && db.isReadOnly()) {                    db.reopenReadWrite();                }            } else if (mName == null) {                db = SQLiteDatabase.create(null);            } else {                try {                    if (DEBUG_STRICT_READONLY && !writable) {                        final String path = mContext.getDatabasePath(mName).getPath();                        db = SQLiteDatabase.openDatabase(path, mFactory,                                SQLiteDatabase.OPEN_READONLY, mErrorHandler);                    } else {                        db = mContext.openOrCreateDatabase(mName, mEnableWriteAheadLogging ?                                Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0,                                mFactory, mErrorHandler);                    }                } catch (SQLiteException ex) {                    if (writable) {                        throw ex;                    }                    Log.e(TAG, "Couldn't open " + mName                            + " for writing (will try read-only):", ex);                    final String path = mContext.getDatabasePath(mName).getPath();                    db = SQLiteDatabase.openDatabase(path, mFactory,                            SQLiteDatabase.OPEN_READONLY, mErrorHandler);                }            }            onConfigure(db);            final int version = db.getVersion();            if (version != mNewVersion) {                if (db.isReadOnly()) {                    throw new SQLiteException("Can't upgrade read-only database from version " +                            db.getVersion() + " to " + mNewVersion + ": " + mName);                }                db.beginTransaction();                try {                    if (version == 0) {                        onCreate(db);                    } else {                        if (version > mNewVersion) {                            onDowngrade(db, version, mNewVersion);                        } else {                            onUpgrade(db, version, mNewVersion);                        }                    }                    db.setVersion(mNewVersion);                    db.setTransactionSuccessful();                } finally {                    db.endTransaction();                }            }            onOpen(db);            if (db.isReadOnly()) {                Log.w(TAG, "Opened " + mName + " in read-only mode");            }            mDatabase = db;            return db;        } finally {            mIsInitializing = false;            if (db != null && db != mDatabase) {                db.close();            }        }    }

There are a lot of things in this method, and it seems to be the core part.

First, we can see that the mDatabase field is of the SQLiteDatabase type.

private SQLiteDatabase mDatabase;

Let's take a look at the code at the beginning:

if (mDatabase != null) {if (!mDatabase.isOpen()) {// Darn!  The user closed the database by calling mDatabase.close().mDatabase = null;} else if (!writable || !mDatabase.isReadOnly()) {// The database is already open for business.return mDatabase;}}

If the mDatabase is not null, you can determine whether the database is closed or not. If the database is closed, set it to null. If it is not disabled, you can determine whether the status is readable or writable, and then return an instance.


Continue with the following code:

SQLiteDatabase db = mDatabase;try {mIsInitializing = true;if (db != null) {if (writable && db.isReadOnly()) {db.reopenReadWrite();}} else if (mName == null) {db = SQLiteDatabase.create(null);} else {try {if (DEBUG_STRICT_READONLY && !writable) {final String path = mContext.getDatabasePath(mName).getPath();db = SQLiteDatabase.openDatabase(path, mFactory,SQLiteDatabase.OPEN_READONLY, mErrorHandler);} else {db = mContext.openOrCreateDatabase(mName, mEnableWriteAheadLogging ?Context.MODE_ENABLE_WRITE_AHEAD_LOGGING : 0,mFactory, mErrorHandler);}} catch (SQLiteException ex) {if (writable) {throw ex;}Log.e(TAG, "Couldn't open " + mName+ " for writing (will try read-only):", ex);final String path = mContext.getDatabasePath(mName).getPath();db = SQLiteDatabase.openDatabase(path, mFactory,SQLiteDatabase.OPEN_READONLY, mErrorHandler);}}

This code mainly initializes a SQLiteDatabase object.


Continue:

final int version = db.getVersion();if (version != mNewVersion) {if (db.isReadOnly()) {throw new SQLiteException("Can't upgrade read-only database from version " +db.getVersion() + " to " + mNewVersion + ": " + mName);}db.beginTransaction();try {if (version == 0) {onCreate(db);} else {if (version > mNewVersion) {onDowngrade(db, version, mNewVersion);} else {onUpgrade(db, version, mNewVersion);}}db.setVersion(mNewVersion);db.setTransactionSuccessful();} finally {db.endTransaction();}}

This code is our main research object and will solve many of our questions. The logic of the code is simple:

First, he gets the version number of the current database. Here, the database is a SQLiteDatabase object created in the previous Code. Then, he calls its getVersion method to obtain the version number and view the source code of getVersion:

    public int getVersion() {        return ((Long) DatabaseUtils.longForQuery(this, "PRAGMA user_version;", null)).intValue();    }


Here we see the longForQuery method of the DatabaseUtils class. Continue to find the source code of this method:

    public static long longForQuery(SQLiteDatabase db, String query, String[] selectionArgs) {        SQLiteStatement prog = db.compileStatement(query);        try {            return longForQuery(prog, selectionArgs);        } finally {            prog.close();        }    }

After finding this method, it is actually very simple internally, that is, to execute an SQL statement. The SQL statement is:

PRAGMA user_version;
The query result is of the long type. Therefore, when defining the database version, the query result is generally an integer, and the increment value is also an integer.

What is the value of the database version when we create the database for the first time? In fact, this can be guessed. It may be 0. So let's make a verification. The verification here is not in the form of code, but by using a software: Sqlite Expert

This software is relatively simple to use. Create a new database and execute the preceding SQL statement. The result is as follows:


Sure enough, the first obtained version number is 0. Now let's continue to look at the previous code analysis. We have analyzed it and obtained the database version number, and then compared it with the previous version. If not


Here we will make another judgment to determine whether the current database is read-only. If it is read-only, subsequent update operations cannot be performed and an exception is thrown.

if (db.isReadOnly()) {throw new SQLiteException("Can't upgrade read-only database from version " +db.getVersion() + " to " + mNewVersion + ": " + mName);}

If it is not read-only, continue with the following code:

db.beginTransaction();try {if (version == 0) {onCreate(db);} else {if (version > mNewVersion) {onDowngrade(db, version, mNewVersion);} else {onUpgrade(db, version, mNewVersion);}}db.setVersion(mNewVersion);db.setTransactionSuccessful();} finally {db.endTransaction();}

Start a transaction. If the obtained database version is 0, the onCreate method is executed. if the version number increases, the onUpgrade method is executed. if the version number decreases, the onDowngrade method is executed, and an exception is thrown.

public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {        throw new SQLiteException("Can't downgrade database from version " +                oldVersion + " to " + newVersion);}

Set the database version to the latest value. End the transaction.


A problem occurs during use.The onCreate method is called in the onUpgrade method, but at this time the onCreate method will report an exception. Of course we captured it (when using Helper outside ), however, the onUpgrade method is executed every time an application is opened. At that time, I was searching for the reason. No clue.

In fact, we can find the cause here, because when the onUpgrade method reports an exception (because the onCreate method is called in the onUpgrade method, when the onCreate method reports an exception, if the onUpgrade method does not capture this exception, an exception will be reported.) The subsequent code will not be executed, and the Code for setting the latest database version number will not be executed, therefore, each time the app is opened, the version number is compared, and the onUpgrade method is executed. This method still reports an exception, so the onUpgrade method is executed every time the app is opened. Next let's take a look.

Package com. sohu. sqlitedemo; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. database. sqlite. SQLiteDatabase. cursorFactory; import android. database. sqlite. SQLiteOpenHelper; import android. util. log; import android. widget. toast; public class DBOpenHelper extends SQLiteOpenHelper {private static final String DBNAME = "ads. db "; private static final int VERSION = 1; p Ublic DBOpenHelper (Context context) {super (context, DBNAME, null, VERSION) ;}@ Overridepublic void onCreate (SQLiteDatabase db) {Log. I ("DEMO", "oldVersion, onCreate ()" mongomongodb.exe cSQL ("CREATE TABLE IF NOT EXISTS offlineBanner (" // + "id integer primary key autoincrement, "// +" vid VARCHAR (100), "/// +" adsequences integer, "// +" isofflineads integer, "+" Impression VARCHAR (2000 ), "// +" Duration VARCHAR (50 ),"// + "ClickThrough VARCHAR (500)," // + "ClickTracking VARCHAR (500)," // + "MediaFile VARCHAR (500 ), "// +" creativeView VARCHAR (500), "// +" start VARCHAR (500), "// +" firstQuartile VARCHAR (500 ), "// +" midpoint VARCHAR (500), "// +" thirdQuartile VARCHAR (500), "// +" complete VARCHAR (500 ), "// +" sdkTracking VARCHAR (2000), "// +" sdkClick VARCHAR (2000), "// +" time VARCHAR (50 ));"); /// this line of code reports an exception db.exe cSQL ("CREATE TABLE offlinePause ("// +" id integer primary key autoincrement, "// +" vid VARCHAR (100), "// +" Impression VARCHAR (2000 ), "// +" StaticResource VARCHAR (500), "// +" NonLinearClickThrough VARCHAR (500), "// +" sdkTracking VARCHAR (2000 ), "// +" sdkClick VARCHAR (2000), "// +" time VARCHAR (50 ));"); // db.exe cSQL ("create table if not exists download_url (" // + "id integer primary key autoincrement," // + "url varch Ar (500), "// +" status integer, "// +" length integer) "); //} @ Overridepublic void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {Log. I ("DEMO", "oldVersion =" + oldVersion + ", newVersion" + newVersion); if (oldVersion! = NewVersion) mongodb.exe cSQL ("alter table offlineBanner add column adsequence integer;" mongomongodb.exe cSQL ("alter table offlineBanner add column isofflinead integer; "dropping mongodb.exe cSQL (" drop table if exists download_url ");} // an onCreate (db) exception will be reported during execution of the method );}}


The reason for reporting exceptions is simple. When an update is required, the onUpgrade method is executed. Here the onCreate method is executed. An exception is reported when you create a pause table because the table already exists.


When we add try... catch to the Code:

Try {// start using the database DBOpenHelper openHelper = new DBOpenHelper (this); SQLiteDatabase db = openHelper. getWritableDatabase (); db. close ();} catch (Exception e ){}

The problem is solved, but the onUpgrade method is executed multiple times:


Therefore, we still need to solve the exception problem in the onCreate method. The exception is because the table exists. Therefore, when creating a table, we need to determine whether the table already exists. In this way, you can.

The above describes the principle from the source code perspective. Let's take a look at the example below:

Android applications may inevitably deal with SQLite. With the continuous upgrading of applications, the original database structure may no longer adapt to new features. At this time, the structure of the SQLite database needs to be upgraded. SQLite provides the alter table command, allowing you to rename or add new fields to an existing TABLE, but cannot delete fields from the TABLE.

You can only add fields at the end of the table. For example, you can add two fields to subpartition:
ALTER TABLE Subscription ADD COLUMN Activation BLOB;ALTER TABLE Subscription ADD COLUMN Key BLOB;

In addition, if you encounter complex modification operations, such as data transfer while modifying, You can execute the following statement in a transaction to modify the table.

1. Change the table name to a temporary table.
 ALTER TABLE Subscription RENAME TO __temp__Subscription;

2. Create a new table
CREATE TABLE Subscription (OrderId VARCHAR(32) PRIMARY KEY ,UserName VARCHAR(32) NOT NULL ,ProductId VARCHAR(16) NOT NULL);

3. Import Data
INSERT INTO Subscription SELECT OrderId, “”, ProductId FROM __temp__Subscription;
Or
INSERT INTO Subscription() SELECT OrderId, “”, ProductId FROM __temp__Subscription;
* Note that double quotation marks (") are used to supplement data that does not exist.
4. delete a temporary table
DROP TABLE __temp__Subscription;
The above four steps can be used to migrate the old database structure to the new database structure, and ensure that the data will not be lost due to the upgrade.
Of course, you can also create a temporary table to reduce fields.

When the Android Application updates, if the database modifies fields, the database needs to be updated and the original database data is retained:
This is the original database table.
CREATE_BOOK = "create table book(bookId integer primarykey,bookName text);";
Then we add a field:
CREATE_BOOK = "create table book(bookId integer primarykey,bookName text,bookContent text);";
First, rename the original database table.
CREATE_TEMP_BOOK = "alter table book rename to _temp_book";
Copy the data in the backup table to the newly created database table.
INSERT_DATA = "insert into book select *, ''from _ temp_book"; (Note ''is required to insert the default value for the newly added field; otherwise, an error will occur)

Then we can just remove the backup table.
DROP_BOOK = "drop table _temp_book";

Modify the database version and update it automatically when the database operation object is created again (Note: during the update process, the object of the first operation data must be writable, that is, the database operation object obtained through getWritableDatabase)

Then execute the preceding SQL statement in the onUpgrade () method.

public class DBservice extends SQLiteOpenHelper{private String CREATE_BOOK = "create table book(bookId integer primarykey,bookName text);";private String CREATE_TEMP_BOOK = "alter table book rename to _temp_book";private String INSERT_DATA = "insert into book select *,'' from _temp_book";private String DROP_BOOK = "drop table _temp_book";public DBservice(Context context, String name, CursorFactory factory,int version) {super(context, name, factory, version);}@Overridepublic void onCreate(SQLiteDatabase db) {db.execSQL(CREATE_BOOK);}@Overridepublic void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {switch (newVersion) {case 2:db.execSQL(CREATE_TEMP_BOOK);db.execSQL(CREATE_BOOK);db.execSQL(INSERT_DATA);db.execSQL(DROP_BOOK);break;}}}


Conclusion: We don't know how to solve this problem at the beginning, so let's continue to look at the fucking code. The source code here is actually not difficult ~~, But we need to develop the habit of viewing source code.



How to update a database after it is changed in android development?

Provide you with several methods:
In the Activity for viewing student information, rewrite the onResume method and obtain data in the method to display the view. whether the activity is newly created or invisible from the background to the foreground, this is the lifecycle.
The data display page listens for data changes to update the input. If ContentProvider is used for data management, you can directly use ContentObserver to listen to the corresponding Uri. If not, you can send a broadcast when operating the student database, then, the Activity on the real student page listens to the broadcast and updates the interface after receiving the broadcast.
If you enter the modification information interface from the View information interface, you can use the startActivityForResult method to start the Information Modification interface. After the information is modified, call the setResult method to return the modified data to the information display interface, information Display Interface override onActivityResult method to obtain new student information, so as to update the interface
Now let's take a look at these methods. I hope they will help you ~


Android database update debugging Error

If your KEY_NUM is not a number, you should write it as follows:

KEY_NUM + "= '" + num + "'";

For example, name = 'Tom'

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.