-1

我需要使用 Eclipse 在我的 Android 应用程序中使用内部 SQLite 数据库。我尝试了很多方法,但我无法获得解决方案。提前致谢。

4

1 回答 1

1

试试这是解决方案:

private static String DB_PATH = "/data/data/your.package/databases/";
    private static String DB_NAME = "namedatabase.sqlite";
    private SQLiteDatabase db;
    private final Context context;

    public DataBaseWorker(Context ctx) {
        super(ctx, DB_NAME, null, 1);
        context = ctx;
    }

    public void createDataBase() throws IOException {
        boolean dbExist = checkDataBase();
        if (!dbExist) {
            File wallpaperDirectory = new File(
                    "/data/data/your.package/databases/");
            wallpaperDirectory.mkdirs();
            try {
                copyDataBase();
            } catch (Exception e) {
                Log.v("CREATEDATABASE", "not copy DB");
            } finally {
                this.close();
            }
        }
    }

    public boolean checkDataBase() {
        SQLiteDatabase checkDB = null;
        try {
            String Path = DB_PATH + DB_NAME;

            checkDB = SQLiteDatabase.openDatabase(Path, null,
                    SQLiteDatabase.OPEN_READONLY);

        } catch (SQLiteException e) {
            Log.v("CHECKDB", "not check DB");
        }

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

        return checkDB != null ? true : false;
    }

    private void copyDataBase() throws IOException {
        InputStream input = context.getAssets().open(DB_NAME);
        String outFileName = DB_PATH + DB_NAME;
        OutputStream output = new FileOutputStream(outFileName);

        byte[] buffer = new byte[1024];
        int length;
        while ((length = input.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        input.close();
        output.close();
    }

    public void openDataBase() throws SQLException {
        String Path = DB_PATH + DB_NAME;        
        db = SQLiteDatabase.openDatabase(Path, null,
                SQLiteDatabase.OPEN_READWRITE);
    }

    public void close() {
        if (db != null)
            db.close();
        super.close();
    }

    public void exec(String query) {
        db.execSQL(query);
        db.close();
    }
于 2012-09-13T07:04:36.337 回答