Android常用开源库———————————LitePal的使用方法

LitePal是一款开源Android数据库框架,采用了对象关系映射的模式,

详细的使用文档见LitePal项目的Github主页

快速设置步骤:

1. Include library

Edit your build.gradle file and add below dependency.

If you program with Java:

dependencies {
    implementation 'org.litepal.android:java:3.0.0'
}

 

2. Configure litepal.xml

Create a file in the assets folder of your project and name it as litepal.xml. Then copy the following codes into it.

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="demo" />

    <version value="1" />

    <list>
    </list>
</litepal>

This is the only configuration file, and the properties are simple.

  • dbname configure the database name of project.
  • version configure the version of database. Each time you want to upgrade database, plus the value here.
  • list configure the mapping classes.
  • storage configure where the database file should be stored. internal and external are the only valid options.

3. Configure LitePalApplication

You don't want to pass the Context param all the time. To makes the APIs simple, just configure the LitePalApplication in AndroidManifest.xml as below:

<manifest>
    <application
        android:name="org.litepal.LitePalApplication"
        ...
    >
        ...
    </application>
</manifest>

 

定义一个Book类

public class Book extends DataSupport{
    private int id;
    private String author;
    private double price;
    private int pages;
    private String name;
    private String press;

    public int getId() {
        return id;
    }

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

    public String getAuthor() {
        return author;
    }
  ...
}

 

Lite升级数据库,只需修改想改的内容,然后将版本号加1即可。如添加了新的模型类,还需将它添加到映射模型列表中。

    <list>
        <mapping class="com.example.litepaltest.Book"></mapping>
        <mapping class="com.example.litepaltest.Category"></mapping>
    </list>

LitePal进行CRUD操作,模型类需要继承DataSupport

使用LitePal添加数据

  public void onClick(View v) {
       Book book = new Book();
       book.setName("The Da Vinci Code");
       book.setAuthor("Dan Brown");
       book.setPages(454);
       book.setPrice(16.96);
       book.setPress("Unknown");
       book.save();
  }

 

使用LitePal更新数据

                Book book = new Book();
                book.setPrice(14.95);
                book.setPress("Anchor");
                book.updateAll("name = ? and author = ?", "The Lost Symbol", "Dan Brown");

 

使用LitePal删除数据

调用过save()方法的对象或者通过LitePal提供的查询API查询出来的对象,可以直接使用delete。或者可以使用以下方式:

DataSupport.deleteAll(Book.class, "price < ?", "15")

 

使用LitePal查询数据

List<Book> books = DataSupport.findAll(Book.class);

 

常用的查询API

List<Book> books = DataSupport.select("name",  "author").find(Book.class);

List<Book> books = DataSupport.where("pages > ?”, “400").find(Book.class);

 

 

posted @ 2018-11-22 12:23  kyun  阅读(262)  评论(0编辑  收藏  举报