Android Database Master cheats (ii)--basic usage of creating tables and Litepal

Source: Internet
Author: User

Reprint Please specify source: http://blog.csdn.net/guolin_blog/article/details/38556989

In the previous article we learned some basic knowledge about the Android database, and a few useful sqlite commands, all directly on the command line. But we all know that the database is to be used in conjunction with the program, a separate database to do the addition and deletion of the operation does not make any sense, so today we will learn how to operate in the Android program SQLite database, have not read the previous article friends can first refer to Android Database Master cheats (a)--sqlite command .

The first step in manipulating the database is, of course, creating tables, and the traditional way to create tables is to believe that most people know, so today I will show you the basic usage of this framework, and use it to do the same litepal, using the framework to manipulate the database.

So let's start with a brief introduction, Litepal is an open-source Android database framework that uses an object-relational mapping (ORM) pattern, and encapsulates some of the database features that we usually use most often during development, so that you can do all kinds of tables without writing a single line of SQL statements. The operation of the inspection and deletion. And the Litepal is "light", the jar package only 100k, and nearly 0 configuration, this and hibernate such a framework is very different. At present, the source of Litepal has been hosted on GitHub, the address is https://github.com/LitePalFramework/LitePal.

OK, a brief introduction of Litepal, let's take a look at the traditional Android development, how to create a table.

The traditional way of building a table

In fact, to facilitate our management of database tables, Android itself provides a helper class: Sqliteopenhelper. This class set creates and upgrades the database in one, and automatically manages the database version, which is a very useful tool.

Let's try Sqliteopenhelper's usage now. First you need to know that Sqliteopenhelper is an abstract class, which means that if we want to use it, we need to create our own helper class to inherit 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. This article only needs to focus on the creation of the database here is OK, upgrade the database we will discuss in the next article.

Create a new Mysqlitehelper class and let it inherit sqliteopenhelper, so the code for the most basic database helper class is as follows:

public class Mysqlitehelper extends Sqliteopenhelper {public Mysqlitehelper (context context, String name, Cursorfactory F Actory,int version) {Super (context, name, Factory, version);} @Overridepublic void OnCreate (Sqlitedatabase db) {} @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {}}
In this case, the OnCreate () method is called when the database is created, where it is possible to perform a table-building operation. For example, if we want to create a new news list with Title,content,publishdate,commentcount columns that represent news headlines, news content, release times, and comments, the code can be written like this:
public class Mysqlitehelper extends Sqliteopenhelper {public static final String create_news = "CREATE table NEWS (" + "ID Integer PRIMARY key AutoIncrement, "+" title text, "+" content text, "+" Publishdate Integer, "+" Commentcount integer) ";p u Blic Mysqlitehelper (Context context, String name, cursorfactory factory,int version) {Super (context, name, factory, Versi ON);} @Overridepublic void OnCreate (Sqlitedatabase db) {db.execsql (create_news);}    ...}
As you can see, we define the build statement as a constant, and then execute the table statement in the OnCreate () method, and the news list is created successfully. This statement is simple, but it contains some small details, let me explain. First, depending on the paradigm requirements of the database, any table should have a primary key, so here we add a self-growing ID column and set it as the primary key. Then the title column and the content column are string types, and the Commentcount column is integer, which is well understood, but how is the publishdate column designed? Since SQLite does not support storing dates for this type of data, we need to convert the date to UTC time (as of January 1, 1970 0 o'clock) and then store it in the database, so the Publishdate column should also be integral.

Now, we just need to get to the instance of Sqlitedatabase, and the database table will be created automatically, as follows:

Sqliteopenhelper dbhelper = new Mysqlitehelper (This, "demo.db", NULL, 1); Sqlitedatabase db = Dbhelper.getwritabledatabase ();

It's simple and convenient, isn't it? Then you are so easily satisfied, let's learn the basic usage of litepal, and see how this framework is used to achieve the same functionality.

Basic usage of Litepal

Although Litepal claims to be near the 0 configuration, but it is only "near", it still needs to do some simple configuration to be able to use, then we first quickly learn the Litepal configuration method.

Quick Configuration

1. Introduction of jar packages or source code

First we need to introduce the Litepal jar package into the project, you can click here to see the latest version of Litepal, select the download you need. Once you have downloaded the jar package, copy it to the project's Libs directory, even if it was successful, as shown in:


If you do not want to use the jar package, you can also download the Litepal source code, and then as a library to import into the eclipse, and then let our project to refer to the library.

2. Configure Litepal.xml

Next, create a new Litepal.xml file under the project's assets directory and copy the following code in:

<?xml version= "1.0" encoding= "Utf-8"?><litepal> <dbname    value= "Demo" ></dbname>    <version value= "1" ></version>    <list>    </list></litepal>
The configuration file is quite simple,<dbname> used to set the database name,<version> used to set the database version number,<list> used to set all the mapping model, we will use later.

3. Configure Litepalapplication

Because the context is needed to manipulate the database, and we obviously don't want to go through this parameter in every interface, it's too tedious to manipulate the database. Therefore, Litepal uses a method to simplify the context of this parameter, only need to configure the litepalapplication in Androidmanifest.xml, all the database operations will not be passed the context, as follows:

<manifest>    <application        android:name= "org.litepal.LitePalApplication" ...    > ...    </application></manifest>
Of course, some programs may have their own application and have been configured here. For example, there is a MyApplication, as follows:
<manifest>    <application        android:name= "com.example.MyApplication" ...    > ...    </application></manifest>
No relationship, then only need to modify the MyApplication inheritance structure, so that it does not directly inherit the application class, but inherit the Litepalapplication class, you can use everything can work properly, the code is as follows:
public class MyApplication extends Litepalapplication {    ...}

However, some programs may encounter more extreme situations, such as myapplication need to inherit another anotherapplication, and the anotherapplication is still in the jar package, cannot modify its code. This should be a relatively rare situation, but if you come across it is not urgent, there is still an explanation. You can download the source code of Litepal, and then copy the SRC directory directly under the SRC directory of your project, then open the Litepalapplication class, the inheritance of its structure to inherit from Anotherapplication, Let MyApplication inherit from Litepalapplication, so that all application can work together properly.

In just three steps, we have all the configuration work done, and this is a discriminating ears thing, since then you can happily experience the various conveniences offered by Litepal, let's start with the table.

Start building a table

As mentioned earlier in the introduction, Litepal takes the object-relational mapping (ORM) pattern, then what is Object-relational mapping? Simply put, we use the programming language is object-oriented language, and we use the database is a relational database, then the object-oriented language and relationship-oriented database to establish a mapping relationship, which is the object relationship mapping.

But why should we use the object-relational mapping model? This is mainly because most programmers are good at object-oriented programming, but only a small number of people are more proficient in relational databases. And the database of the SQL language is obscure, even if you are proficient in it, I am afraid I do not like to often write in the code it? The object-relational mapping model solves this problem very well, allowing us to manipulate the database in an object-oriented way, freeing it from the obscure SQL language.

So let's take a look at how the table is built in Litepal. According to the concept of object-relational mapping mode, each table should correspond to a model, that is, if we want to build a news table, there should be a corresponding news model class. Create a new news class, as follows:

Package Com.example.databasetest.model;public class News {}
Then, each column in the table actually corresponds to a field in the model class, such as the list of IDs, title, content, Publishdate, and Commentcount in the news table, then there should be several fields in the news class, as shown in the following code:
public class News {private int id;private string title;private string content;private Date publishdate;private int Comment count;//Auto-Generate GET, set method ...}
Where ID This field can write not write, because even if you do not write this field, Litepal will automatically generate an ID column in the table, after all, every table must have a primary key.

Here I would like to highlight that the mapping rules of Litepal are very lightweight, unlike some other database frameworks, all mappings of xml,litepal that need to be configured separately for each model class are automatically completed. Depending on the data type of Litepal, there are 8 types of data that can be mapped to an object relationship, int, short, long, float, double, Boolean, String, and date. As long as the fields declared into these 8 data types are automatically mapped to the database tables, no additional configuration is required.

Then some friends may ask, since it is automatic mapping, if there is a string field in the news class I do not want to map it to the database table, what should I do? Litepal also employs a very lightweight solution, where only fields declared as private modifiers are mapped to database tables, and if you have a field that you do not want to map, just change it to public, The protected or default modifier is available.

Now that the model class has been built, we are still in the final step of configuring it in the Map list. Edit the Litepal.xml file in the assets directory and add the news model class declaration to the <list> tab:

<?xml version= "1.0" encoding= "Utf-8"?><litepal> <dbname    value= "Demo" ></dbname>    <version value= "1" ></version>    <list>        <mapping class= " Com.example.databasetest.model.News "></mapping>    </list></litepal>
Note that you must fill in the full class name of the news class here.

OK, so all the work is done, and now as long as you have any action on the database, the news list will be created automatically. For example, Litepal provides a convenient way to obtain an instance of Sqlitedatabase, as follows:

Sqlitedatabase db = Connector.getdatabase ();
Call the above code, the news table should have been created successfully. We use the SQLite command we learned in the previous article to look at it, open the Demo.db database, enter the. Table command, and the results are as follows:


As you can see, the news table already exists. The other two sheets of android_metadata and Table_schema are automatically generated, and we don't have to. We can then look at the statement of the news table, as shown in the following list:


This is the litepal that is automatically generated by the fields in the news class, which also shows that the table operation has been completed successfully.

Well, so far you've been a bit of a primer on Litepal's usage, so here's what this article is about, and in the next article we'll learn how to use Litepal to upgrade tables.

Android Database Master cheats (ii)--basic usage of creating tables and Litepal

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.