数据库未从资产文件夹复制到设备

时间:2012-12-29 11:12:13

标签: android sqlite assets

我的assets文件夹中有.db文件。我已将其复制到模拟器中的data/data/<packagename>/databases/文件夹中并且工作正常..

但是当我在设备上运行时,它会强行关闭。它正在显示

SQLite exception: no such table: tbl_user

这是我的代码..

public class DatabaseHelper extends SQLiteOpenHelper {

        public DatabaseHelper() {

            super(dataContext, DATABASE_NAME, null, 1);

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

            Log.d("PATH", DB_PATH);

            boolean dbExist = checkDataBase();
            if (!dbExist) {

                this.getReadableDatabase();
                try {
                    copyDataBase();

                } catch (IOException e) {
                    Log.d("Error", e.toString());
                }
            }

        }

        private void copyDataBase() throws IOException {
            // TODO Auto-generated method stub

            InputStream inFile = dataContext.getAssets().open(DATABASE_NAME);
            String outFileName = DB_PATH + DATABASE_NAME;
            OutputStream myOutput = new FileOutputStream(outFileName);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = inFile.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);
            }
            // Close the streams
            myOutput.flush();
            myOutput.close();
            inFile.close();
        }

        private boolean checkDataBase() {
            // TODO Auto-generated method stub

            File dbFile = new File(DB_PATH + DATABASE_NAME);

            return dbFile.exists();

        }

我是否应该采取其他措施将该数据库复制到设备???

谢谢..

2 个答案:

答案 0 :(得分:5)

得到答案...... :)

从这里开始..

http://www.anddev.org/networking-database-problems-f29/missing-table-in-sqlite-with-specific-version-of-desire-hd-t50364.html

这是版本2.3.6的问题...它正在与其他设备一起工作......只需添加三行来解决问题......

boolean dbExist = checkDataBase();
        SQLiteDatabase db_Read = null;
        if (!dbExist) 
        {
            db_Read = this.getReadableDatabase(); 
            db_Read.close();

            try 
            {
                copyDataBase();
            } 
            catch (IOException e) 
            {
                Log.d("Error", e.toString());
            }
        }

答案 1 :(得分:0)

只需将资产文件夹中的数据库文件.db扩展名更改为.png或其将在2.1,2.2及更高版本设备中使用的任何其他压缩格式