我需要在我的Android应用程序中使用内部SQLite数据库使用Eclipse.i尝试了很多方法,但我无法得到解决方案。 提前致谢。
答案 0 :(得分: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();
}