Android使用LitePal數(shù)據(jù)庫框架

LitePal是一個便于開發(fā)者使用SQLite的Android框架,極大的簡化了SQLite的使用,這是它的github地址
https://github.com/LitePalFramework/LitePal

初期準(zhǔn)備

1.導(dǎo)入

在build.gradle中加入依賴

dependencies {
    compile 'org.litepal.android:core:1.6.1'
}
2.配置litepal.xml

在app/src/main下新建文件夾assets,在該文件夾下new->Android resource file新建一個xml文件命名為litepal,復(fù)制以下內(nèi)容到這個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>
  • dbname 該數(shù)據(jù)庫的名字
  • version 該數(shù)據(jù)庫的版本
  • list 配置映射類
  • storage 配置數(shù)據(jù)的儲存位置,只有internal和external兩個值
3.配置 LitePalApplication

為便于使用,避免不必要的參數(shù)傳遞,在AndroidManifest.xml中作如下配置

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

然后在Application中初始化

public class MyOwnApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        LitePal.initialize(this);
    }
    ...
}

使用

1.創(chuàng)建數(shù)據(jù)表

定義一個類,類名為表名,成員變量為表中各個屬性,為便于操作,需繼承自DataSupport,假如有Album和Song兩個表

public class Album extends DataSupport {
    
    @Column(unique = true, defaultValue = "unknown")
    private String name;
    
    private float price;
    
    private byte[] cover;
    
    private List<Song> songs = new ArrayList<Song>();

    // generated getters and setters.
    ...
}
public class Song extends DataSupport {
    
    @Column(nullable = false)
    private String name;
    
    private int duration;
    
    @Column(ignore = true)
    private String uselessField;
    
    private Album album;

    // generated getters and setters.
    ...
}

然后在litepal.xml中的<List> </list>中添加

<list>
    <mapping class="org.litepal.litepalsample.model.Album" />
    <mapping class="org.litepal.litepalsample.model.Song" />
</list>

這樣在下次操作數(shù)據(jù)庫的時候就會生成這個表。
得到數(shù)據(jù)庫:

SQLiteDatabase db = LitePal.getDatabase();
2.更新數(shù)據(jù)表

只需要改變該類的成員變量,然后改變litepal.xml中的verson值及可更新數(shù)據(jù)表

<!--
    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>
-->
<version value="2" ></version>
3.添加數(shù)據(jù)

為該數(shù)據(jù)表添加數(shù)據(jù)只需新定義一個對象,然后調(diào)用save()就可以添加

Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.save();                    //svae()方法
Song song1 = new Song();
song1.setName("song1");
song1.setDuration(320);
song1.setAlbum(album);
song1.save();                     //svae()方法
Song song2 = new Song();
song2.setName("song2");
song2.setDuration(356);
song2.setAlbum(album);
song2.save();                    //svae()方法
4.更新數(shù)據(jù)

調(diào)用find()找到id為i的該行數(shù)據(jù),然后改變相應(yīng)值,調(diào)用save()即可更新該行數(shù)據(jù)
id為數(shù)據(jù)表創(chuàng)建時自動添加的一個屬性

Album albumToUpdate = DataSupport.find(Album.class, 1);
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.save();

如果想一次修改多條數(shù)據(jù),調(diào)用updateAll();

Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.updateAll("name = ?", "album");
5.刪除數(shù)據(jù)

刪除單條,用delete()

DataSupport.delete(Song.class, id);

刪除多條

DataSupport.deleteAll(Song.class, "duration > ?" , "350");
6.查找數(shù)據(jù)

查找單條數(shù)據(jù)(根據(jù)id)

Song song = DataSupport.find(Song.class, id);

查找所有數(shù)據(jù)

List<Song> allSongs = DataSupport.findAll(Song.class);

按條件查找并排序

List<Song> songs = DataSupport.where("name like ? and duration < ?", "song%", "200").order("duration").find(Song.class);
7.異步操作

每次數(shù)據(jù)庫操作默認(rèn)是在main thread操作的,如果有耗時查詢,需要用異步操作findAllAsync(),存儲用saveAsync()
操作結(jié)果在onFinish()回調(diào),

DataSupport.findAllAsync(Song.class).listen(new FindMultiCallback() {
    @Override
    public <T> void onFinish(List<T> t) {
        List<Song> allSongs = (List<Song>) t;
    }
});
Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
album.setCover(getCoverImageBytes());
album.saveAsync().listen(new SaveCallback() {
    @Override
    public void onFinish(boolean success) {

    }
});
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,505評論 6 533
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,556評論 3 418
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,463評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,009評論 1 312
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 71,778評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,218評論 1 324
  • 那天,我揣著相機(jī)與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,281評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,436評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,969評論 1 335
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 40,795評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 42,993評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,537評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 44,229評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,659評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,917評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,687評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 47,990評論 2 374

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 134,785評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,660評論 25 708
  • 路遙知馬力,日久見人心。是古人見證朋友友誼的金玉良言,千古年來被人們借鑒、使用和警策。。時間流逝,人們的性格、脾氣...
    魚團(tuán)長閱讀 141評論 0 0
  • 今天初八,離國家法定的上班時間已經(jīng)是第二天了,我迫不及待趕到回龍觀眾創(chuàng)空間上班,四處一片蕭條,連餐飲也很多沒有開業(yè)...
    知秋姐閱讀 226評論 0 0