How to use my own sqlite database?

后端 未结 7 503
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 15:20

I put my database field in \"assets\" folder. And use the code from this blog to copy the database to \"/data/data/my_packname/databases/\", (This copy code i run it in the

7条回答
  •  [愿得一人]
    2020-12-02 15:28

    I know this is an old post, but for those who still get here after a Google or a Bing search, this is the solution to the stated problem:

    in createDataBase() there is the following check;

    this.getReadableDatabase();
    

    This checks if there is already a database with the provided name and if not creates an empty database such that it can be overwritten with the one in the assets folder. On newer devices this works flawlessly but there are some devices on which this doesn't work. Mainly older devices. I do not know exactly why, but it seems like the getReadableDatabase() function not only gets the database but also opens it. If you then copy the database from the assets folder over it, it still has the pointer to an empty database and you will get table does not exist errors.

    So in order to make it work on all devices you should modify it to the following lines:

    SQLiteDatabase db = this.getReadableDatabase();
    if (db.isOpen()){
        db.close();
    }
    

    Even if the database is opened in the check, it is closed thereafter and it will not give you any more trouble.

提交回复
热议问题