-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 に答える