The OnCreate method and the Onupgrade method in the application of SQLite in Android--

Source: Internet
Author: User

Original: http://blog.csdn.net/jiangwei0910410003/article/details/46536329

Today in the database upgrade, encountered a problem, is the OnCreate method and the implementation of the Onupgrade method of the timing of the problem, this time in operation, did not find out, is confused, so write code when there are a lot of problems, so there is no way to get the source code to see. But before that I explained an article about database upgrade, but there is no detailed explanation of the timing of the implementation of these two methods, so here is a separate talk

Article about database Upgrade: http://blog.csdn.net/jiangwei0910410003/article/details/39670813

Not much to say, the following directly into the topic:

First we look at the source code of Sqliteopenhelper class:

There is an important method in it:getdatabaselocked

Here we see that when our mname variable is null, a memory database is created and the life cycle of the data is application level, and this mname is the name of the file that created the database.

Of course, normally, we will pass in a database file name, so this method is generally not executed, then go to the following code. The following code is to open a database directly. But what we see is that the creation of a database is related to the context. Let's look at the code in the context. But here we know that the context is an abstract class, and we will generally look at his subclass Contextimpl implementations:

Take a look at the Getdatabasepath method and the openorcreatedatabase method:

First look at the openorcreatedatabase method:

[Java]View Plaincopy
  1. @Override
  2. Public sqlitedatabase openorcreatedatabase (String name, int mode, Cursorfactory factory,
  3. Databaseerrorhandler ErrorHandler) {
  4. File f = validatefilepath (name, true);
  5. int flags = sqlitedatabase.create_if_necessary;
  6. if (mode & mode_enable_write_ahead_logging)! = 0) {
  7. Flags |= sqlitedatabase.enable_write_ahead_logging;
  8. }
  9. Sqlitedatabase db = Sqlitedatabase.opendatabase (F.getpath (), factory, flags, ErrorHandler);
  10. Setfilepermissionsfrommode (F.getpath (), mode, 0);
  11. return DB;
  12. }

Here we see that the OpenDatabase method of Sqlitedatabase is actually called.

Let's take a look at the Getdatabasepath method:

[Java]View Plaincopy
    1. @Override
    2. Public File Getdatabasepath (String name) {
    3. return Validatefilepath (name, false);
    4. }

We see that both methods have a central approach:Validatefilepath

[Java]View Plaincopy
  1. Private File Validatefilepath (String name, boolean createdirectory) {
  2. File dir;
  3. File F;
  4. if (Name.charat (0) = = File.separatorchar) {
  5. String Dirpath = name.substring (0, Name.lastindexof (File.separatorchar));
  6. dir = new File (Dirpath);
  7. Name = Name.substring (Name.lastindexof (File.separatorchar));
  8. f = new File (dir, name);
  9. } Else {
  10. dir = Getdatabasesdir ();
  11. f = Makefilename (dir, name);
  12. }
  13. if (createdirectory &&!dir.isdirectory () && Dir.mkdir ()) {
  14. Fileutils.setpermissions (Dir.getpath (),
  15. fileutils.s_irwxu| Fileutils.s_irwxg| Fileutils.s_ixoth,
  16. -1,-1);
  17. }
  18. return F;
  19. }

This method is very simple, that is, by passing the name of the database, and then build a database file object return.

So here are a few ways we can summarize the function:

Create a file object by passing the database name named Name, and then get the path to the database file: In the OpenDatabase method passed to SQLDatabase, open the database file

Let's continue to look at that process:

[Java]View Plaincopy
  1. Final int version = Db.getversion ();
  2. if (version! = mnewversion) {
  3. if (db.isreadonly ()) {
  4. throw New Sqliteexception ("Can ' t upgrade read-only database from version" +
  5. Db.getversion () + "to" + Mnewversion + ":" + mname);
  6. }
  7. Db.begintransaction ();
  8. try {
  9. if (Version = = 0) {
  10. OnCreate (DB);
  11. } Else {
  12. if (Version > mnewversion) {
  13. Ondowngrade (db, version, mnewversion);
  14. } Else {
  15. Onupgrade (db, version, mnewversion);
  16. }
  17. }
  18. Db.setversion (mnewversion);
  19. Db.settransactionsuccessful ();
  20. } finally {
  21. Db.endtransaction ();
  22. }
  23. }

When we opened the database file, we began to operate, the main content of today's speech is the above judgment:

The current version of the database is obtained first, and when the version number is 0, the OnCreate method is executed (the version number is 0 when the database file is first created) If the version number is not 0 and is compared with the latest version number, if it is greater then the upgrade operation Onupgrade method is performed, otherwise the demotion Ondowngrade method is performed, but the demotion method implementation is simple:

Throws an exception directly, that is, the database does not allow the demotion operation, this also conforms to the normal situation.

All right. From the above analysis, we will summarize these two methods:

public abstract void OnCreate (Sqlitedatabase db);
public abstract void Onupgrade (Sqlitedatabase db,int oldversion,int newversion);


Sqliteopenhelper automatically detects whether the database file exists. If present, the database is opened, in which case the OnCreate () method is not called. If the database file does not exist, Sqliteopenhelper first creates a database file, opens the database, and finally calls the OnCreate () method. Therefore, the OnCreate () method is typically used to create a database build of tables, views, and so on in a newly created database.

This means that the OnCreate () method is called when the database file is first created.


First look at the construction method of the Sqliteopenhelper class and then explain when the OnUpdate () method is called.
Public Sqliteopenhelper (Context context,string name,cursorfactory factory,int version);
Where the name parameter represents the database file name (not including the file path), Sqliteopenhelper creates the database file based on the file name. Version indicates the release number of the database. If the current incoming database version number is higher than the last created or upgraded version number, Sqliteopenhelper calls the OnUpdate () method. That is, when the database is first created, there will be an initial version number. You can increase the version number and recreate them when you need to upgrade the tables, views, and so on in the database. Now summarize the OnCreate () and Onupgrade () call procedures.


1. If the database file does not exist, Sqliteopenhelper will call the OnCreate () method after the database is automatically created, and in this method it is common to create components such as tables, views, and so on. The database is generally empty before it is created, so you do not need to delete the related components in the database first.
2. If the database file exists and the current version number is higher than the last created or promoted version number, Sqliteopenhelper calls the Onupgrade () method, and the version number of the database is updated when the method is called. In addition to creating components such as tables, views, and so on, in the Onupgrade () method, these related components need to be removed before the Onupgrade () method is called, so the database is present and many database builds are restored.

Combining the two points above, a conclusion can be drawn:

If the database file does not exist, only OnCreate () is called (the method is called once when the database is created). If the database file exists, the Onupgrade () method is called to upgrade the database and update the version number.

OnCreate method and Onupgrade method in SQLite in Android--(GO)

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.