Litepal的用法以及dbname is empty的解決

要使用Litepal的步驟如下:
1.引入JAR包以及更改配置
使用Android Studio在項目的build.gradle中添加:
dependencies {
compile 'org.litepal.android:core:1.6.1'
}

其中1.6.1是版本號,可以根據需求改變。
然後配置litepal.xml文件,一般先在app/src/main目錄下新建一個assets 目錄,然後在其下面創建一個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="CourseManager" />

    <!--
        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="6" />

    <!--
        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" />
        <st>
    -->
    <list>
        <mapping class = "com.example.qr_code.QR"/>
        </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 is empty 或者空指針異常,這是因爲你的Litepal.xml文件有問題,乍一看沒錯,只要使用這一段就沒問題了,別問我爲什麼,我也不知道。
之後就是創建一個class,也就是你數據庫裏面的表,在上面的xml文件中的標籤中添加這個類的絕對路徑。這樣你就生成了自己的表.
在實際的數據庫操作中一旦你對這個數據庫有操作,在沒有數據庫的時候,他會自行創建。
當然我們還需要在AndroidManifest.xml文件中配置一下。
<application
android:name="org.litepal.LitePalApplication">
</application>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章