[英]Import and Export SQLite Database in Android
我需要導入和導出我的SQlite數據庫。 我有我的ListAdapter和SQliteHelper類。 我通過參考一些文章編寫了代碼,但無法根據我的要求對其進行調整。 我有ListAdapter
類, SQLiteHelper
類, DbExportImport
類,在adapter.open()
和adapter.close()
出現錯誤。 很可能我的DbExportImport
類有錯誤。 我無法弄清楚/理解該代碼。
有人可以簡要解釋一下這里發生了什么。 有人可能會從中得到幫助。
這是DbExportImport
類
/** Imports the file at IMPORT_FILE **/
protected static boolean importIntoDb(Context ctx){
if( ! SdIsPresent() ) return false;
File importFile = IMPORT_FILE;
if( ! checkDbIsValid(importFile) ) return false;
try{
SQLiteDatabase sqlDb = SQLiteDatabase.openDatabase
(importFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = sqlDb.query(true, DATABASE_TABLE,
null, null, null, null, null, null, null
);
DbAdapter dbAdapter = new DbAdapter(ctx);
dbAdapter.open();
final int titleColumn = cursor.getColumnIndexOrThrow("title");
final int timestampColumn = cursor.getColumnIndexOrThrow("timestamp");
// Adds all items in cursor to current database
cursor.moveToPosition(-1);
while(cursor.moveToNext()){
dbAdapter.createQuote(
cursor.getString(titleColumn),
cursor.getString(timestampColumn)
);
}
sqlDb.close();
cursor.close();
dbAdapter.close();
} catch( Exception e ){
e.printStackTrace();
return false;
}
return true;
}
/** Given an SQLite database file, this checks if the file
* is a valid SQLite database and that it contains all the
* columns represented by DbAdapter.ALL_COLUMN_KEYS **/
protected static boolean checkDbIsValid( File db ){
try{
SQLiteDatabase sqlDb = SQLiteDatabase.openDatabase
(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);
Cursor cursor = sqlDb.query(true, DATABASE_TABLE,
null, null, null, null, null, null, null
);
// ALL_COLUMN_KEYS should be an array of keys of essential columns.
// Throws exception if any column is missing
for( String s : DbAdapter.ALL_COLUMN_KEYS ){
cursor.getColumnIndexOrThrow(s);
}
sqlDb.close();
cursor.close();
} //catching all exceptions here
return true;
}
我認為答案是,既不使用,也可能調整 DbAdapter 以適應。
看起來 DbAdapter 不是用於顯示目的的適配器,而是從導入的數據庫中調整/轉換/提取數據以適合本地使用。
ListAdapter 是用於顯示目的而不是用於轉換的適配器
總之方法importIntoDb
:-
checkDbIsValid
SQLiteDatabase sqlDb = SQLiteDatabase.openDatabase(db.getPath(), null, SQLiteDatabase.OPEN_READONLY);
- 將文件作為 SQLite 數據庫打開,如果文件不是 SQLite 數據庫,如 SQLite 所理解的那樣,則捕獲異常並且該方法返回 false。 這是可以/合適的,因為它是通用的。Cursor cursor = sqlDb.query(true, DATABASE_TABLE, null, null, null, null, null, null, null);
- 根據 DATABASE_TABLE 從表中提取包含所有列和所有行(重復項除外)的 Cursor,無論是什么。 這要求 DATABASE_TABLE,無論在哪里設置,都設置為導入數據庫中存在的表。for( String s : DbAdapter.ALL_COLUMN_KEYS ){ cursor.getColumnIndexOrThrow(s); }
for( String s : DbAdapter.ALL_COLUMN_KEYS ){ cursor.getColumnIndexOrThrow(s); }
-檢查是否在光標的列是所有的字符串數組,它是所述的類變量中發現DbAdapter
類。 這需要 DbAdapter 類。 所以這需要省略或調整。true
或false
,后者表明數據庫無效。title
和timestamp
。DbAdapter
的createQuote
方法循環游標,利用從title
和timestamp
列中提取的數據。 因此,這僅在源中存在所述列並且存在 DbAdapter 類的實例時才有效。....
要適應 DbAdapter,您可能必須繼續查看您復制的代碼並確定它是否適合您的目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.