在Android中使用資料庫,在一些情況下,需要導進一個已經有資料的資料庫,然後在程式中去調用它,來實現我們的功能。
比如在一個查詢信用卡歸屬銀行的小demo中,在輸入框輸入信用卡的前6位號碼(這6位號碼決定了信用卡的歸屬銀行),點擊查詢按鈕,就可以將其對應的銀行給顯示出來。
而卡表中的資料結構如下:
下面我們來看看,程式中是如何?這個功能的。
1)Asset檔案夾
在Asset檔案夾下面放上我們的資料庫:
2)建立一個CreditCardDb類。
在這個類中,我們要實現以下幾個功能:
2.1)要將資料庫從assets 檔案夾複製到手機自身的儲存當中去,即 /data/data/package/databases/。
public void copyDatabase(){String databasePath = mContext.getApplicationContext().getFilesDir().getAbsolutePath();databasePath = databasePath.substring(0, databasePath.lastIndexOf("/")) + "/databases";mDatabasePath = databasePath + "/" + DB_NAME;File dir = new File(databasePath);if(!dir.exists()){dir.mkdir();}File file = new File(mDatabasePath);if(!file.exists() || file.length() == 0){try {InputStream is = mContext.getAssets().open("database/"+DB_NAME);FileOutputStream fos = new FileOutputStream(mDatabasePath);byte[] buffer = new byte[8192];int count = 0;while ((count = is.read(buffer)) > 0) {fos.write(buffer, 0, count);}fos.close();is.close();} catch (IOException e) {e.printStackTrace();}}}在上面這個方法中,
a)首先找出資料庫在記憶體中存放的位置,即"/data/data/包名/databases/"下面,並建立對應的檔案,如下:
b)利用Context類的getAssets方法獲得AssetManager,然後調用其open方法,將對應路徑下的資料庫開啟,並寫到上一步找出來的檔案中去。
2.2)建立兩個方法,一個用來開啟資料庫,一個用來關閉資料庫,如下:
private void openDatabase(){Log.v(TAG, "Open DataBase : " + mDatabasePath);mCreditCardDb = SQLiteDatabase.openDatabase(mDatabasePath, null,SQLiteDatabase.NO_LOCALIZED_COLLATORS);}private void closeDatabase() {SQLiteDatabase.releaseMemory();mCreditCardDb.close();}
2.3)剩下的就是對資料庫表的操作了,根據前6位卡號查出所屬的銀行:
public String getBankByCreditCardNumber(String creditCardNumber){String sql = "select * from t_bank where card_bin = ? ";String bankName = "";openDatabase();Cursor cursor = mCreditCardDb.rawQuery(sql, new String[] {creditCardNumber});if(cursor == null){Log.e(TAG, "Cursor is null.");}else if(!cursor.moveToFirst()){Log.e(TAG, "Cursor has no records.");}else{bankName = cursor.getString(cursor.getColumnIndex(COL_BANK_NAME));}closeDatabase();return bankName;}
3)MainActivity在MainActivity的onCreate方法中,構造CreditCardDb類的對象,並調用其copyDatabase方法,如下:
mCreditCardDb = new CreditCardDb(this);mCreditCardDb.copyDatabase();
並建立一個AsyncTask,根據EditText輸入的值,去資料庫中查詢,將查詢的結果展示在TextView上,如下:
class CheckCreditCard extends AsyncTask{protected void onPostExecute(String result){tvBankName.setText(result);}@Overrideprotected String doInBackground(String... params) {String creditCardNumber = params[0];String bankName = "";if(creditCardNumber.length() >= 6){bankName = mCreditCardDb.getBankByCreditCardNumber(creditCardNumber.substring(0,6));}return bankName;}}
這裡只是簡單地展示如何去使用已存在資料的資料庫,原始碼下載。結束!