2016-12-20 19 views
0

我試圖創建一個檢查日期的申請,引用的時候太陽下山,從預加載數據庫,且在此之前輸出報警90分鐘。不太具體(也可能與您更相關),我試圖編寫一個應用程序,該應用程序隨附預填充的信息數據庫,可根據需要訪問它。在Android開發中有多個使用SQLite的教程,但他們都假設你正在創建數據庫,而應用程序正在運行並嘗試輸入用戶確定的數據;我找到的唯一一個教程是從2009年開始的,自那時以來有一些更新使得無法使用(我認爲;無論它在Android Studio中肯定無法使用)。所有關於此問題的其他問題都被標記爲重複項,並引用回一個非常古老的問題,並回答 - 您猜對了 - 同樣過時的教程。 This是我正在討論的教程,如果它有幫助的話;不知道會不會,但它可能會。試圖預裝SQLite數據庫到Android應用

編輯:爲什麼關閉呢?我在我的問題中提到,這個問題有技術上以前已經回答,但它都鏈接回到一個過時的,不相關的教程,根本沒有幫助。這個問題以前可能已經提出過,但答案已經改變。

回答

1

Use SQLiteAssetHelper。您添加一個庫,創建一個SQLiteAssetHelper(而不是正常的SQLiteOpenHelper)的子類,並將您的數據庫置於assets/

因此,例如,在this sample app,我添加庫中app/build.gradle

compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:2.0.1' 

DatabaseHelper延伸SQLiteAssetHelper

/*** 
    Copyright (c) 2008-2012 CommonsWare, LLC 
    Licensed under the Apache License, Version 2.0 (the "License"); you may not 
    use this file except in compliance with the License. You may obtain a copy 
    of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required 
    by applicable law or agreed to in writing, software distributed under the 
    License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS 
    OF ANY KIND, either express or implied. See the License for the specific 
    language governing permissions and limitations under the License. 

    From _The Busy Coder's Guide to Android Development_ 
    https://commonsware.com/Android 
*/ 

package com.commonsware.android.dbasset; 

import android.content.Context; 
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; 

class DatabaseHelper extends SQLiteAssetHelper { 
    static final String TITLE="title"; 
    static final String VALUE="value"; 
    static final String TABLE="constants"; 
    private static final String DATABASE_NAME="constants.db"; 

    public DatabaseHelper(Context context) { 
    super(context, DATABASE_NAME, null, 1); 
    } 
} 

而且我的數據庫is in app/src/main/assets/databases/

一切從有別的就像在Android中正常使用的SQLite。第一次運行應用程序時,數據庫會自動從資產中解壓縮。

+0

嗯,這工作得很好。猜猜我應該多看看盒子外面。快速說明問題,因爲我對Android有點新,在下載並解壓縮之後,我會在哪裏放置SQLiteAssetHelper文件? – Jacob

+0

@Jacob:「在下載並解壓縮SQLiteAssetHelper文件後,我應該在哪裏放置它?」 - 我不知道你的意思。 SQLiteAssetHelper是Java類,來自庫。假設您使用的是Android Studio,將庫添加到模塊的'build.gradle'文件中。如果你下載了'SQLiteAssetHelper'的GitHub倉庫,你可以做到這一點,這是不必要的,除非你分叉圖書館。 – CommonsWare

+0

哦。咄。沒關係,我生病了,因此腦殘。 – Jacob