Android Learning Notes (16)--Database operations (top)

Source: Internet
Author: User

This series is the "first line of Android Code" Learning notes, if there are errors and omissions, please correct me!

Android in order to make it easier for us to manage the database, we specifically provide a Sqliteopenhelper helper class, which allows us to easily create and upgrade the database. First, since Sqliteopenhelpe is an abstract class, we need to create a class to inherit from it. There are two abstract methods in Sqliteopenhelper, namely OnCreate () and Onupgrade (), we must rewrite the two methods in our helper class, and then implement the logic of creating and upgrading the database separately in these two methods. There are also two very important example methods in Sqliteopenhelper, Getreadabledatabase () and getwritabledatabase (). Both of these methods can create or open an existing database (open directly if the database already exists, otherwise create a new database) and return an object that can read and write to the database. The difference is that when the database is not writable (such as disk space is full) the object returned by the Getreadabledatabase () method will open the database in a read-only manner, and the Getwritabledatabase () method will have an exception.

There are two construction methods in Sqliteopenhelper that can be overridden, typically using a less-parametric construction method. This construction method receives four parameters, the first parameter is the Context, this has nothing to say, must have it to operate the database. The second parameter is the database name, which is the name specified here when the database is created. The third parameter allows us to return a custom Cursor when querying the data, usually passing null. The fourth parameter represents the version number of the current database and can be used to perform an upgrade operation on the database. Let's try out the use of the database.


First, the new Mydatabasehelper class inherits from the Sqliteopenhelper:

1  Public classMydatabasehelperextendsSqliteopenhelper {2      Public Static FinalString create_book = "CREATE table book ("3+ "ID integer primary key autoincrement,"4+ "Author text,"5+ "Price Real,"6+ "pages integer,"7+ "Name text");8     PrivateContext Mcontext;9      PublicMydatabasehelper (Context context, String name, Sqlitedatabase.cursorfactoryTenFactoryintversion) { One         Super(context, name, Factory, version); AMcontext =context; -     } - @Override the      Public voidonCreate (Sqlitedatabase db) { - Db.execsql (create_book); -Toast.maketext (Mcontext, "Create succeeded", Toast.length_short). Show (); -     } + @Override -      Public voidOnupgrade (Sqlitedatabase db,intOldversion,intnewversion) { +     } A}

We defined the build statement as a string constant, then called the Sqlitedatabase Execsql () method in the OnCreate () method to execute the build statement and popped a toast prompt to create the success, This ensures that the Book table can be created successfully while the database is being created.

Second, write the layout file:

1 <Relativelayoutxmlns:android= "Http://schemas.android.com/apk/res/android"2 Xmlns:tools= "Http://schemas.android.com/tools"Android:layout_width= "Match_parent"3 Android:layout_height= "Match_parent"Android:paddingleft= "@dimen/activity_horizontal_margin"4 Android:paddingright= "@dimen/activity_horizontal_margin"5 Android:paddingtop= "@dimen/activity_vertical_margin"6 Android:paddingbottom= "@dimen/activity_vertical_margin"Tools:context=". Mainactivity ">7 8     <Button9         Android:id= "@+id/create_database"Ten Android:layout_width= "Match_parent" One Android:layout_height= "Wrap_content" A Android:text= "Create database" -         /> - </Relativelayout>
View Code

We have added a button to the interface to create the database.

Third, modify the code in the mainactivity:

1  Public classMainactivityextendsappcompatactivity {2 3     PrivateMydatabasehelper DBHelper;4 @Override5     protected voidonCreate (Bundle savedinstancestate) {6         Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_main);8DBHelper =NewMydatabasehelper ( This, "Bookstore.db",NULL, 1);9Button CreateDatabase =(Button) Findviewbyid (r.id.create_database);TenCreatedatabase.setonclicklistener (NewView.onclicklistener () { One @Override A              Public voidOnClick (View v) { - dbhelper.getwritabledatabase (); -             } the         }); -     } -}
View Code

We built a Mydatabasehelper object in the OnCreate () method and specified the database name as Bookstore.db through the constructor's parameters, the version number was specified as 1, and then called in the Click event of the Create database button. Getwritabledatabase () method. So when the first click on the Create Database button, it will detect that the current program does not have the bookstore.db, so the database will be created and call Mydatabasehelper in the OnCreate () method, so The Book table is created and then a toast prompt is created to create the success. When you click the Create Database button again, you will see that there are already bookstore.db databases, so it will not be created again.

The program runs as follows:

  

At this point, you can see that bookstore has been created in com.mycompany.database/databases:

  

There are two database files in this directory, one is the bookstore.db that we created, and the other bookstore.db-journal is the temporary log file that is generated to allow the database to support transactions, typically the size of this file is 0 bytes.

End.

Android Learning Notes (16)--Database operations (top)

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.