如何使用Android应用程序的外部SQLite数据库 [英] How use an external sqlite database in android application

查看:176
本文介绍了如何使用Android应用程序的外部SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用我的 companies.db SQLite数据库在我的Andr​​oid应用程序。我在Android项目的资产夹复制它。并使用DatabaseHelper类,如下图所示:

I want to use my companies.db sqlite database in my android app. I copied it in "assets" folder of android project. and use DatabaseHelper class as seen below:

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();
        }
    }
}

和我使用下面code一个活动,我想数据库信息:

and I use below code in an activity that I want database information:

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);

但是当我运行该应用程序我得到了一些异常:

but when I run the application I got some exception:

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是我保存我的信息,哪里是我的code中的问题表?我究竟做错了什么?先谢谢了。

companies_fa is a table that I stored my information, where is the problem in my code? What am I doing wrong? Thanks in advance.

推荐答案

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

using SQLiteAssetHelper (https://github.com/jgilfelt/android-sqlite-asset-helper) solved my problem!

这篇关于如何使用Android应用程序的外部SQLite数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆