DB文件的资产文件夹。它会被更新?它会、文件夹、资产、文件

2023-09-12 09:04:13 作者:半开半落

我是新来的的Andr​​oid SQLite的整个事情。这是我有:

db.sqlite 在我的资产文件夹。 该数据库的目的是为READ ONLY。用户不会写了。 当应用程序被更新时, db.sqlite 将被替换是一个新的数据库(我会删除旧文件,从项目,并添加新)

我很担心的是:

将旧数据库文件被删除? (这就是我想要的;换旧人用新) 为什么要问?因为当我调试我的应用程序,每一次我更新的数据库文件,我需要卸载,以强制更新从设备上的应用程序。将用户需要做同样的,当他们从Play商店更新我的应用程序?恐怕从。 这是否会受到影响我如何实现onCreate(SQLiteDatabase)和onUpgrade(SQLiteDatabase, INT,INT)? 如果是,什么是实现它们来满足我的要求吗?的正确方法

这是我如何扩展SQLiteOpenHelper类。我也跟着教程中,我发现在互联网上:

 进口java.io.FileOutputStream中;
进口java.io.IOException异常;
进口的java.io.InputStream;
进口java.io.OutputStream中;
进口android.content.Context;
进口android.database.Cursor;
进口android.database.SQLException;
进口android.database.sqlite.SQLiteDatabase;
进口android.database.sqlite.SQLiteException;
进口android.database.sqlite.SQLiteOpenHelper;
进口android.util.Log;

公共类DataBaseHelper扩展SQLiteOpenHelper {

    //而Android的默认系统应用程序的数据库路径。
    私有静态字符串DB_PATH =/data/data/com.mydomain.myapp/databases/;
    私有静态字符串DB_NAME =db.sqlite;
    私人SQLiteDatabase MyDatabase的;
    私人最终语境myContext;

    / *
     *构造函数
     *注意到并保持传递的上下文中的一个参考,以便访问该应用程序的资产和资源。
     * @参数方面
     ** /
    公共DataBaseHelper(上下文的背景下){

        超级(上下文,DB_NAME,空,1);
        this.myContext =背景;
    }

  / **
     *在系统上创建一个空数据库,并与自己的数据库重写它。
     * * /
    公共无效的CreateDatabase()抛出IOException异常{

        布尔dbExist = checkDataBase();

        如果(dbExist){
            //什么也不做 - 数据库中已存在
            Log.i(MyApp的,数据库中已存在);
        }其他{
            Log.i(MyApp的,数据库不存在);

            //通过调用这个方法和空的数据库将被创建到系统​​默认路径
               //你的应用程序,所以我们要能够覆盖数据库,我们的数据库。
            this.getReadableDatabase();

            尝试 {

                copyDataBase();

            }赶上(IOException异常E){

                抛出新的错误(错误复制数据库);

            }
        }

    }

    / **
     *检查数据库中已存在,以避免重新复制每次打开应用程序时,该文件。
     * @返回true,如果它存在,虚假的,如果它不
     * /
    私人布尔checkDataBase(){

        SQLiteDatabase CHECKDB = NULL;

        尝试{
            字符串mypath中= DB_PATH + DB_NAME;
            CHECKDB = SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READONLY);

        }赶上(SQLiteException E){

            //数据库的简化版,存在。

        }

        如果(CHECKDB!= NULL){

            checkDB.close();

        }

        返回CHECKDB!= NULL?真假;
    }

    / **
     *复制你的数据库从当地的资产文件夹在刚才创建的空数据库
     *系统文件夹,从那里它可以被访问和处理。
     *这是通过transfering字节流进行。
     * * /
    私人无效copyDataBase()抛出IOException异常{

        //打开本地数据库作为输入流
        InputStream的myInput = myContext.getAssets()开(DB_NAME)。

        //路径刚刚创建的空分贝
        字符串outFileName = DB_PATH + DB_NAME;

        //打开空分贝的输出流
        的OutputStream myOutput =新的FileOutputStream(outFileName);

        //传输的字节从inputfile中的OUTPUTFILE
        byte []的缓冲区=新的字节[1024];
        INT长;
        而((长度= myInput.read(缓冲液))大于0){
            myOutput.write(缓冲液,0,长度);
        }

        //关闭流
        myOutput.flush();
        myOutput.close();
        myInput.close();

    }

    公共无效的openDatabase()抛出的SQLException {

        //打开数据库
        字符串mypath中= DB_PATH + DB_NAME;
        MyDatabase的= SQLiteDatabase.openDatabase(mypath中,空,SQLiteDatabase.OPEN_READWRITE);

    }

    @覆盖
    市民同步无效的close(){

            如果(MyDatabase的!= NULL)
                myDataBase.close();

            super.close();

    }

    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){

    }

    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,诠释静态网页){

    }

  //我的公共辅助方法来访问,并从数据库中获取的内容放在这里
 

解决方案 手动解析APP数据篇

您不能替换 onUpgrade数据库(),因为这种方法的数据库已在使用。你必须做数据库打开前,像在构造你的 DatabaseHelper 。正如你不能使用 onUpgrade(),你必须自己管理数据库版本。使用共享preferences 是一个好办法。检查您的数据库是否存在(如果它已经从资产复制目录),并检查版本,如果数据库存在。现在,您可以删除旧的数据库和复制从资产新的。 请参阅下面的实现。

要标记您更新的应用程序发布新的数据库中的资产只是incerment DATABASE_VERSION 不变。

 私有静态类DatabaseHelper扩展SQLiteOpenHelper {

    私有静态最后弦乐DATABASE_NAME =database.db;
    私有静态最终诠释DATABASE_VERSION = 1;
    私有静态最后弦乐SP_KEY_DB_VER =db_ver;
    私人最终语境mContext;

    公共DatabaseHelper(上下文的背景下){
        超(背景下,DATABASE_NAME,空,DATABASE_VERSION);
        mContext =背景;
        初始化();
    }

    / **
     *初始化数据库。创建数据库,如果不存在。
     * /
    私人无效初始化(){
        如果(databaseExists()){
            共享preferences preFS = preferenceManager
                    .getDefaultShared preferences(mContext);
            INT dbVersion = prefs.getInt(SP_KEY_DB_VER,1);
            如果(DATABASE_VERSION!= dbVersion){
                文件DBFILE = mContext.getDatabasePath(DATABASE_NAME);
                如果(!dbFile.delete()){
                    Log.w(TAG,无法更新数据库);
                }
            }
        }
        如果(!databaseExists()){
            的CreateDatabase();
        }
    }

    / **
     *如果数据库文件存在,否则为false返回true。
     * @返回
     * /
    私人布尔databaseExists(){
        文件DBFILE = mContext.getDatabasePath(DATABASE_NAME);
        返回dbFile.exists();
    }

    / **
     *从资产目录复制它创建数据库。
     * /
    私人无效的CreateDatabase(){
        串parentPath = mContext.getDatabasePath(DATABASE_NAME).getParent();
        字符串路径= mContext.getDatabasePath(DATABASE_NAME).getPath();

        档案文件=新的文件(parentPath);
        如果(!file.exists()){
            如果(!file.mkdir()){
                Log.w(TAG,无法创建数据库目录);
                返回;
            }
        }

        InputStream的是= NULL;
        OutputStream的OS = NULL;
        尝试 {
            是= mContext.getAssets()开(DATABASE_NAME)。
            OS =新的FileOutputStream(路径);

            byte []的缓冲区=新的字节[1024];
            INT长;
            而((长度= is.​​read(缓冲液))大于0){
                os.write(缓冲液,0,长度);
            }
            os.flush();
            共享preferences preFS = preferenceManager
                    .getDefaultShared preferences(mContext);
            共享preferences.Editor编辑器= prefs.edit();
            editor.putInt(SP_KEY_DB_VER,DATABASE_VERSION);
            editor.commit();
        }赶上(IOException异常E){
            e.printStackTrace();
        } 最后 {
            如果(是!= NULL){
                尝试 {
                    is.close();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
            如果(OS!= NULL){
                尝试 {
                    os.close();
                }赶上(IOException异常E){
                    e.printStackTrace();
                }
            }
        }
    }

    @覆盖
    公共无效的onCreate(SQLiteDatabase DB){
    }

    @覆盖
    公共无效onUpgrade(SQLiteDatabase分贝,INT oldVersion,
            INT动态网页){
    }
}
 

I'm new to the Android SQLite whole thing. This is what I have:

I have db.sqlite in my assets folder. The intent of the db is to READ ONLY. The user will not write to it. When the app gets updated, the db.sqlite will be replaced be a new db (I'll delete the old file from the project and add the new one).

What I'm concerned about is:

Will the old db file gets deleted? (that's what I want; replacing the old one with the new one) Why ask? Because when I debug my app, each time I update the db file, I need to uninstall the app from the device in order to force the update. Will the users need to do the same when they update my app from the play store? I'm afraid from that. Will this be affected by how I implement onCreate(SQLiteDatabase) and onUpgrade(SQLiteDatabase, int, int)? If yes, what is the proper way to implement them to meet my requirement?

This is how I extends the SQLiteOpenHelper class. I followed a tutorial I found in the internet:

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;    
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

public class DataBaseHelper extends SQLiteOpenHelper{

    //The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.mydomain.myapp/databases/";
    private static String DB_NAME = "db.sqlite";
    private SQLiteDatabase myDataBase;   
    private final Context myContext;

    /*
     * Constructor
     * Takes and keeps a reference of the passed context in order to access to the application assets and resources.
     * @param context
     **/
    public DataBaseHelper(Context context) {

        super(context, DB_NAME, null, 1);
        this.myContext = context;
    }   

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

        boolean dbExist = checkDataBase();

        if(dbExist){
            //do nothing - database already exist
            Log.i("myapp", "database already exist");
        }else{
            Log.i("myapp", "database NOT exist");

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

            }
        }

    }

    /**
     * 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
     */
    private boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

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

        }catch(SQLiteException e){

            //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;
        myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

    }

    @Override
    public synchronized void close() {

            if(myDataBase != null)
                myDataBase.close();

            super.close();

    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

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

    }

  // My public helper methods to access and get content from the database go here

解决方案

You can't replace database in onUpgrade() because in this method the database is already in use. You have to do it before the database is open, like in a constructor of your DatabaseHelper. As you can't use onUpgrade(), you have to manage database versioning by yourself. Using SharedPreferences is a good way for it. You check if your database exists (if it is already copied from assets directory) and check the version if database exists. Now you can delete old database and copy new one from assets. See implementation below.

To mark your updated application is published with new database in assets just incerment DATABASE_VERSION constant.

private static class DatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "database.db";
    private static final int DATABASE_VERSION = 1;
    private static final String SP_KEY_DB_VER = "db_ver";
    private final Context mContext;

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        mContext = context;
        initialize();
    }

    /**
     * Initializes database. Creates database if doesn't exist.
     */
    private void initialize() {
        if (databaseExists()) {
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(mContext);
            int dbVersion = prefs.getInt(SP_KEY_DB_VER, 1);
            if (DATABASE_VERSION != dbVersion) {
                File dbFile = mContext.getDatabasePath(DATABASE_NAME);
                if (!dbFile.delete()) {
                    Log.w(TAG, "Unable to update database");
                }
            }
        }
        if (!databaseExists()) {
            createDatabase();
        }
    }

    /**
     * Returns true if database file exists, false otherwise.
     * @return
     */
    private boolean databaseExists() {
        File dbFile = mContext.getDatabasePath(DATABASE_NAME);
        return dbFile.exists();
    }

    /**
     * Creates database by copying it from assets directory.
     */
    private void createDatabase() {
        String parentPath = mContext.getDatabasePath(DATABASE_NAME).getParent();
        String path = mContext.getDatabasePath(DATABASE_NAME).getPath();

        File file = new File(parentPath);
        if (!file.exists()) {
            if (!file.mkdir()) {
                Log.w(TAG, "Unable to create database directory");
                return;
            }
        }

        InputStream is = null;
        OutputStream os = null;
        try {
            is = mContext.getAssets().open(DATABASE_NAME);
            os = new FileOutputStream(path);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = is.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
            SharedPreferences prefs = PreferenceManager
                    .getDefaultSharedPreferences(mContext);
            SharedPreferences.Editor editor = prefs.edit();
            editor.putInt(SP_KEY_DB_VER, DATABASE_VERSION);
            editor.commit();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
    }

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