天天看點

LitePal(版本1.5.0,寫此部落格時是最新版本)一,概述二,配置LitePal1.5.0三,建立和更新資料庫四,使用LitePal添加資料五,使用LitePal更新資料 六,使用LitePal删除資料七,使用LitePal查詢資料(相對前面來說,查詢比較複雜,相對sql來說,還是挺簡單的)八,總結

一,概述

今天按慣例打開郭霖大神的微信公衆号,看看有沒有什麼幹貨之類的文章(其實郭神推送的文章都是滿滿的幹貨,嘻嘻)。然後發現郭神的LitePal竟然有了新版本,到了LitePal1.5.0,我的天啊,請允許我表達一下激動的心情。最初知道LitePal是在去年(好像是去年)翻郭神的部落格時看見了他寫的關于LitePal的專欄部落格,當時看那個部落格的時間是2015年以前的,也就沒在意,心想這技術肯定有點老了,不去了解也罷(從我的這個想法可以看出,我還是Too Young了)。去年郭神《第二行代碼》首發,我搶了一本簽名版(郭神的字好漂亮),書一到手上就迫不及待的翻了起來,然後在《第二行代碼》的第六章又邂逅了LitePal1.3.2,不知是忙還是懶,也沒有引起重視,連Demo都沒敲一個,真是服了自己,該打!終于在2017年三八婦女節的前一天,也就是傳說中的女生節(What節?)這一天,我決定不再錯過Litepal。

二,配置LitePal1.5.0

我使用的IDE是Android Studio2.2,如果正在看這篇部落格的你還在使用Eclipse搞Android開發,我強烈建議你馬上去安裝一個AS,使用AS開發Android是大勢所趨,好處也特别多。不多說,進入正題。如何配置LitePal1.5.0,可以參考GitHub上郭神給出的示例,連結在此 https://github.com/LitePalFramework/LitePal

首先,在AS中建立一個工程,在app/build.gradle檔案的dependencies閉包中添加一行内容:compile 'org.litepal.android:core:1.5.0',然後Sync Now同步一下。

接下來,右擊app/src/main目錄-->New-->Directory,建立一個assets目錄,然後在assets目錄下再建立一個litepal.xml檔案,将LitePal上的那一段代碼粘貼過來即可。LitePal.xml檔案裡面的内容如下:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <!--
        Define the database name of your application. 
        By default each database name should be end with .db. 
        If you didn't name your database end with .db, 
        LitePal would plus the suffix automatically for you.
        For example:    
        <dbname value="demo" />
    -->
    <dbname value="demo" />

    <!--
        Define the version of your database. Each time you want 
        to upgrade your database, the version tag would helps.
        Modify the models you defined in the mapping tag, and just 
        make the version value plus one, the upgrade of database
        will be processed automatically without concern.
            For example:    
        <version value="1" />
    -->
    <version value="1" />

    <!--
        Define your models in the list with mapping tag, LitePal will
        create tables for each mapping class. The supported fields
        defined in models will be mapped into columns.
        For example:    
        <list>
            <mapping class="com.test.model.Reader" />
            <mapping class="com.test.model.Magazine" />
        </list>
    -->
    <list>
    </list>

    <!--
        Define where the .db file should be. "internal" means the .db file
        will be stored in the database folder of internal storage which no
        one can access. "external" means the .db file will be stored in the
        path to the directory on the primary external storage device where
        the application can place persistent files it owns which everyone
        can access. "internal" will act as default.
        For example:
        <storage value="external" />
    -->

</litepal>
           

可以将這些注釋的東西看完之後統統删掉,留着也并沒什麼用。

最後,自己建立一個MyApplication.java繼承自Application類,并且在onCreate方法中初始化一下LitePal,一行代碼搞定,如下:

@Override
    public void onCreate() {
        super.onCreate();
        //初始化
        LitePal.initialize(this);
    }
           

并且還要在AndroidManifest.xml檔案中配置一下剛剛我們自己建立的MyApplication:

<application
        android:name=".application.MyApplication"
        ......
           

至此,Litepal的配置工作就完成了,接下來,去感受LitePal的強大之處吧。

三,建立和更新資料庫

先貼一個Java bean的代碼如下:

package com.bighuan.litepaldemo.model;

import org.litepal.crud.DataSupport;

/**
 * 項目名:  LitePalDemo
 * 包名:    com.bighuan.litepaldemo.model
 * 檔案名:  Phone
 * 作者:    LH
 * 郵箱:   [email protected]
 * 建立時間:2017/3/7 15:39
 * 描述:    手機bean
 */


public class Phone extends DataSupport {

    private int id;

    private String name; //手機名

    private float price;//價格

    private String brand;//品牌

    private double discount;//打折

    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 float getPrice() {
        return price;
    }

    public void setPrice(float price) {
        this.price = price;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getDiscount() {
        return discount;
    }

    public void setDiscount(double discount) {
        this.discount = discount;
    }
}
           

大家可以先忽略為什麼Phone繼承了DataSupport。估計大家也猜到了Phone類會對應到資料庫中的Phone表,而該類中的每一個字段對應表中一個列。你可能會有疑問,我資料庫都沒建呢?别急嘛,還記得litepal.xml這個檔案嗎,它要出場了。隻要在它裡面配置就行了,示例和解釋都如下:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <!--PhoneMall就是資料庫名,自己取名就可以了-->
    <dbname value="PhoneMall" />
    <!--下面的這個1表示版本,第一次就是1了-->
    <version value="1" />
    <!--Phone類也要添加到映射模型清單中,注意一定要是完整類名-->
    <list>
        <!--Phone類對應資料庫中的Phone表,将Phone類映射到模型清單中-->
        <mapping class="com.bighuan.litepaldemo.model.Phone"></mapping>
    </list>
</litepal>
           

接下來,隻要在代碼中建立資料庫即可。

使用建工程時預設的那個MainActivity,其對應的activity_main.xml裡面有5個按鈕,分别是建立資料庫,添加資料,更新資料,删除資料,查詢資料,代碼如下(其實也沒什麼好貼的):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.bighuan.litepaldemo.activity.MainActivity">

    <Button
        android:id="@+id/main_btn_create_db"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="建立資料庫"/>
    <Button
        android:id="@+id/main_btn_add_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加資料add"/>
    <Button
        android:id="@+id/main_btn_update_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="更新資料update"/>
    <Button
        android:id="@+id/main_btn_delete_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除資料delete"/>
    <Button
        android:id="@+id/main_btn_query_data"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查詢資料query"/>
</LinearLayout>
           

建立資料庫的點選事件:

//建立資料庫(我的天,這也太簡潔了吧)
      Connector.getDatabase();
           

當時我确實吃驚了,怎麼可以這麼簡單呢,但這就是LitePal的強大之處。

如果你覺得Phone表中還要增加字段,直接在Phone.java增加就可以了,然後将litepal.xml中的版本号加一即可,然後重新建立資料庫就可以。

四,使用LitePal添加資料

先貼代碼,然後解釋:

/**
     * 插入資料
     */
    private void addData() {
        //添加資料
        Phone phone = new Phone();
        phone.setId(001);
        phone.setName("小米mix");
        phone.setPrice(3999);
        phone.setBrand("小米");
        phone.setDiscount(0.95);

        phone.save();//1,主線程運作


       /* phone.saveAsync().listen(new SaveCallback() {
            @Override
            public void onFinish(boolean success) {
                if (success) {
                    Toast.makeText(MainActivity.this, "插入資料成功了", Toast.LENGTH_LONG).show();
                }
            }
        });//,2,子線程運作,并且所有異步操作回到onFinish()方法之後都會切回到主線程,厲害了*//*


        phone.saveOrUpdateAsync().listen(new SaveCallback() {
            @Override
            public void onFinish(boolean success) {
                Toast.makeText(MainActivity.this, "插入資料成功了", Toast.LENGTH_LONG).show();
            }
        });
        phone.saveOrUpdate("name=?", phone.getName());//已存在就更新,不存在就建立*/

    }
           

如果通過LitePal進行增删改查操作,必須讓我們的java bean繼承DataSupport類就可以啦,是以前面貼代碼時我繼承了DataSupport的原因。我們隻要new 一個Phone對象出來,設定好我們要插入的資料,然後直接phone.save();就OK了。但是在我注釋的代碼了還有phone.saveAsync().listen(...)這種代碼,這又代表什麼呢?前者是在主線程運作,後者是在子線程運作,但回調的onFinish()确實在主線程的,可以修改UI,這就厲害了,這也是LitePal1.5.0相比之前版本退出的重磅功能。之後介紹LitePal的更新資料方法也是這樣。當我們操作的資料過多時(如插入幾萬條資料)可能會阻塞主線程時,就有必要在子線程中操作了。在代碼中都有注釋,相信你們看的懂。接下來就是貼代碼了。

五,使用LitePal更新資料

/**
     * 更新資料
     */
    private void updateData() {
        Phone phone1 = new Phone();
        phone1.setName("小米note2");
        phone1.setPrice(2799);
        //phone1.updateAll("name = ? and price = ?","小米mix","3999");
        phone1.updateAllAsync("name = ? and price = ?", "小米mix", "3999").
                listen(new UpdateOrDeleteCallback() {
                    @Override
                    public void onFinish(int rowsAffected) {
                        Toast.makeText(MainActivity.this, "更新操作影響了" + rowsAffected + "行資料",
                                Toast.LENGTH_LONG).show();
                    }
                });
    }
           

六,使用LitePal删除資料

/**
     * 删除資料
     */
    private void deleteData() {
        DataSupport.deleteAllAsync(Phone.class, "price < ?", "2800").
                listen(new UpdateOrDeleteCallback() {
                    @Override
                    public void onFinish(int rowsAffected) {
                        Toast.makeText(MainActivity.this, "删除操作影響了" + rowsAffected + "行資料",
                                Toast.LENGTH_LONG).show();
                    }
                });
    }
           

七,使用LitePal查詢資料(相對前面來說,查詢比較複雜,相對sql來說,還是挺簡單的)

/**
     * 查詢資料,方法比較多
     */
    private void queryData() {
        //直接将Phone表中的所有資料查了出來
        List<Phone> phones = DataSupport.findAll(Phone.class);
        Log.d("MainActivity", phones.toString());

        //查詢第一條資料
        Phone firstPhone = DataSupport.findFirst(Phone.class);
        //最後一條
        Phone lastPhone = DataSupport.findLast(Phone.class);

        //通過select()方法查找資料,隻查name,price兩列資料
        List<Phone> phones1 = DataSupport.select("name", "price").find(Phone.class);

        //通過where指定限制條件,查詢價格大于2800的手機
        List<Phone> phones2 = DataSupport.where("price > ? ", "2800").find(Phone.class);

        //order()方法,示例是将查詢結果按價格由低到高排序,預設就是asc,desc則是相反
        List<Phone> phones3 = DataSupport.order("price asc").find(Phone.class);
        //隻查前四條資料
        List<Phone> phones4 = DataSupport.limit(5).find(Phone.class);

        //還可以通過offset()來指定偏移量,示例表示查到了第3,4,5條資料
        List<Phone> phones5 = DataSupport.limit(3).offset(2).find(Phone.class);

        //同時也可以将以上的的幾個方法任意的連綴組合進而完成複雜的查詢操作
        DataSupport.select("name", "price", "discount")
                .where("price > ?", "2800")
                .order("id")
                .limit(5)
                .offset(5)
                .find(Phone.class);
    }
           

八,總結

LitePal這麼強大,肯定還有一些功能沒介紹到,大家可以去關注郭霖大神的部落格專欄,微信公衆号(每個工作日都有幹貨文章哦),GitHub首頁。寫這篇部落格竟然花了我幾小時時間,也挺值得的,希望自己可以堅持寫一些技術部落格吧!再見啦!

繼續閱讀