首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

Android SQLiteStudio 匯出 XML 資料庫檔案的使用方式

     編輯:程式設計疑難解答

問題背景

使用 SQLiteStudio 將資料庫匯出為 XML 格式,不知如何放置專案中、如何用 SQLiteOpenHelper 讀取、如何透過 SimpleCursorAdapter 顯示在 ListView。

核心觀念釐清

SQLiteOpenHelper 只能開啟 .db / .sqlite 二進制資料庫檔案,無法直接讀取 XML。 XML 匯出僅供資料交換/備份/人工閱讀。

正確流程

  1. 取得原始 .db 檔案(而非 XML)。
  2. 放置於 assets/ 目錄(唯讀)或啟動時複製到 /data/data/package/databases/(可寫)。
  3. 繼承 SQLiteOpenHelper,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(); }
    }
}
  1. 查詢並綁定 ListView:
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);

XML 檔案的替代用途

  • 若堅持使用 XML,需自行解析(XmlPullParser/DOM/SAX)轉為物件列表,再用 ArrayAdapter 顯示,失去 SQLite 索引/查詢/交易優勢。
  • 適用於極小型靜態資料(如設定檔、城市代碼表)。

結論:請使用原始 .db 檔配合 SQLiteOpenHelper,XML 僅作備份/遷移參考。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved