Litepal Basics of Android Database Framework Learning (i) __ Database

Source: Internet
Author: User
Tags sqlite

Android's own database has a sqlite, but usually development time if we need the table structure is very complex, so some business logic and version upgrade using SQLite is not convenient, usually we will encapsulate a framework or with some open source framework to operate the database, Today I will introduce a lightweight database litepal, if you are interested in SQLite, you can go here to download jar bag and source code. Article from Http://blog.csdn.net/guolin_blog/article/details/38083103,Thank you. Let's begin today's story. first, SQL command simple to use

To facilitate our viewing of the information in a moment, you can add a record to your address book now.


①. Open a Command line window to display the currently available devices: ADB devices

②. Into shell mode: adb shell (Note: Please use the root phone or simulator, if multiple devices are connected please use ADB-S device name shell, #代表有Root权限)


③. Then enter the specified directory: CD data/data/com.android.providers.contacts/databases

④. View the current directory content: LL


⑤. Open database: Sqlite3 contacts2.db

⑥. View table:. Table


⑦. Enter line mode:. Mode line (can be used to format the display of the table structure)

⑧. Display table structure: pragma table_info (accounts); (pragma table_info (table name))


⑨. View the data in the table: SELECT * from data; (Basic SQL statement for viewing data in the database table)

The SQL command is simple to use. Finally we'll see the data we added to our address book.
ii. Basic usage of Litepal

Litepal Introduction: Litepal is an open source of the Android database framework, which uses object-relational mapping (ORM) model, and we usually develop the most commonly used in the database functions are encapsulated, so that without writing a line of SQL statements can complete a variety of tables, The operation of the censored check. And Litepal is very "light", jar bag only 100k not to, below we through a simple demo to understand Litepal.

①. Open Android Studio new module (or create a new Android project with ADT) The project directory structure is as follows.


② we've said before. Litepal is based on object-relational mapping, which is to automatically map objects to table relationships with object-oriented thinking. First, we create a new person class in the domain package

public class Person {

    //id field can not write
    private int id;

    private String name;
    private int age;

    As long as it is not private, it will not automatically map the
    protected String sex;

    public int getId () {return
        ID;
    }

    public void setId (int id) {
        this.id = ID;
    }

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    public int getage () {return age
        ;
    }

    public void Setage (int age) {
        this.age = age;
    }

    Public String Getsex () {return
        sex;
    }

    public void Setsex (String sex) {
        this.sex = sex;
    }
}
There are 2 points to note:

1. ID field can not be written, the system will automatically add on.
2. If the modifier is not private, it is not automatically mapped to the table.
③. Create a new assets directory under the src/main/directory, create a new litepal.xml configuration file

<?xml version= "1.0" encoding= "Utf-8"?>
<litepal>
	<dbname value= "Demo" ></dbname>
	<version value= "1" ></version>
	<list>
		<mapping class= " Com.example.litepaldemo.domain.Person "></mapping>
	</list>
</litepal>
The name of the database configured in this profile is demo, the version number is 1, and the person entity class is mapped to the table.

④. We can create a database by calling the following line of code in mainactivity.

Sqlitedatabase db = Connector.getdatabase ();
Finally, we went to the database and looked at the table we created.


At this point, the basic usage of Litepal has been introduced, and then we look at the Litepal upgrade (using SQLite upgrade or more cumbersome, if the upgrade is too frequent, you need to write a long switch in the Onupgrade method) three, Use the Litepal upgrade table ①. Add Table

Create a new student class, and then configure the following code in Litepal.xml

public class Student {
    private String ID;
    private String name;
    private int age;
    Private String School;

    Public String GetId () {return
        ID;
    }

    public void SetId (String id) {
        this.id = ID;
    }

    Public String GetName () {return
        name;
    }

    public void SetName (String name) {
        this.name = name;
    }

    public int getage () {return age
        ;
    }

    public void Setage (int age) {
        this.age = age;
    }

    Public String Getschool () {return
        school;
    }

    public void Setschool (String school) {
        this.school = school;
    }
}

<?xml version= "1.0" encoding= "Utf-8"?>
<litepal>
    <dbname value= "Demo" ></dbname>

    <version value= "2" ></version>

    <list>
        <mapping class= " Com.example.litepaldemo.domain.Person "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.Student "></mapping>
    </list>
</litepal>
We use the command to check the current database for a few tables

Looking at the person table, we can see that there is no sex column because the sex column is not private decorated


②. Adding columns

We're going to add a column to the student table, first we open the Student class, add a private test field, and provide the get and set methods

Then change the value of the version label in the Litepal.xml file to 3, rerun the program, and get the following results.


③. Delete Column

Remove the test field and get and set methods in the Student class, change the value of the version label in Litepal.xml to 4, and rerun the program with the following results.


Note: SQLite itself does not support deleting columns, Litepal deletes the column principle by renaming the student table to a temporary table and then generating a new student table based on the structure of the latest student class, and then copying data in the temporary table except test to the new table. Finally, delete the temporary form.

Believe that the above explanation, we can intuitively feel the use of Litepal to deal with the problem of the upgrade of the database convenient place.

three. there are three types of association between tables and tables associated with Litepal: one-to-one, Many-to-many, Hedo to multiple
Three types of implementations corresponding to:
How to implement one-to-one association with foreign keys
The implementation of a Many-to-many association using foreign keys
The implementation of multi-Many-to-many association using the intermediate table
Handle three types of associations in an object-oriented way:
One-to-one: On either side of the entity class corresponding to the two tables, reference another entity class.
Multi-pair: Use a list to encapsulate multiple parties in one entity and then refer to one entity in multiple entities.
Many-to-many: An entity that uses the list collection to refer to the other side of the two-table-corresponding entity.
To give a simple Lezilai of the above relationship, we find this phenomenon in the use of news software, and each piece of news will only correspond to one profile so that we can see the news and the briefing Table (Introduction) as one-to-one relationships. Every other piece of news can have multiple comments, so that we can look at the news and the comment table (Comment) as a one-to-many relationship. There is also the possibility that every piece of news can be seen in a different category, and that there will be more than one news in each category, so that we can see that the news and the category table (Category) are a many-to-many relationship. Here we use code to describe the associations between these tables.

One-on-one

①. New news entity class, automatically generate get Set method

private int id;
Private String title;
Private String content;
private int commentcount;
Private Date publishdate;
Private Introduction mintroduction;
②. New introduction entity class, automatically generate get Set method

private int id;
Private String Guide;
Private String Digest;
private int news_id;
③. Edit Assets Directory Litepal.xml file, upgrade version number, reference class

<litepal>
    <dbname value= "Demo" ></dbname>
    <version value= "5" ></version>
    <list>
        <mapping class= "Com.example.litepaldemo.domain.Person" ></mapping>
        < Mapping class= "com.example.litepaldemo.domain.Student" ></mapping>
        <mapping class= " Com.example.litepaldemo.domain.Introduction "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.News "></mapping>
    </list>
</litepal>
After three steps to complete a one-to-one association of tables, let's look at whether there are news_id associations in the table


A pair of many

①. New comment entity class, automatically generate get Set method

  private int id;
    Private String content;
    Private Date publishdate;
    private int news_id;

②. Use the list collection in the news entity to wrap the comment entity, form a one-to-many relationship, and automatically generate a get-set method

    private int id;
    Private String title;
    Private String content;
    private int commentcount;
    Private Date publishdate;

    Private Introduction mintroduction;
    

③. Upgrade the version number in Litepal.xml and introduce the entity bean

<litepal>
    <dbname value= "Demo" ></dbname>
    <version value= "6" ></version>

    <list>
        <mapping class= "Com.example.litepaldemo.domain.Person" ></mapping>
        < Mapping class= "com.example.litepaldemo.domain.Student" ></mapping>
        <mapping class= " Com.example.litepaldemo.domain.Introduction "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.News "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.Comment "></mapping>
    </list>
</litepal>
After three steps to complete a One-to-many association of tables, let's look at whether this association exists in the table


many to many

①. New entity class category, automatically generate Get Set method

private int id;
private String name;
Private list<news> newslist = new arraylist<news> ();
②. Use the list collection to wrap category in the news entity class and automatically generate get Set methods

    private int id;
    Private String title;
    Private String content;
    private int commentcount;
    Private Date publishdate;

    Private Introduction mintroduction;
    Private list<comment> commentlist = new arraylist<comment> ();
    Private list<category> categorylist = new arraylist<category> ();
③. Modify Litepal.xml File
<litepal>
    <dbname value= "Demo" ></dbname>
    <version value= "7" ></version>
    <list>
        <mapping class= "Com.example.litepaldemo.domain.Person" ></mapping>
        < Mapping class= "com.example.litepaldemo.domain.Student" ></mapping>
        <mapping class= " Com.example.litepaldemo.domain.Introduction "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.News "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.Comment "></mapping>
        <mapping class=" Com.example.litepaldemo.domain.Category "></mapping>
    </list>
</litepal>
After the above three steps to complete the table Many-to-many Association, let's go to see if there is this association in the table



The above is how we use the Litepal framework to handle the relationships between tables.

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.