船上应用程序与数据库
-
21-08-2019 - |
题
如果应用程序需要一个数据库,并配有内置的数据,什么是最好的方式为船舶的应用程序?我应该:
预创建源码数据库,包括它的
.apk
?包括SQL命令的应用程序并创建数据库,并插入的数据首先使用?
存在的缺陷,我看到的是:
能源码版本的不匹配可能会引起问题,我目前不知道在哪里,该数据库应该去和如何进行访问。
这可能需要很长时间来创建和填充数据库的设备。
任何建议?指针的文件有关的任何问题,将不胜感激。
解决方案
我只是找到一种方法来这样做 ReignDesign blog
在一篇题为 用你自己的源码数据库卓应用程序.基本上你预先创建数据库,把它放在你的财产目录中,并在第一次使用复制到 /data/data/YOUR_PACKAGE/databases/
目录。
其他提示
有两个选项创建和更新数据库。
一个是创建一个数据库是外部,然后将其在该资产上的文件夹的项目和随后复制的整个数据库。这是快得多,如果该数据库有很多表和其他组件。 升级引发的变化的数据库的版本号res/values/strings.xml 文件。 升级会然后可通过创建一个新的数据库外,更换旧的数据库中的资产文件夹,与新数据库,节省的旧数据库在内部存在的另一个名称、复制新的数据库的资产文件夹成内部储存、转让所有的数据从旧的数据库(这一名称改为前)进入新的数据库,并最终删除旧的数据库。你可以创建一个数据库最初是通过使用 源码管理FireFox插件 执行你的创作sql发言。
其他选项是创建一个数据库在内部从一个sql文件。这是不是作为快速而延迟可能觉察不到的用户,如果该数据库只有几个表格。 升级引发的变化的数据库的版本号res/values/strings.xml 文件。 升级会然后可以通过处理的升级sql文件。数据库中的数据将保持不变,除了当地的容器中被去掉,例如删除表。
下面的示例说明如何使用的方法。
这里是一样create_database.sql文件。它是被放置在该资产上的文件夹的项目,为内部方法或复制到"执行SQL'的源码管理来创建数据库,用于外部方法。 (注:注意到评论的表格所需的机器人。)
--Android requires a table named 'android_metadata' with a 'locale' column
CREATE TABLE "android_metadata" ("locale" TEXT DEFAULT 'en_US');
INSERT INTO "android_metadata" VALUES ('en_US');
CREATE TABLE "kitchen_table";
CREATE TABLE "coffee_table";
CREATE TABLE "pool_table";
CREATE TABLE "dining_room_table";
CREATE TABLE "card_table";
这里是一样update_database.sql文件。它是被放置在该资产上的文件夹的项目,为内部方法或复制到"执行SQL'的源码管理来创建数据库,用于外部方法。 (注:注意到所有三种类型的SQL的意见将被忽略的sql parser包括在此例。)
--CREATE TABLE "kitchen_table"; This is one type of comment in sql. It is ignored by parseSql.
/*
* CREATE TABLE "coffee_table"; This is a second type of comment in sql. It is ignored by parseSql.
*/
{
CREATE TABLE "pool_table"; This is a third type of comment in sql. It is ignored by parseSql.
}
/* CREATE TABLE "dining_room_table"; This is a second type of comment in sql. It is ignored by parseSql. */
{ CREATE TABLE "card_table"; This is a third type of comment in sql. It is ignored by parseSql. }
--DROP TABLE "picnic_table"; Uncomment this if picnic table was previously created and now is being replaced.
CREATE TABLE "picnic_table" ("plates" TEXT);
INSERT INTO "picnic_table" VALUES ('paper');
这是一项添加至/res/values/strings.xml 文件数据库版本的编号。
<item type="string" name="databaseVersion" format="integer">1</item>
这里是一个活动,访问该数据库,然后使用它。(注:你可能会想要跑的数据库码在一个单独的线如果它使用了大量的资源。)
package android.example;
import android.app.Activity;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
/**
* @author Danny Remington - MacroSolve
*
* Activity for demonstrating how to use a sqlite database.
*/
public class Database extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
DatabaseHelper myDbHelper;
SQLiteDatabase myDb = null;
myDbHelper = new DatabaseHelper(this);
/*
* Database must be initialized before it can be used. This will ensure
* that the database exists and is the current version.
*/
myDbHelper.initializeDataBase();
try {
// A reference to the database can be obtained after initialization.
myDb = myDbHelper.getWritableDatabase();
/*
* Place code to use database here.
*/
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
myDbHelper.close();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
myDb.close();
}
}
}
}
这里是数据库的辅助类数据库创建或更新的,如果必要的。 (注:安卓,你需要创建一个类延伸SQLiteOpenHelper为了工作源码数据库。)
package android.example;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
/**
* @author Danny Remington - MacroSolve
*
* Helper class for sqlite database.
*/
public class DatabaseHelper extends SQLiteOpenHelper {
/*
* The Android's default system path of the application database in internal
* storage. The package of the application is part of the path of the
* directory.
*/
private static String DB_DIR = "/data/data/android.example/databases/";
private static String DB_NAME = "database.sqlite";
private static String DB_PATH = DB_DIR + DB_NAME;
private static String OLD_DB_PATH = DB_DIR + "old_" + DB_NAME;
private final Context myContext;
private boolean createDatabase = false;
private boolean upgradeDatabase = false;
/**
* Constructor Takes and keeps a reference of the passed context in order to
* access to the application assets and resources.
*
* @param context
*/
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, context.getResources().getInteger(
R.string.databaseVersion));
myContext = context;
// Get the path of the database that is based on the context.
DB_PATH = myContext.getDatabasePath(DB_NAME).getAbsolutePath();
}
/**
* Upgrade the database in internal storage if it exists but is not current.
* Create a new empty database in internal storage if it does not exist.
*/
public void initializeDataBase() {
/*
* Creates or updates the database in internal storage if it is needed
* before opening the database. In all cases opening the database copies
* the database in internal storage to the cache.
*/
getWritableDatabase();
if (createDatabase) {
/*
* If the database is created by the copy method, then the creation
* code needs to go here. This method consists of copying the new
* database from assets into internal storage and then caching it.
*/
try {
/*
* Write over the empty data that was created in internal
* storage with the one in assets and then cache it.
*/
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
} else if (upgradeDatabase) {
/*
* If the database is upgraded by the copy and reload method, then
* the upgrade code needs to go here. This method consists of
* renaming the old database in internal storage, create an empty
* new database in internal storage, copying the database from
* assets to the new database in internal storage, caching the new
* database from internal storage, loading the data from the old
* database into the new database in the cache and then deleting the
* old database from internal storage.
*/
try {
FileHelper.copyFile(DB_PATH, OLD_DB_PATH);
copyDataBase();
SQLiteDatabase old_db = SQLiteDatabase.openDatabase(OLD_DB_PATH, null, SQLiteDatabase.OPEN_READWRITE);
SQLiteDatabase new_db = SQLiteDatabase.openDatabase(DB_PATH,null, SQLiteDatabase.OPEN_READWRITE);
/*
* Add code to load data into the new database from the old
* database and then delete the old database from internal
* storage after all data has been transferred.
*/
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
/**
* Copies your database from your local assets-folder to the just created
* empty database in the system folder, from where it can be accessed and
* handled. This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException {
/*
* Close SQLiteOpenHelper so it will commit the created empty database
* to internal storage.
*/
close();
/*
* Open the database in the assets folder as the input stream.
*/
InputStream myInput = myContext.getAssets().open(DB_NAME);
/*
* Open the empty db in interal storage as the output stream.
*/
OutputStream myOutput = new FileOutputStream(DB_PATH);
/*
* Copy over the empty db in internal storage with the database in the
* assets folder.
*/
FileHelper.copyFile(myInput, myOutput);
/*
* Access the copied database so SQLiteHelper will cache it and mark it
* as created.
*/
getWritableDatabase().close();
}
/*
* This is where the creation of tables and the initial population of the
* tables should happen, if a database is being created from scratch instead
* of being copied from the application package assets. Copying a database
* from the application package assets to internal storage inside this
* method will result in a corrupted database.
* <P>
* NOTE: This method is normally only called when a database has not already
* been created. When the database has been copied, then this method is
* called the first time a reference to the database is retrieved after the
* database is copied since the database last cached by SQLiteOpenHelper is
* different than the database in internal storage.
*/
@Override
public void onCreate(SQLiteDatabase db) {
/*
* Signal that a new database needs to be copied. The copy process must
* be performed after the database in the cache has been closed causing
* it to be committed to internal storage. Otherwise the database in
* internal storage will not have the same creation timestamp as the one
* in the cache causing the database in internal storage to be marked as
* corrupted.
*/
createDatabase = true;
/*
* This will create by reading a sql file and executing the commands in
* it.
*/
// try {
// InputStream is = myContext.getResources().getAssets().open(
// "create_database.sql");
//
// String[] statements = FileHelper.parseSqlFile(is);
//
// for (String statement : statements) {
// db.execSQL(statement);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
}
/**
* Called only if version number was changed and the database has already
* been created. Copying a database from the application package assets to
* the internal data system inside this method will result in a corrupted
* database in the internal data system.
*/
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/*
* Signal that the database needs to be upgraded for the copy method of
* creation. The copy process must be performed after the database has
* been opened or the database will be corrupted.
*/
upgradeDatabase = true;
/*
* Code to update the database via execution of sql statements goes
* here.
*/
/*
* This will upgrade by reading a sql file and executing the commands in
* it.
*/
// try {
// InputStream is = myContext.getResources().getAssets().open(
// "upgrade_database.sql");
//
// String[] statements = FileHelper.parseSqlFile(is);
//
// for (String statement : statements) {
// db.execSQL(statement);
// }
// } catch (Exception ex) {
// ex.printStackTrace();
// }
}
/**
* Called everytime the database is opened by getReadableDatabase or
* getWritableDatabase. This is called after onCreate or onUpgrade is
* called.
*/
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
}
/*
* Add your public helper methods to access and get content from the
* database. You could return cursors by doing
* "return myDataBase.query(....)" so it'd be easy to you to create adapters
* for your views.
*/
}
这里的FileHelper类,其中包含的方法的字节流复制文件和分析sql文件。
package android.example;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.nio.channels.FileChannel;
/**
* @author Danny Remington - MacroSolve
*
* Helper class for common tasks using files.
*
*/
public class FileHelper {
/**
* Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
* of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
* it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
* path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
* <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
* operation.
*
* @param fromFile
* - InputStream for the file to copy from.
* @param toFile
* - InputStream for the file to copy to.
*/
public static void copyFile(InputStream fromFile, OutputStream toFile) throws IOException {
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
try {
while ((length = fromFile.read(buffer)) > 0) {
toFile.write(buffer, 0, length);
}
}
// Close the streams
finally {
try {
if (toFile != null) {
try {
toFile.flush();
} finally {
toFile.close();
}
}
} finally {
if (fromFile != null) {
fromFile.close();
}
}
}
}
/**
* Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
* of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
* it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
* path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
* <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
* operation.
*
* @param fromFile
* - String specifying the path of the file to copy from.
* @param toFile
* - String specifying the path of the file to copy to.
*/
public static void copyFile(String fromFile, String toFile) throws IOException {
copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
}
/**
* Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
* of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
* it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
* path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
* <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
* operation.
*
* @param fromFile
* - File for the file to copy from.
* @param toFile
* - File for the file to copy to.
*/
public static void copyFile(File fromFile, File toFile) throws IOException {
copyFile(new FileInputStream(fromFile), new FileOutputStream(toFile));
}
/**
* Creates the specified <i><b>toFile</b></i> that is a byte for byte a copy
* of <i><b>fromFile</b></i>. If <i><b>toFile</b></i> already existed, then
* it will be replaced with a copy of <i><b>fromFile</b></i>. The name and
* path of <i><b>toFile</b></i> will be that of <i><b>toFile</b></i>. Both
* <i><b>fromFile</b></i> and <i><b>toFile</b></i> will be closed by this
* operation.
*
* @param fromFile
* - FileInputStream for the file to copy from.
* @param toFile
* - FileInputStream for the file to copy to.
*/
public static void copyFile(FileInputStream fromFile, FileOutputStream toFile) throws IOException {
FileChannel fromChannel = fromFile.getChannel();
FileChannel toChannel = toFile.getChannel();
try {
fromChannel.transferTo(0, fromChannel.size(), toChannel);
} finally {
try {
if (fromChannel != null) {
fromChannel.close();
}
} finally {
if (toChannel != null) {
toChannel.close();
}
}
}
}
/**
* Parses a file containing sql statements into a String array that contains
* only the sql statements. Comments and white spaces in the file are not
* parsed into the String array. Note the file must not contained malformed
* comments and all sql statements must end with a semi-colon ";" in order
* for the file to be parsed correctly. The sql statements in the String
* array will not end with a semi-colon ";".
*
* @param sqlFile
* - String containing the path for the file that contains sql
* statements.
*
* @return String array containing the sql statements.
*/
public static String[] parseSqlFile(String sqlFile) throws IOException {
return parseSqlFile(new BufferedReader(new FileReader(sqlFile)));
}
/**
* Parses a file containing sql statements into a String array that contains
* only the sql statements. Comments and white spaces in the file are not
* parsed into the String array. Note the file must not contained malformed
* comments and all sql statements must end with a semi-colon ";" in order
* for the file to be parsed correctly. The sql statements in the String
* array will not end with a semi-colon ";".
*
* @param sqlFile
* - InputStream for the file that contains sql statements.
*
* @return String array containing the sql statements.
*/
public static String[] parseSqlFile(InputStream sqlFile) throws IOException {
return parseSqlFile(new BufferedReader(new InputStreamReader(sqlFile)));
}
/**
* Parses a file containing sql statements into a String array that contains
* only the sql statements. Comments and white spaces in the file are not
* parsed into the String array. Note the file must not contained malformed
* comments and all sql statements must end with a semi-colon ";" in order
* for the file to be parsed correctly. The sql statements in the String
* array will not end with a semi-colon ";".
*
* @param sqlFile
* - Reader for the file that contains sql statements.
*
* @return String array containing the sql statements.
*/
public static String[] parseSqlFile(Reader sqlFile) throws IOException {
return parseSqlFile(new BufferedReader(sqlFile));
}
/**
* Parses a file containing sql statements into a String array that contains
* only the sql statements. Comments and white spaces in the file are not
* parsed into the String array. Note the file must not contained malformed
* comments and all sql statements must end with a semi-colon ";" in order
* for the file to be parsed correctly. The sql statements in the String
* array will not end with a semi-colon ";".
*
* @param sqlFile
* - BufferedReader for the file that contains sql statements.
*
* @return String array containing the sql statements.
*/
public static String[] parseSqlFile(BufferedReader sqlFile) throws IOException {
String line;
StringBuilder sql = new StringBuilder();
String multiLineComment = null;
while ((line = sqlFile.readLine()) != null) {
line = line.trim();
// Check for start of multi-line comment
if (multiLineComment == null) {
// Check for first multi-line comment type
if (line.startsWith("/*")) {
if (!line.endsWith("}")) {
multiLineComment = "/*";
}
// Check for second multi-line comment type
} else if (line.startsWith("{")) {
if (!line.endsWith("}")) {
multiLineComment = "{";
}
// Append line if line is not empty or a single line comment
} else if (!line.startsWith("--") && !line.equals("")) {
sql.append(line);
} // Check for matching end comment
} else if (multiLineComment.equals("/*")) {
if (line.endsWith("*/")) {
multiLineComment = null;
}
// Check for matching end comment
} else if (multiLineComment.equals("{")) {
if (line.endsWith("}")) {
multiLineComment = null;
}
}
}
sqlFile.close();
return sql.toString().split(";");
}
}
的 SQLiteAssetHelper
图书馆使这任务真的很简单。
这很容易添加作为一个摇篮的依赖(而是一个罐子也可用于Ant/蚀),并在一起的文件,它可以发现:
https://github.com/jgilfelt/android-sqlite-asset-helper
注: 这个项目不再保持如上述审查的链接。
正如在文件:
添加依赖于你的模块的实例建立的文件:
dependencies { compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' }
复制该数据库的资产目录,在一个称为子目录
assets/databases
.例如:
assets/databases/my_database.db
(可选择的,你可以压缩的数据库中的一个压缩文件,例如
assets/databases/my_database.zip
.这不是需要的,因为该应是压缩为一个整体了。)创建一个类,例如:
public class MyDatabase extends SQLiteAssetHelper { private static final String DATABASE_NAME = "my_database.db"; private static final int DATABASE_VERSION = 1; public MyDatabase(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } }
我猜最好的和最新的方式,直到今天是使用 SQLiteAssetHelper
类。
这个教程 指导你完全通过 进口和使用外部数据库在安卓
安卓
SQLiteAssetHelper
图书馆可以让你建立自己的SQLite
数据库在你的桌面计算机,并为进口和使用它在你的 应用程序。让我们创建一个简单的应用程序演示 应用这种图书馆。步骤1:创建一个数据库中的报价。db使用你最喜欢的源码 数据库应用程序(DB浏览器源码是一个便携式的交叉 平台免费软件,它可以被用来创建和编辑源码 数据库)。创建一个表"报价"有一个单列的"报价".插入一些随机的引进表"报价".
步骤2:该数据库可以进入的项目可以直接作为 是的,还是作为一个压缩文件。压缩文件的建议,如果 你的数据库是太大的大小。您可以创建一个
ZIP
压缩或GZ
压缩。文件名称的压缩db文件必须
quotes.db.zip
, 如果你 是用拉链压缩或quotes.db.gz
, 如果您使用的是GZ 压缩。步骤3:创建一个新的应用程序
External Database Demo
与 包名称com.javahelps.com.javahelps.externaldatabasedemo
.步骤4:打开的
build.gradle
(模块:应用程序)的文件和添加以下 依赖性。dependencies { compile 'com.readystatesoftware.sqliteasset:sqliteassethelper:+' }
一旦你们保存的
build.gradle
文件中点击'Sync现在' 链接,以更新项目。你可以同步build.gradle
, 通过 右击build.gradle
文件和选择Synchronize build.gradle
选项。步骤5:右键应用程序的文件夹和创造新的资产文件夹。
步骤6:创建一个新文件数据库内的资产的文件夹。
步骤7:抄和粘贴
quotes.db.zip
文件内assets/databases
文件夹。步骤8:创建一个新的类
DatabaseOpenHelper
package com.javahelps.externaldatabasedemo; import android.content.Context; import com.readystatesoftware.sqliteasset.SQLiteAssetHelper; public class DatabaseOpenHelper extends SQLiteAssetHelper { private static final String DATABASE_NAME = "quotes.db"; private static final int DATABASE_VERSION = 1; public DatabaseOpenHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } } Notice that rather than extending SQLiteOpenHelper, the DatabaseOpenHelper extends SQLiteAssetHelper class.
步骤9:创建一个新的类
DatabaseAccess
并输入的代码显示 如下。更多的细节,关于这类可以在高级安卓 数据库的教程。package com.javahelps.externaldatabasedemo; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.ArrayList; import java.util.List; public class DatabaseAccess { private SQLiteOpenHelper openHelper; private SQLiteDatabase database; private static DatabaseAccess instance; /** * Private constructor to aboid object creation from outside classes. * * @param context */ private DatabaseAccess(Context context) { this.openHelper = new DatabaseOpenHelper(context); } /** * Return a singleton instance of DatabaseAccess. * * @param context the Context * @return the instance of DabaseAccess */ public static DatabaseAccess getInstance(Context context) { if (instance == null) { instance = new DatabaseAccess(context); } return instance; } /** * Open the database connection. */ public void open() { this.database = openHelper.getWritableDatabase(); } /** * Close the database connection. */ public void close() { if (database != null) { this.database.close(); } } /** * Read all quotes from the database. * * @return a List of quotes */ public List<String> getQuotes() { List<String> list = new ArrayList<>(); Cursor cursor = database.rawQuery("SELECT * FROM quotes", null); cursor.moveToFirst(); while (!cursor.isAfterLast()) { list.add(cursor.getString(0)); cursor.moveToNext(); } cursor.close(); return list; } } In this class only the `getQuotes` method is implemented to read the data from the database. You have the full freedom to insert,
更新,并删除任何在数据库中的行为通常的。更多的细节, 按照这个链接高级安卓数据库。
所有的数据库相关的设置完成,现在我们需要 创建一个
ListView
来显示报价。步骤10:增加一个
ListView
在你activity_main.xml
.<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" /> </FrameLayout>
步骤11:找到对象的
ListView
在onCreate
方法MainActivity
和饲料的报价,这是读 形式的数据库。package com.javahelps.externaldatabasedemo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.List; public class MainActivity extends ActionBarActivity { private ListView listView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.listView = (ListView) findViewById(R.id.listView); DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this); databaseAccess.open(); List<String> quotes = databaseAccess.getQuotes(); databaseAccess.close(); ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, quotes); this.listView.setAdapter(adapter); } }
步骤12:保存所有的改变和运行的应用程序。
除了这篇文章你可以下载 SQLiteAssetHelper
在这里,
我的解决方案既没有使用任何第三方图书馆,也没有强迫你叫定义的方法 SQLiteOpenHelper
类初始化数据库的创建。它也需要护理的数据库的升级。所有这一切需要做的是子类 SQLiteOpenHelper
.
先决条件:
- 该数据库是你想要的船舶的程序。 它应该包含 一表1×1名为
android_metadata
有一个属性locale
具有的价值en_US
除了表独特的应用程序。
继承 SQLiteOpenHelper
:
- 子类
SQLiteOpenHelper
. - 创建一个
private
方法之内SQLiteOpenHelper
亚类。这种方法包含的逻辑复制数据库内容的数据库文件的'财产'的文件夹到创建的数据库应用程序包的上下文。 - 重写
onCreate
,onUpgrade
和onOpen
方法SQLiteOpenHelper
.
足够说。这里去 SQLiteOpenHelper
类:
public class PlanDetailsSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String TAG = "SQLiteOpenHelper";
private final Context context;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "my_custom_db";
private boolean createDb = false, upgradeDb = false;
public PlanDetailsSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
/**
* Copy packaged database from assets folder to the database created in the
* application package context.
*
* @param db
* The target database in the application package context.
*/
private void copyDatabaseFromAssets(SQLiteDatabase db) {
Log.i(TAG, "copyDatabase");
InputStream myInput = null;
OutputStream myOutput = null;
try {
// Open db packaged as asset as the input stream
myInput = context.getAssets().open("path/to/shipped/db/file");
// Open the db in the application package context:
myOutput = new FileOutputStream(db.getPath());
// Transfer db file contents:
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
// Set the version of the copied database to the current
// version:
SQLiteDatabase copiedDb = context.openOrCreateDatabase(
DATABASE_NAME, 0, null);
copiedDb.execSQL("PRAGMA user_version = " + DATABASE_VERSION);
copiedDb.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error(TAG + " Error copying database");
} finally {
// Close the streams
try {
if (myOutput != null) {
myOutput.close();
}
if (myInput != null) {
myInput.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new Error(TAG + " Error closing streams");
}
}
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "onCreate db");
createDb = true;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "onUpgrade db");
upgradeDb = true;
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.i(TAG, "onOpen db");
if (createDb) {// The db in the application package
// context is being created.
// So copy the contents from the db
// file packaged in the assets
// folder:
createDb = false;
copyDatabaseFromAssets(db);
}
if (upgradeDb) {// The db in the application package
// context is being upgraded from a lower to a higher version.
upgradeDb = false;
// Your db upgrade logic here:
}
}
}
最后,要获得一个数据库连接的,只是呼叫 getReadableDatabase()
或 getWritableDatabase()
在 SQLiteOpenHelper
子类,它将负责创建一个数据库,复制db内容从指定的文件中的'财产'的文件夹,如果数据库中并不存在。
在短短的,可以使用 SQLiteOpenHelper
类访问的数据库运送中资产的文件夹只是因为你会用一个数据库是初始化使用SQL查询 onCreate()
法。
运用一个数据库文件,在机器人工作室3.0
运用一个数据库文件是一个很好的想法对于我。优点是,你不需要做一个复杂的初始化,有时候费用大量的时间,如果数据集是巨大的。
步骤1:准备数据库的文件
有你的数据库文件的准备。它可以是一个.db文件或一个.源码文件。如果您使用的一个。源码文件,所有你需要做的是改变文件延长的名称。该步骤是相同的。
在这个例子中,我准备一个文件叫testDB.db。它有一个表以及一些样本数据,在这样
步骤2:进口的文件进你的项目
创建的资产文件夹,如果你还没有一个。然后抄和粘贴文件数据库进这个文件夹
步骤3:复制的文件应用程序的数据文件夹
你需要复制该数据库文件的应用程序的数据文件夹在了做进一步的互动。这是一个一次性的行动(初始化)复制的数据库文件。如果你打电话给这个代码多次,数据库文件中的数据文件夹中的文件将被复盖的一项资产的文件夹。这个复盖的过程是有用的,当你想要更新的数据库,在未来期间的应用程序更新。
注意,在应用程序,更新这个数据库文件将是不可更改的,在应用程序的数据文件夹。只卸载将其删除。
该数据库文件需要复制到 /databases
文件夹。打开设备的文件资源。输入 data/data/<YourAppName>/
位置。这是应用的默认数据文件夹上面提到的。和默认情况下,该数据库文件将被放置在另一个文件夹,名为数据库这一目录下
现在,复制文件的过程是非常喜欢的是什么Java是这样做的。使用下列代码做的复制贴。这是启动代码。它还可以被用来更新(通过复盖)的数据库文件的未来。
//get context by calling "this" in activity or getActivity() in fragment
//call this if API level is lower than 17 String appDataPath = "/data/data/" + context.getPackageName() + "/databases/"
String appDataPath = context.getApplicationInfo().dataDir;
File dbFolder = new File(appDataPath + "/databases");//Make sure the /databases folder exists
dbFolder.mkdir();//This can be called multiple times.
File dbFilePath = new File(appDataPath + "/databases/testDB.db");
try {
InputStream inputStream = context.getAssets().open("testDB.db");
OutputStream outputStream = new FileOutputStream(dbFilePath);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
outputStream.flush();
outputStream.close();
inputStream.close();
} catch (IOException e){
//handle
}
然后刷新文件夹到验证的复制过程
步骤4:创建数据库开启的帮手
创建一个子类 SQLiteOpenHelper
, 与连接、关闭道路等。我把它命名为 DatabaseOpenHelper
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
public static final String DB_NAME = "testDB.db";
public static final String DB_SUB_PATH = "/databases/" + DB_NAME;
private static String APP_DATA_PATH = "";
private SQLiteDatabase dataBase;
private final Context context;
public DatabaseOpenHelper(Context context){
super(context, DB_NAME, null, 1);
APP_DATA_PATH = context.getApplicationInfo().dataDir;
this.context = context;
}
public boolean openDataBase() throws SQLException{
String mPath = APP_DATA_PATH + DB_SUB_PATH;
//Note that this method assumes that the db file is already copied in place
dataBase = SQLiteDatabase.openDatabase(mPath, null, SQLiteDatabase.OPEN_READWRITE);
return dataBase != null;
}
@Override
public synchronized void close(){
if(dataBase != null) {dataBase.close();}
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
步骤5:创造顶级的互动数据库
这将是这类阅读和写你的数据库文件。还有一样的查询,以打印出来的价值在数据库。
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
public class Database {
private final Context context;
private SQLiteDatabase database;
private DatabaseOpenHelper dbHelper;
public Database(Context context){
this.context = context;
dbHelper = new DatabaseOpenHelper(context);
}
public Database open() throws SQLException
{
dbHelper.openDataBase();
dbHelper.close();
database = dbHelper.getReadableDatabase();
return this;
}
public void close()
{
dbHelper.close();
}
public void test(){
try{
String query ="SELECT value FROM test1";
Cursor cursor = database.rawQuery(query, null);
if (cursor.moveToFirst()){
do{
String value = cursor.getString(0);
Log.d("db", value);
}while (cursor.moveToNext());
}
cursor.close();
} catch (SQLException e) {
//handle
}
}
}
步骤6:试运行
测试的代码,通过运行以下行的代码。
Database db = new Database(context);
db.open();
db.test();
db.close();
命运行按钮和欢呼!
在十一月2017年的谷歌公布的 房间持续存图书馆
从文件:
房间里持续存图书馆提供了一个抽象层源码 允许流利的数据库访问,同时利用全部力量 源码.
图书馆有助于创建一个缓的应用的数据在一个装置 这就是运行的应用程序。这种高速缓存,作为应用的单 真实来源,允许用户查看一致的复制的关键 信息程序,而不论用户是否有一个 互联网连接。
房间数据库有时回调的数据库是一次创建或开幕。你可以使用创造回来填充数据库。
Room.databaseBuilder(context.applicationContext,
DataDatabase::class.java, "Sample.db")
// prepopulate the database after onCreate was called
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
// moving to a new thread
ioThread {
getInstance(context).dataDao()
.insert(PREPOPULATE_DATA)
}
}
})
.build()
从这个代码 博客.
从我所看到的你应当以运费的数据库已经表安装和数据。但是如果你想要(以及取决于应用程序的类型你有)可以允许"升级数据库的选择"。然后你做什么被下载最新的源码版本,获得最新插入/创造的声明的文本文件在线托,执行该声明和做一个数据从旧的数据库。
最后我做到了!!我用这个的链接 帮助使用自己的源码数据库卓应用程序, 但不得不改变这一点。
如果你有多软件包,你应该把主包名称:
private static String DB_PATH = "data/data/masterPakageName/databases";
我改变了方法,该方法复制该数据库从地方文件夹给模拟器文件夹!它有一些问题时那个文件夹不存在。所以首先,它应该检查路径,如果它不在那里,它应当创造的文件夹。
在前面的代码时,
copyDatabase
方法是永远不会被称为数据库时不存在的checkDataBase
方法造成的例外。所以我改变了代码的一点。如果你的数据库没有一个文件的扩展,不要使用的文件名称中的一个。
它工作好对我来说,我希望怎样有用的u太
package farhangsarasIntroduction;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DataBaseHelper extends SQLiteOpenHelper{
//The Android's default system path of your application database.
private static String DB_PATH = "data/data/com.example.sample/databases";
private static String DB_NAME = "farhangsaraDb";
private SQLiteDatabase myDataBase;
private final Context myContext;
/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
}
/**
* Creates a empty database on the system and rewrites it with your own database.
* */
public void createDataBase() {
boolean dbExist;
try {
dbExist = checkDataBase();
} catch (SQLiteException e) {
e.printStackTrace();
throw new Error("database dose not exist");
}
if(dbExist){
//do nothing - database already exist
}else{
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
throw new Error("Error copying database");
}
//By calling this method and empty database will be created into the default system path
//of your application so we are gonna be able to overwrite that database with our database.
this.getReadableDatabase();
}
}
/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH +"/"+ DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}catch(SQLiteException e){
//database does't exist yet.
throw new Error("database does't exist yet.");
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
private void copyDataBase() throws IOException{
//copyDataBase();
//Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH +"/"+ DB_NAME;
File databaseFile = new File( DB_PATH);
// check if databases folder exists, if not create one and its subfolders
if (!databaseFile.exists()){
databaseFile.mkdir();
}
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
@Override
public synchronized void close() {
if(myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
you to create adapters for your views.
}
目前没有办法预先创建一个源码数据库的船舶你。好的,你能做的就是保存适当的SQL作为一种资源和运行他们自己的应用程序。是的,这导致工作重复的数据(同样的信息存在作为一个resrouce并为一个数据库),但是没有其他的方法吧。只有减轻的因素是该应用文件被压缩。我的经验是908KB压缩小于268KB.
线以下具有最佳的讨论/解决方案,我们发现有好的样本代码。
http://groups.google.com/group/android-developers/msg/9f455ae93a1cf152
我保存我创造的声明作为一串的资源可以阅读的上下文。形式()并运行它与SQLiteDatabse.execSQL().
我保存的数据对于我插在res/原/插入。sql(I创建sql文件,7000+线)。使用技术从上面的链接,我进入了一个循环,阅读该文件逐行和concactenated的数据到"INSERT INTO tbl值"并没有另一个SQLiteDatabase.execSQL().没有意义的在节约7000"INSERT INTO tbl值"s的时候他们可以只是concactenated。
它需要大约二十秒钟在模拟器上,我不知道怎么长这将需要在一个真正的电话,但它只发生一次,当用户首次启动的应用程序。
运输数据库内的该应和随后复制它 /data/data/...
将增加一倍的大小的数据库(1,1 data/data/...
),并将增加该应大小(当然)。那么你的数据库应该不会太大。
安卓已经提供了一个版本-知道做法的数据库管理。这种方法已经被利用的BARACUS框架,安卓应用程序。
它可以让你来管理数据库以及整个版本的生命周期的一个应用程序,beeing能够更新源码数据库从任何现有版本的当前的一个。
我不是100%肯定的,但一个热恢复 具体 设备可以让你的船准备好的数据库在你的程序。但我不确定有关数据库的二元格式可能具体到某些设备,供应商或设备几代人。
因为东西是Apache许可证2,随时重新使用任何一部分代码, 这上可以找到。
编辑:
如果你只想要的船舶的数据,你可以考虑的实例,并坚持独在应用程序第一个开始。BARACUS有一个建立在为此提供支助(建立在关键的价值储存配置的相关信息,例如"APP_FIRST_RUN"外加一个后背景下-引导钩,以便运行后启动业务上上下文)。这让你有紧密的联接数据随附应用程序;在大多数情况下,这种装到我的使用情况。
如果需要的数据是不太大的(限制,我不知道,取决于很多事),可能还下载的数据(XML式,无论)从一个网站/网络应用程序.之后收到,执行SQL报表使用的接收到的数据制表和插入的数据。
如果你的移动应用程序含有大量的数据,它可能会更容易后来更新的数据在安装应用程序更准确的数据或改变。
我写了一个 图书馆 为了简化这一进程。
dataBase = new DataBase.Builder(context, "myDb").
// setAssetsPath(). // default "databases"
// setDatabaseErrorHandler().
// setCursorFactory().
// setUpgradeCallback()
// setVersion(). // default 1
build();
这将创建一个数据库从 assets/databases/myDb.db
文件。此外,你会得到所有这些功能:
- 负载数据库的文件
- 同步访问该数据库
- 使用 源码-安卓 通过再次查询,安卓具体分布的最新版本的源码.
克隆它从 想.
我使用的Pstcollectionview及以下代码为我工作
public class DatabaseProvider extends OrmLiteSqliteOpenHelper {
private static final String DatabaseName = "DatabaseName";
private static final int DatabaseVersion = 1;
private final Context ProvidedContext;
public DatabaseProvider(Context context) {
super(context, DatabaseName, null, DatabaseVersion);
this.ProvidedContext= context;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean databaseCopied = preferences.getBoolean("DatabaseCopied", false);
if (databaseCopied) {
//Do Nothing
} else {
CopyDatabase();
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("DatabaseCopied", true);
editor.commit();
}
}
private String DatabasePath() {
return "/data/data/" + ProvidedContext.getPackageName() + "/databases/";
}
private void CopyDatabase() {
try {
CopyDatabaseInternal();
} catch (IOException e) {
e.printStackTrace();
}
}
private File ExtractAssetsZip(String zipFileName) {
InputStream inputStream;
ZipInputStream zipInputStream;
File tempFolder;
do {
tempFolder = null;
tempFolder = new File(ProvidedContext.getCacheDir() + "/extracted-" + System.currentTimeMillis() + "/");
} while (tempFolder.exists());
tempFolder.mkdirs();
try {
String filename;
inputStream = ProvidedContext.getAssets().open(zipFileName);
zipInputStream = new ZipInputStream(new BufferedInputStream(inputStream));
ZipEntry zipEntry;
byte[] buffer = new byte[1024];
int count;
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
filename = zipEntry.getName();
if (zipEntry.isDirectory()) {
File fmd = new File(tempFolder.getAbsolutePath() + "/" + filename);
fmd.mkdirs();
continue;
}
FileOutputStream fileOutputStream = new FileOutputStream(tempFolder.getAbsolutePath() + "/" + filename);
while ((count = zipInputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return tempFolder;
}
private void CopyDatabaseInternal() throws IOException {
File extractedPath = ExtractAssetsZip(DatabaseName + ".zip");
String databaseFile = "";
for (File innerFile : extractedPath.listFiles()) {
databaseFile = innerFile.getAbsolutePath();
break;
}
if (databaseFile == null || databaseFile.length() ==0 )
throw new RuntimeException("databaseFile is empty");
InputStream inputStream = new FileInputStream(databaseFile);
String outFileName = DatabasePath() + DatabaseName;
File destinationPath = new File(DatabasePath());
if (!destinationPath.exists())
destinationPath.mkdirs();
File destinationFile = new File(outFileName);
if (!destinationFile.exists())
destinationFile.createNewFile();
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = inputStream.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
inputStream.close();
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int fromVersion, int toVersion) {
}
}
请注意,代码数据库提取的文件从一个压缩文件中的资产
我修改了类和回答问题,并写了一类,允许更新的数据库通过DB_VERSION.
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "info.db";
private static String DB_PATH = "";
private static final int DB_VERSION = 1;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
this.mContext = context;
copyDataBase();
this.getReadableDatabase();
}
public void updateDataBase() throws IOException {
if (mNeedUpdate) {
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
dbFile.delete();
copyDataBase();
mNeedUpdate = false;
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() {
if (!checkDataBase()) {
this.getReadableDatabase();
this.close();
try {
copyDBFile();
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private void copyDBFile() throws IOException {
InputStream mInput = mContext.getAssets().open(DB_NAME);
//InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
mOutput.write(mBuffer, 0, mLength);
mOutput.flush();
mOutput.close();
mInput.close();
}
public boolean openDataBase() throws SQLException {
mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
return mDataBase != null;
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
mNeedUpdate = true;
}
}
使用的一类。
在活动类声明变量。
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
在onCreate方法,写下代码。
mDBHelper = new DatabaseHelper(this);
try {
mDBHelper.updateDataBase();
} catch (IOException mIOException) {
throw new Error("UnableToUpdateDatabase");
}
try {
mDb = mDBHelper.getWritableDatabase();
} catch (SQLException mSQLException) {
throw mSQLException;
}
如果添加一个数据库文件,该文件夹res/原则使用以下的修改。
public class DatabaseHelper extends SQLiteOpenHelper {
private static String DB_NAME = "info.db";
private static String DB_PATH = "";
private static final int DB_VERSION = 1;
private SQLiteDatabase mDataBase;
private final Context mContext;
private boolean mNeedUpdate = false;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
if (android.os.Build.VERSION.SDK_INT >= 17)
DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
else
DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
this.mContext = context;
copyDataBase();
this.getReadableDatabase();
}
public void updateDataBase() throws IOException {
if (mNeedUpdate) {
File dbFile = new File(DB_PATH + DB_NAME);
if (dbFile.exists())
dbFile.delete();
copyDataBase();
mNeedUpdate = false;
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() {
if (!checkDataBase()) {
this.getReadableDatabase();
this.close();
try {
copyDBFile();
} catch (IOException mIOException) {
throw new Error("ErrorCopyingDataBase");
}
}
}
private void copyDBFile() throws IOException {
//InputStream mInput = mContext.getAssets().open(DB_NAME);
InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
byte[] mBuffer = new byte[1024];
int mLength;
while ((mLength = mInput.read(mBuffer)) > 0)
mOutput.write(mBuffer, 0, mLength);
mOutput.flush();
mOutput.close();
mInput.close();
}
public boolean openDataBase() throws SQLException {
mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
return mDataBase != null;
}
@Override
public synchronized void close() {
if (mDataBase != null)
mDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
mNeedUpdate = true;
}
}