Android學習小Demo(16)Android中使用已存在資料的SqliteDatabase

來源:互聯網
上載者:User

在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;}}

這裡只是簡單地展示如何去使用已存在資料的資料庫,原始碼下載。結束!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.