如何将预先存在的sqlite数据库文件从资源复制到数据库文件夹?

时间:2011-09-17 22:35:37

标签: android sqlite

我在使用我的应用程序时遇到了麻烦,我花了好几个小时没有成功。

我创建了一个数据库,其中包含一个包含1000个预先存在的行的表(在我的桌面上完成)。由于数据量的原因,我不希望在应用程序运行时填充应用程序数据库。所以我打算让应用程序部署将assets文件夹中的现有文件复制到数据库文件夹中。 必须是人们发展中的一种重新出现的模式。

实现此目的的代码部分来自此链接: http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/

很抱歉粘贴了一些代码,我通常不会这样做但是我已经花了好几个小时没有看到解决方案。

我的主要活动是这样的:

    public class MainActivity extends ListActivity {
        /** Called when the activity is first created. */


        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);


            try {
            new DbHelper(this).createDataBase();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }                        
            //....   
        }
}

在DbHelper中,调用copyDataBase来复制资产数据库。 当我打开数据库时,不存在任何表,只存在android_metadata表。所以复制失败了???

DbHelper是这样的:

public class DbHelper extends SQLiteOpenHelper {
    private static final String TAG= "DbHelper";

    static final String DB_NAME = "mydatabase.sqlite";
    static final int DB_VERSION = 1;
    private static String DB_PATH = "";

    private Context myContext;

    public DbHelper(Context context)
    {
        super(context,  DB_NAME, null, DB_VERSION);
        this.myContext = context;

        DB_PATH = "/data/data/" + context.getApplicationContext().getPackageName() + "/databases/";

    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate called");

        try {
            Log.d(TAG, "Copying database...");
            copyDataBase();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // TODO Auto-generated method stub

    }

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

    }

    public boolean checkDataBase(){

        SQLiteDatabase checkDB = null;

        try{
            String myPath = DB_PATH + DB_NAME;
            checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
            Log.d(TAG, "db exists");
            }
        catch(SQLiteException e){
             //database does't exist yet.
            Log.d(TAG, "db doesn't exist");

         }

         if(checkDB != null){
             checkDB.close();
         }

         return checkDB != null ? true : false;
    }

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

任何人都可以解释为什么这不起作用吗?

2 个答案:

答案 0 :(得分:0)

查看基本相同的代码,您应该:

InputStream = myContext.getResources().getAssets().open(DB_NAME);

我不确定Context.getAssetsResources.getAssets之间的区别,但请试一试。

答案 1 :(得分:0)

我认为您的SQLiteOpenHelper的onCreate方法可能不是您想要复制的地方。您想在尝试打开/创建文件之前复制该文件。

为了进行调试,我已经多次从应用程序的启动代码中完成了这项工作,并且工作正常:

    copyFile("/sdcard/dbs/latest_database.db", context.getDatabasePath("DatabaseNameHere").getPath());

(copyFile只是一个小帮手函数,可以达到你所期望的效果。)

您应该能够调整它以从资产目录而不是SD卡复制它。

请注意,当我这样做时,我正在复制一个我从应用程序的上一版本中提取的数据库。如果您尝试复制使用非android sqlite工具创建的数据库,则可能需要先添加android_metadata表。就我所见,这只是一个列(“locale”)和一行(例如“en_US”)。