errorCopyingDatabase从Assets文件夹到内存

时间:2012-12-14 03:56:28

标签: android sqlite database-connection

我正在关注此链接以打开与数据库的连接。但是,当我尝试打开它时,它会抛出一个异常,表示errorCopyingDatabase。我的数据库大小约为20MB。是因为它没有从Assets文件夹复制到内存或其他问题的大小。我确定我的代码很好,我还仔细检查了所有路径(一切似乎都很好)。我得到以下异常:

12-14 04:44:45.471: E/AndroidRuntime(512): java.lang.Error: ErrorCopyingDataBase
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.bondsms.db.DBHelper.createDataBase(DBHelper.java:42)
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.bondsms.db.DBAdapter.createDatabase(DBAdapter.java:37)
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.bondsms.BSGroupsActivity.loadAllGroupsFromDB(BSGroupsActivity.java:98)
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.bondsms.BSGroupsActivity.onCreate(BSGroupsActivity.java:55)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.os.Looper.loop(Looper.java:123)
12-14 04:44:45.471: E/AndroidRuntime(512):  at android.app.ActivityThread.main(ActivityThread.java:4627)
12-14 04:44:45.471: E/AndroidRuntime(512):  at java.lang.reflect.Method.invokeNative(Native Method)
12-14 04:44:45.471: E/AndroidRuntime(512):  at java.lang.reflect.Method.invoke(Method.java:521)
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-14 04:44:45.471: E/AndroidRuntime(512):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-14 04:44:45.471: E/AndroidRuntime(512):  at dalvik.system.NativeStart.main(Native Method)

1 个答案:

答案 0 :(得分:0)

我已经花了很多时间从资产中复制数据库,这是我要复制的类,它对我来说很好用,你可以使用它,也许它有帮助(记得改变DB_PATH =“/ data / data / [你的包裹] / databases /“。和DB_NAME =资产中你的数据名称。”

 public class DatabaseController extends SQLiteOpenHelper {

    // The Android's default system path of your application database.
    private static String DB_PATH = "/data/data/com.hanoifood/databases/";

    private static final String DB_NAME = "HanoiFood.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 DatabaseController(Context context) {
        super(context, DB_NAME, null, 1);
        this.myContext = context;
        try {
            createDataBase();
        } catch (IOException ioe) {
            throw new Error("Unable to create database");
        }
    }

    /**
     * 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
            myDataBase = getWritableDatabase();
        } else {
            myDataBase = getWritableDatabase();
            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 (Exception 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);

    }

    public Cursor query(String table, String[] columns, String selection,
            String[] selectionArgs, String groupBy, String having,
            String orderBy) {
        myDataBase = getWritableDatabase();
        Cursor cursor = myDataBase.query(table, columns, selection,
                selectionArgs, groupBy, having, orderBy);
        if (cursor == null) {
            return null;
        } else if (!cursor.moveToFirst()) {
            cursor.close();
            return null;
        }
        return cursor;
    }

    public long insert(String table, String nullColumnHack, ContentValues values) {
        long insertRet = myDataBase.insert(table, nullColumnHack, values);
        if (insertRet == -1) {
            Log.d("DungHV", "Insert db error");
        }
        return insertRet;
    }

    @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) {
        // TODO Auto-generated method stub
    }
}

在您的Activity简单调用中:

DatabaseContrller mdb = new DatabaseController(getApplicationContext());