如何使用我自己的数据库 - 机器人 [英] How to use my own database - android

查看:109
本文介绍了如何使用我自己的数据库 - 机器人的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/9109438/how-to-use-an-existing-database-with-an-android-application\">How使用现有的数据库,一个Android应用程序


我有一个SQLite数据库文件,我想在我的应用程序中使用它。

我该怎么办呢?

我怎么把我的数据库文件到模拟器,然后在我的code使用它?

任何解决方案是值得欢迎的。
THX在前进,汤姆。


解决方案

 公共类AssetDatabaseHelper扩展SQLiteOpenHelper {    私人字符串DBNAME;
    私人字符串DB_PATH;
    私人上下文的背景下;    / **
     *一个辅助类导入数据库文件。
     *
     * @参数基地
     * /应用程序上下文
     * @参数DBNAME
     *资产文件夹中的DB的名称。
     * /
    公共AssetDatabaseHelper(上下文的背景下,字符串DBNAME){
        超(背景下,数据库名,空,1);
        this.dbName = DBNAME;
        this.context =背景;
        DB_PATH =/数据/数据​​/+ context.getPackageName()+/数据库/;
    }    / **
     *检查是否已存在于数据库,以避免重新复制每个文件
     *一次打开应用程序。
     *
     *如果存在返回:真的,假的,如果它不
     * /
    公共布尔checkExist(){        SQLiteDatabase CHECKDB = NULL;        尝试{
            字符串mypath中= DB_PATH + DBNAME;
            CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,
                    SQLiteDatabase.OPEN_READONLY);        }赶上(SQLiteException E){
            e.printStackTrace();
            //数据库开不存在。        }赶上(例外EP){
            ep.printStackTrace();
        }        如果(CHECKDB!= NULL){            checkDB.close();        }        返回CHECKDB!= NULL?真假;
    }    / **
     *在系统上创建一个空数据库,然后用自己的重写它
     *数据库。
     * * /
    公共无效importIfNotExist()抛出IOException        布尔dbExist = checkExist();        如果(dbExist){
            //什么也不做 - 已存在于数据库
        }其他{            //通过调用此方法与空的数据库将被创建成
            //默认的系统路径
            //你的应用程序,所以我们要能够覆盖
            //数据库与我们的数据库。
            this.getReadableDatabase();            尝试{                copyDatabase();            }赶上(IOException异常五){                抛出新的错误(错误复制数据库);            }
        }    }    私人无效copyDatabase()抛出IOException
        InputStream为= context.getAssets()开(数据库)。        OutputStream的OS =新的FileOutputStream(DB_PATH +数据库名);        字节[]缓冲区=新的字节[4096];
        INT长;
        而((长度= is.​​read(缓冲液))大于0){
            os.write(缓冲液,0,长度);
        }
        os.flush();
        os.close();
        is.close();
        this.close();
    }    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
    }    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){
    }}

根据关闭此教程。你把你的SQLite数据库文件在你的资源文件夹,当你运行code这将复制。我的版本允许成倍的数据库文件,因为它选择的路径。
要使用它做的事:

  AssetDatabaseHelper dbHelper =新AssetDatabaseHelper(
                getBaseContext(),SomeDataBase.SOME_DATABASE_NAME);
        尝试{
            dbHelper.importIfNotExist();
        }赶上(IOException异常五){
            e.printStackTrace();
        }

Possible Duplicate:
How to use an existing database with an Android application

I have a sqlite database file, and i want to use it in my app.

How do i do it ?

How do i push my db file to the emulator, and then use it in my code ?

Any solution is welcome. thx in advance, Tom.

解决方案

public class AssetDatabaseHelper extends SQLiteOpenHelper {

    private String dbName;
    private String db_path;
    private Context context;

    /**
     * A helper class to import db files.
     * 
     * @param base
     *            /app context
     * @param dbName
     *            The name of the db in asset folder .
     */
    public AssetDatabaseHelper(Context context, String dbName) {
        super(context, dbName, null, 1);
        this.dbName = dbName;
        this.context = context;
        db_path = "/data/data/" + context.getPackageName() + "/databases/";
    }

    /**
     * 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
     */
    public boolean checkExist() {

        SQLiteDatabase checkDB = null;

        try {
            String myPath = db_path + dbName;
            checkDB = SQLiteDatabase.openDatabase(myPath, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {
            e.printStackTrace();
            // database does't exist yet.

        } catch (Exception ep) {
            ep.printStackTrace();
        }

        if (checkDB != null) {

            checkDB.close();

        }

        return checkDB != null ? true : false;
    }

    /**
     * Creates a empty database on the system and rewrites it with your own
     * database.
     * */
    public void importIfNotExist() throws IOException {

        boolean dbExist = checkExist();

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

                throw new Error("Error copying database");

            }
        }

    }

    private void copyDatabase() throws IOException {
        InputStream is = context.getAssets().open(dbName);

        OutputStream os = new FileOutputStream(db_path + dbName);

        byte[] buffer = new byte[4096];
        int length;
        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }
        os.flush();
        os.close();
        is.close();
        this.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }

}

Based off of this tutorial. You put your sqlite database file in your asset folder and it will copy when you run the code. My version allows multiply databases files since it chooses the path. To use it do :

AssetDatabaseHelper dbHelper = new AssetDatabaseHelper(
                getBaseContext(), SomeDataBase.SOME_DATABASE_NAME);
        try {
            dbHelper.importIfNotExist();
        } catch (IOException e) {
            e.printStackTrace();
        }

这篇关于如何使用我自己的数据库 - 机器人的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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