android - 如何在 android 应用程序中使用外部 sqlite 数据库

标签 android sqlite android-sqlite

我想在我的 android 应用程序中使用我的 companies.db sqlite 数据库。我将它复制到 android 项目的“ Assets ”文件夹中。并使用 DatabaseHelper 类,如下所示:

public class DatabaseHelper extends SQLiteOpenHelper {
String DB_PATH = null;
public static String DB_NAME = "companies";
private SQLiteDatabase myDataBase;
private final Context myContext;
Context ctx;

public DatabaseHelper(Context context) {
    super(context, DB_NAME, null, 2);
    this.myContext = context;
    DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}

public void createDataBase() throws IOException {
    boolean dbExist = checkDataBase();
    if (dbExist) {
        // do nothing - database already exist
    } else {

        // 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();
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
            //throw new Error("Error copying database");
        }
    }
}
private boolean checkDataBase() {
    SQLiteDatabase checkDB = null;
    try {
        String myPath = DB_PATH + DB_NAME;
        checkDB = SQLiteDatabase.openDatabase(myPath, null,
                SQLiteDatabase.OPEN_READONLY);
    } catch (SQLiteException e) {
        e.printStackTrace();
        // 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 {
    // 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;
    // 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();
}
public void openDataBase() throws SQLException {
    // Open the database
    String myPath = DB_PATH + DB_NAME;
    // SQLiteDatabase.NO_LOCALIZED_COLLATORS
    myDataBase = SQLiteDatabase.openDatabase(myPath, null,
            SQLiteDatabase.OPEN_READONLY
                    | SQLiteDatabase.NO_LOCALIZED_COLLATORS
                    | SQLiteDatabase.CREATE_IF_NECESSARY);
}
@Override
public synchronized void close() {
    if (myDataBase != null)
        myDataBase.close();
    super.close();
}
// return cursor
public Cursor query(String table, String[] columns, String selection,
                    String[] selectionArgs, String groupBy, String having,
                    String orderBy) {
    return myDataBase.query("pwp_singers", null, null, null, null, null,
            null);
}
@Override
public void onCreate(SQLiteDatabase arg0) {
    // TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (newVersion > oldVersion)
        try {
            copyDataBase();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我在需要数据库信息的 Activity 中使用以下代码:

DatabaseHelper myDbHelper=new DatabaseHelper(ListViewActivity.this);
    try {
        myDbHelper.createDataBase();
    }catch(Exception e)
    {}
    myDbHelper.openDataBase();
    db = myDbHelper.getReadableDatabase();
    Cursor c;
    c= db.rawQuery("select * from companies_fa where id=103", null);

但是当我运行应用程序时,出现了一些异常:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ahmad.exhibition/com.example.ahmad.exhibition.ListViewActivity}: android.database.sqlite.SQLiteException: no such table: companies_fa: , while compiling: select * from companies_fa where id=103
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1815)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
        at android.app.ActivityThread.access$500(ActivityThread.java:122)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:132)
        at android.app.ActivityThread.main(ActivityThread.java:4123)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:491)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
        at dalvik.system.NativeStart.main(Native Method)
 Caused by: android.database.sqlite.SQLiteException: no such table: companies_fa: , while compiling: select * from companies_fa where id=103
        at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
        at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:64)
        at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:146)
        at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:367)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:130)
        at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
        at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:46)
        at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
        at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1539)
        at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1508)
        at com.example.ahmad.exhibition.ListViewActivity.onCreate(ListViewActivity.java:70)
        at android.app.Activity.performCreate(Activity.java:4397)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1779)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1831)
            at android.app.ActivityThread.access$500(ActivityThread.java:122)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1024)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:132)
            at android.app.ActivityThread.main(ActivityThread.java:4123)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:491)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
            at dalvik.system.NativeStart.main(Native Method)

companies_fa 是我存储我的信息的表,我的代码哪里有问题?我究竟做错了什么?提前致谢。

最佳答案

使用 SQLiteAssetHelper ( https://github.com/jgilfelt/android-sqlite-asset-helper ) 解决了我的问题!

关于android - 如何在 android 应用程序中使用外部 sqlite 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28589900/

相关文章:

iOS SQLite 或 1000 个松散文件?

django - python sqlite 在终端-django 中的使用

Android API 8 , 10 ContactsContract.Data.HAS_PHONE_NUMBER 没有这样的列

android - 使用 AsyncTask 从 sqlite 数据库加载数据并显示在 recyclerview 项目中

java - 解析 JSONObject 和 JSONArray 并在 ListView 中修复它们

java - CardboardView 如何处理头部运动?

javascript - Android 2.X HTML5 视频结束全屏

mysql - 用专业数据库替换核心数据以提高性能

java - Android - sqlite in 子句使用数组列表中的字符串值?

android - Phonegap Childbrowser 打开 Phonegap 页面。