【问题标题】:Trying to preload a SQLite database into an Android app [duplicate]尝试将 SQLite 数据库预加载到 Android 应用程序中 [重复]
【发布时间】:2017-05-06 03:04:06
【问题描述】:

我正在尝试创建一个应用程序来检查日期,从预加载的数据库中引用日落时间,并在该时间发生前 90 分钟输出警报。不太具体(可能与您更相关),我正在尝试编写一个带有预填充信息数据库的应用程序,它可以根据需要访问。在 Android 开发中使用 SQLite 有多个教程,但它们都假设您在应用程序运行并尝试输入用户确定的数据时创建数据库;我发现的唯一教程是从 2009 年开始的,从那以后有一些更新导致无法使用(我认为;无论如何,它肯定不会在 Android Studio 中工作)。关于此的所有其他问题都刚刚被标记为重复,并引用回一个非常古老的问题,答案是 - 你猜对了 - 同一个过时的教程。 This 是我正在谈论的教程,如果它有帮助的话;不知道它会,但它可能。

编辑:为什么要关闭它?我在我的问题中提到,这个问题在技术上之前已经得到回答,但它都链接回一个过时的、不相关的教程,根本没有帮助。这个问题可能以前被问过,但答案已经改变了。

【问题讨论】:

    标签: 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 一样。在您的应用首次运行时,您的数据库会自动从资产中解压缩。

    【讨论】:

    • 嗯嗯,效果很好。我想我应该多看看盒子外面的东西。快速澄清问题,因为我对 Android 有点陌生,下载并解压缩 SQLiteAssetHelper 文件后,我该把它放在哪里?
    • @Jacob:“下载并解压缩后,我将 SQLiteAssetHelper 文件放在哪里?” ——我不明白你的意思。 SQLiteAssetHelper,Java 类,来自库。假设您使用的是 Android Studio,您将库添加到模块的 build.gradle 文件中。如果你下载了SQLiteAssetHelper 的 GitHub 存储库,虽然你可以这样做,但没有必要这样做,除非你要分叉库。
    • 哦。呃。没关系,我病了,因此脑死亡。
    猜你喜欢
    • 2017-09-29
    • 2017-12-23
    • 1970-01-01
    • 2012-08-25
    • 2015-11-15
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    相关资源
    最近更新 更多