我是新手與android sqlite數據庫。現在我只是嘗試創建自定義數據庫管理器,並且在oncreate()函數中出現錯誤。我已經花了3天的時間弄清楚了,但不幸的是我仍然陷入了困境。任何輝煌的想法將不勝感激。Android的SQLite創建數據庫錯誤
public class DBManager extends SQLiteOpenHelper {
private SQLiteDatabase db;
private static Context myContext;
public static final String DB_NAME = "goldenland.db";
public static final String TB_CAT = "tbl_categories";
public static final String TB_ARTICLE = "tbl_articles";
public static final String TB_SUBCAT = "tbl_subcategories";
public static final String TB_SCHEDULE = "tbl_schedule";
public static final String TB_CONTENT = "tbl_contents";
public static final String TB_CITY = "tbl_cities";
public static final String name = "name";
public static String DB_PATH = "/data/data/com.gokiri.goldenland/databases/";
public DBManager(Context context) {
super(context, DB_NAME, null, 1);
DBManager.myContext = context;
}
public void createDataBase() throws IOException {
boolean dbExit = checkDataBase();
if (dbExit) {
System.out.println("Testing");
} else {
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDb = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDb = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLException e) {
}
if (checkDb != null) {
checkDb.close();
}
return checkDb != null ? true : false;
}
public void copyDataBase() throws IOException {
InputStream myInput = myContext.getAssets().open("goldenland_2.sqlite");
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLiteException {
String myPath = DB_PATH + DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
不應該靜態保存上下文。如果您從多個活動中訪問此代碼,則可能會導致崩潰。 – 2011-03-15 04:02:45
所以我怎麼能使用這個代碼從多個活動。它是否與手機讀/寫訪問有關? – geekmyo 2011-03-15 04:06:57