使用 SQLiteStudio 將資料庫匯出為 XML 格式,不知如何放置專案中、如何用 SQLiteOpenHelper 讀取、如何透過 SimpleCursorAdapter 顯示在 ListView。
SQLiteOpenHelper 只能開啟 .db / .sqlite 二進制資料庫檔案,無法直接讀取 XML。 XML 匯出僅供資料交換/備份/人工閱讀。
/data/data/package/databases/(可寫)。onCreate 中複製 assets 資料庫:public class DBHelper extends SQLiteOpenHelper {
private static String DB_PATH = "/data/data/com.example.app/databases/";
private static String DB_NAME = "mydb.db";
private Context context;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
copyDatabase();
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldV, int newV) {}
private void copyDatabase() {
try {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(DB_PATH + DB_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) os.write(buffer, 0, length);
os.flush(); os.close(); is.close();
} catch (IOException e) { e.printStackTrace(); }
}
}
DBHelper helper = new DBHelper(this);
SQLiteDatabase db = helper.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT _id, name, value FROM my_table", null);
String[] from = {"name", "value"};
int[] to = {R.id.tv_name, R.id.tv_value};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(
this, R.layout.list_item, cursor, from, to, 0);
listView.setAdapter(adapter);
XmlPullParser/DOM/SAX)轉為物件列表,再用 ArrayAdapter 顯示,失去 SQLite 索引/查詢/交易優勢。結論:請使用原始 .db 檔配合 SQLiteOpenHelper,XML 僅作備份/遷移參考。