android - 将位于 Assets 文件夹中的预填充数据库放入 data/data/mypackage/databases

标签 android database

我一直在努力效仿这个例子:http://blog.softeq.com/2012/12/using-pre-populated-sqlite-database-in.html

此示例旨在向您展示如何打开存储在 Assets 文件夹中的预填充数据库。

已经创建了与此主题相关的线程,我已经尝试了提出的建议,但它并没有帮助我弄清楚为什么程序没有打开数据库文件。我究竟做错了什么?这是我在 LogCat 的前几行中得到的:

01-13 15:54:33.171: E/Trace(30747): error opening trace file: No such file or directory (2)
01-13 15:54:33.171: D/ActivityThread(30747): setTargetHeapUtilization:0.25
01-13 15:54:33.171: D/ActivityThread(30747): setTargetHeapIdealFree:8388608
01-13 15:54:33.171: D/ActivityThread(30747): setTargetHeapConcurrentStart:2097152
01-13 15:54:33.251: D/AbsListView(30747): Get MotionRecognitionManager
01-13 15:54:33.261: E/SQLiteLog(30747): (14) cannot open file at line 30245 of [00bb9c9ce4]
01-13 15:54:33.261: E/SQLiteLog(30747): (14) os_unix.c:30245: (2) open(/data/data/com.example.prepopdb/databases/yourdb.db) - 
01-13 15:54:33.261: E/SQLiteDatabase(30747): Failed to open database '/data/data/com.example.prepopdb/databases/yourdb.db'.
01-13 15:54:33.261: E/SQLiteDatabase(30747): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:278)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:464)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:186)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:178)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at com.example.prepopdb.ExternalDbOpenHelper.checkDataBase(ExternalDbOpenHelper.java:62)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at com.example.prepopdb.ExternalDbOpenHelper.createDataBase(ExternalDbOpenHelper.java:43)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at com.example.prepopdb.ExternalDbOpenHelper.openDataBase(ExternalDbOpenHelper.java:97)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at com.example.prepopdb.ExternalDbOpenHelper.<init>(ExternalDbOpenHelper.java:37)
01-13 15:54:33.261: E/SQLiteDatabase(30747):    at com.example.prepopdb.PrepopSqliteDbActivity.onCreate(PrepopSqliteDbActivity.java:35)

我使用上面链接中提到的 SQLite 数据库浏览器创建了测试数据库,除了我的数据库扩展名是“.db”而不是“.sqlite3”。 (虽然我也尝试过使用“.sqlite3”,但有类似/相同的错误)。

这是我的 PrepopSqliteDbActivity 的代码:

package com.example.prepopdb;

import com.example.prepopdb.ExternalDbOpenHelper;
import java.util.ArrayList;

import android.app.ListActivity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PrepopSqliteDbActivity extends ListActivity {

private static final String DB_NAME = "yourdb.db";

// Database field names
private static final String TABLE_NAME = "friends";
private static final String FRIEND_ID = "_id";
private static final String FRIEND_NAME = "name";

private SQLiteDatabase database;
private ListView listView;
private ArrayList<String> friends;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ExternalDbOpenHelper dbOpenHelper = new ExternalDbOpenHelper(this,
            DB_NAME);
    database = dbOpenHelper.openDataBase(); // Database is open

    /*SOME OTHER CODE HERE*/
}

这是我的 ExternalDbOpenHelper 的代码:

package com.example.prepopdb;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class ExternalDbOpenHelper extends SQLiteOpenHelper {

// Path to the device folder with database
public static String DB_PATH;

// Database filename
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;

public SQLiteDatabase getDb() {
    return database;
}

public ExternalDbOpenHelper(Context context, String databaseName) {
    super(context, databaseName, null, 1);
    this.context = context;

    // Write the full path to the databases of your application
    String packageName = context.getPackageName();
    DB_PATH = String.format("%s/data/%s/databases/", Environment.getDataDirectory(), packageName);
    DB_NAME = databaseName;
    openDataBase();

}

// Create a database if its not yet created
public void createDataBase() {
    boolean dbExist = checkDataBase();
    if (!dbExist) {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), "Copying error!");
            throw new Error("Error copying database!");
        }
    } else {
        Log.i(this.getClass().toString(), "Database already exists");
    }
}

//Performing a database existence check
private boolean checkDataBase(){
    SQLiteDatabase checkDb = null;
    try {
        String path = DB_PATH + DB_NAME;
        checkDb = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e){
        Log.e(this.getClass().toString(), "Error while checking db");
    }

    if (checkDb != null){
        checkDb.close();
    }
    return checkDb !=null;
}

private void copyDataBase() throws IOException {
    //Open a stream for reading, located in the assets
    InputStream externalDbStream = context.getAssets().open(DB_NAME);
    //Path to the created empty database on your Android device
    String outFileName = DB_PATH + DB_NAME;

    //Create a stream for writing the database byte by byte
    OutputStream localDbStream = new FileOutputStream(outFileName);

    //Copy the database
    byte[] buffer = new byte[1024];
    int bytesRead;
    while((bytesRead = externalDbStream.read(buffer)) > 0){
        localDbStream.write(buffer, 0, bytesRead);
    }

    //Close the streams
    localDbStream.close();
    externalDbStream.close();
}

SQLiteDatabase openDataBase() throws SQLException {
    String path = DB_PATH + DB_NAME;
    if (database == null) {
        createDataBase();
        database = SQLiteDatabase.openDatabase(path, null,
                SQLiteDatabase.OPEN_READWRITE);
        //database = getWritableDatabase();
    }
    return database;
}

@Override
public synchronized void close(){
    if (database != null){
        database.close();
    }
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}
}

更新

谢谢卡洛斯。我同意对路径进行硬编码不是一个好主意,因为它可能因设备而异。我按照您的建议进行了更改,但是我仍然遇到相同的错误。我已验证 yourdb.db 文件具有所有级别的读/写权限。

我在之前的评论中提到了这一点,但是否会因为我使用的是非 root 手机而发生这种情况?将“yourdb.db”的权限从 Asssets 文件夹复制到/data/data/com.example.prepopdb/databases/然后我的程序试图打开它后,它的权限可能会改变吗?我知道如何使用 adb 更改权限,但如何在程序中执行此操作?

这是我的 Logcat 所说的内容:

01-14 12:18:02.240: E/Trace(18167): error opening trace file: No such file or directory (2)
01-14 12:18:02.240: D/ActivityThread(18167): setTargetHeapUtilization:0.25
01-14 12:18:02.240: D/ActivityThread(18167): setTargetHeapIdealFree:8388608
01-14 12:18:02.240: D/ActivityThread(18167): setTargetHeapConcurrentStart:2097152
01-14 12:18:02.360: D/AbsListView(18167): Get MotionRecognitionManager
01-14 12:18:02.370: E/SQLiteLog(18167): (14) cannot open file at line 30245 of [00bb9c9ce4]
01-14 12:18:02.370: E/SQLiteLog(18167): (14) os_unix.c:30245: (2) open(/data/data/com.example.prepopdb/databases/yourdb.db) - 
01-14 12:18:02.370: E/SQLiteDatabase(18167): Failed to open database '/data/data/com.example.prepopdb/databases/yourdb.db'.
01-14 12:18:02.370: E/SQLiteDatabase(18167): android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:278)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:217)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:464)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:186)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:178)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:669)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.example.prepopdb.ExternalDbOpenHelper.checkDataBase(ExternalDbOpenHelper.java:63)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.example.prepopdb.ExternalDbOpenHelper.createDataBase(ExternalDbOpenHelper.java:45)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.example.prepopdb.ExternalDbOpenHelper.openDataBase(ExternalDbOpenHelper.java:97)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.example.prepopdb.ExternalDbOpenHelper.<init>(ExternalDbOpenHelper.java:39)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.example.prepopdb.PrepopSqliteDbActivity.onCreate(PrepopSqliteDbActivity.java:35)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.Activity.performCreate(Activity.java:5048)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2052)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.ActivityThread.access$700(ActivityThread.java:139)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.os.Looper.loop(Looper.java:137)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at android.app.ActivityThread.main(ActivityThread.java:4918)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at java.lang.reflect.Method.invokeNative(Native Method)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at java.lang.reflect.Method.invoke(Method.java:511)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
01-14 12:18:02.370: E/SQLiteDatabase(18167):    at dalvik.system.NativeStart.main(Native Method)
01-14 12:18:02.370: E/class com.example.prepopdb.ExternalDbOpenHelper(18167): Error while checking db
01-14 12:18:02.480: D/libEGL(18167): loaded /system/lib/egl/libEGL_adreno200.so
01-14 12:18:02.500: D/libEGL(18167): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
01-14 12:18:02.500: D/libEGL(18167): loaded /system/lib/egl/libGLESv2_adreno200.so
01-14 12:18:02.540: I/Adreno200-EGLSUB(18167): <ConfigWindowMatch:2087>: Format RGBA_8888.
01-14 12:18:02.560: E/(18167): <s3dReadConfigFile:75>: Can't open file for reading
01-14 12:18:02.560: E/(18167): <s3dReadConfigFile:75>: Can't open file for reading
01-14 12:18:02.560: D/OpenGLRenderer(18167): Enabling debug mode 0
01-14 12:18:21.380: W/IInputConnectionWrapper(18167): beginBatchEdit on inactive InputConnection
01-14 12:18:21.380: W/IInputConnectionWrapper(18167): endBatchEdit on inactive InputConnection

最佳答案

您对数据文件夹的假设太多了。您宁愿让系统为您提供正确的路径。 您可以使用 context.getDatabasePath(); 获取数据库路径,您将所需的名称传递给文件(无论它是否存在)。实际上你应该那样做

为此,您可以在任何地方使用 String outFileName = DB_PATH + DB_NAME; 你应该改变它

 String outFileName =myContext.getDatabasePath(DB_NAME).getPath() ;

这是您文件的真正有效位置。所以我们的助手会像这样

public class ExternalDbOpenHelper extends SQLiteOpenHelper {

// Path to the device folder with database
public static String DB_PATH;

// Database filename
public static String DB_NAME;
public SQLiteDatabase database;
public final Context context;

public SQLiteDatabase getDb() {
    return database;
}

public ExternalDbOpenHelper(Context context, String databaseName) {
    super(context, databaseName, null, 1);
    this.context = context;
        DB_NAME = databaseName;
            DB_PATH =context.getDatabasePath(DB_NAME).getPath() ;
    openDataBase();

}

// Create a database if its not yet created
public void createDataBase() {
    boolean dbExist = checkDataBase();
    if (!dbExist) {
        this.getReadableDatabase();
        try {
            copyDataBase();
        } catch (IOException e) {
            Log.e(this.getClass().toString(), "Copying error!");
            throw new Error("Error copying database!");
        }
    } else {
        Log.i(this.getClass().toString(), "Database already exists");
    }
}

//Performing a database existence check
private boolean checkDataBase(){
    SQLiteDatabase checkDb = null;
    try {

        checkDb = SQLiteDatabase.openDatabase(DB_PATH, null, SQLiteDatabase.OPEN_READONLY);
    } catch (SQLException e){
        Log.e(this.getClass().toString(), "Error while checking db");
    }

    if (checkDb != null){
        checkDb.close();
    }
    return checkDb !=null;
}

private void copyDataBase() throws IOException {
    //Open a stream for reading, located in the assets
    InputStream externalDbStream = context.getAssets().open(DB_NAME);



    //Create a stream for writing the database byte by byte
    OutputStream localDbStream = new FileOutputStream(DB_PATH);

    //Copy the database
    byte[] buffer = new byte[1024];
    int bytesRead;
    while((bytesRead = externalDbStream.read(buffer)) > 0){
        localDbStream.write(buffer, 0, bytesRead);
    }

             //FLUSH THE OUT STREAM
             localDbStream.flush();

    //Close the streams
    localDbStream.close();
    externalDbStream.close();
}

SQLiteDatabase openDataBase() throws SQLException {

    if (database == null) {
        createDataBase();
        database = SQLiteDatabase.openDatabase(DB_PATH, null,
                SQLiteDatabase.OPEN_READWRITE);
        //database = getWritableDatabase();
    }
    return database;
}

@Override
public synchronized void close(){
    if (database != null){
        database.close();
    }
    super.close();
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub

}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub

}
}

有了这个它应该可以工作

更新

您可以考虑一些注意事项:

  • 查看系统为您的数据库返回的路径

    DB_PATH =context.getDatabasePath(DB_NAME).getPath() ;
    Log.i ("myApp", DB_PATH);
    
  • 检查模拟器中的代码,看看您是否遇到同样的问题。在那里你可以手动检查文件是否实际创建,如解释的那样 here

  • 添加 permissions写入和读取 SD 卡(READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE)。但我真的不相信你需要这个

关于android - 将位于 Assets 文件夹中的预填充数据库放入 data/data/mypackage/databases,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21101515/

相关文章:

android - 如何在 Mac、Windows 和 Linux 中使用 keytool 为默认调试 key 生成 SHA1、SHA256、MD5?

android - 查看屏幕外的位置

ios - FMDB 数据库无法在设备上运行,但可以在模拟器中运行

mysql - 适用于传感器数据的数据存储

android - 如何将 azure sql 数据库中的表连接到 Easy Tables 的表?

android - 困在谷歌播放控制台中的目标受众和内容

android - 在imageview中显示水平和垂直图像

android - 我的自定义 View 没有显示,我应该如何修复它?

database - session 和数据库的 oracle db 时区, session 区域的更改不起作用

MYSQL 函数/过程