安卓第七夜 雅典學院


作者:Vamei 出處:http://www.cnblogs.com/vamei 歡迎轉載,也請保留這段聲明。謝謝! 

 

我之前只使用了一種持續保存數據的方法,即SharedPreferences。然而,SharedPreferences只能存儲少量松散的數據,並不適合大量數據的存儲。安卓帶有SQLite數據庫,它是一個簡單版本的關系型數據庫,可以應對更復雜的數據存取需求。我將在這里說明安卓中該數據庫的使用方法。這里只專注於安卓中SQLite數據庫的接口使用,並沒有深入關系型數據庫和SQL語言的背景知識。

《雅典學院》是拉斐爾的畫。他在這幅壁畫中描繪了許多古典時代的哲學家,如蘇格拉底、柏拉圖、亞里士多德等。畫中的哲學家生活在不同的時代,硬是被拉斐爾放在了一起。

 

描述

這一講,我將繼續拓展應用的功能,讓應用存儲多個聯系人信息。相關的安卓知識點包括:

  • 使用SQLite數據庫。
  • 使用adb命令行工具查看數據庫。

在這一講中的新增代碼,都將放入到me.vamei.vamei.model包中。右鍵點擊src文件夾,選擇New -> Package,就可以在src中創建新的包。

 

創建對象模型

在面向對象語言中,對象用於描述和操作數據。我使用兩個類Category和Contact的對象:

  • Category:聯系人分類。包括id屬性和name屬性。
  • Contact:聯系人。包括id,url,name和categoryId屬性。其中categoryId是Contact所屬Category對象的id。

 

 

Category類與Contact類 

Category類有id和name屬性,分別存儲序號和分類姓名。它定義在Category.java中:

package me.vamei.vamei.model; public class Category { int id; String name; public Category() {} public Category(String name) { this.name = name; } public Category(int id, String name) { this.id = id; this.name = name; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } }

 

Contact類的定義在Contact.java中。它的id和name屬性,用於記錄聯系人序號和聯系人姓名。url用以存儲聯系人的博客地址。Contact還有一個Category類的屬性。這是用組合的方式,說明了Contact所歸屬的Category。

 

package me.vamei.vamei.model; public class Contact { int id; Category category; String name; String url; public Contact() { } public Contact(String name, String url, Category category) { this.name = name; this.url  = url; this.category = category; } public Contact(int id, String name, String url, Category category) { this.id   = id; this.name = name; this.url  = url; this.category = category; } public int getId() { return this.id; } public void setId(int id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getUrl() { return this.url; } public void setUrl(String url) { this.url = url; } public Category getCategory() { return this.category; } public void setCategory(Category category) { this.category = category; } }

 

上面的對象數據模型只是存活於內存中,只能臨時保存數據。要想持續的保存數據,我們還要想辦法把對象中的數據放入SQLite的表中。安卓提供了一個類來實現相關的交互,即SQLiteOpenHelper。

 

SQLiteOpenHelper

SQLiteOpenHelper是對象數據模型和關系型數據庫的一個接口。我通過繼承該類,對每一個數據庫建立一個子類。這個子類即代表了該數據庫。數據庫操作的相關SQL語句都存放在該子類中。

 

下面的contactsManager類管理了"contactsManager"數據庫。這個類定義在ContactsManager.java中。我需要覆蓋該類的onCreate()onUpgrade()方法,用於說明創建和升級時,數據庫將采取的行動,比如在創建時新建數據庫的表。SQLite利用SQL語言進行操作,所以建表的過程就是執行SQL的"create table ..."語句。在該類中,我還額外增加CRUD方法,即新建(Create)、讀取(Read)、更新(Update)、刪除(Delete)數據庫記錄。

 

package me.vamei.vamei.model; import java.util.LinkedList; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; /* * Database Manager * Interfacing between the database and the object models * */
public class ContactsManager extends SQLiteOpenHelper { // All Static variables // Database Version
    private static final int DATABASE_VERSION = 1; // Database Name
    private static final String DATABASE_NAME = "contactsManager"; // Contacts table name
    private static final String TABLE_CONTACTS   = "contacts"; private static final String TABLE_CATEGORIES = "categories"; // Contacts Table Columns names
    private static final String KEY_ID   = "id"; private static final String KEY_CATEGORY_ID = "category_id"; private static final String KEY_NAME = "name"; private static final String KEY_URL  = "url"; // Constructor
    public ContactsManager(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String CREATE_CATEGORIES_TABLE = "CREATE TABLE " + TABLE_CATEGORIES + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," 
                + KEY_NAME + " TEXT UNIQUE" + ")"; String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + KEY_NAME + " TEXT," 
                + KEY_CATEGORY_ID + " INTEGER," + KEY_URL + " TEXT," 
                + "FOREIGN KEY(" + KEY_CATEGORY_ID +") REFERENCES " 
                + TABLE_CATEGORIES + "(" + KEY_ID + ")"
                + ")"; db.execSQL(CREATE_CATEGORIES_TABLE); db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CATEGORIES); db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS); // Create tables again
 onCreate(db); } /** * All CRUD(Create, Read, Update, Delete) Operations for Contacts */
    
    public void createContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); values.put(KEY_URL, contact.getUrl()); values.put(KEY_CATEGORY_ID, contact.getCategory().getId()); db.insert(TABLE_CONTACTS, null, values); db.close(); } // Getting single contact
    public Contact getContact(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID, KEY_NAME, KEY_URL, KEY_CATEGORY_ID }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst(); Category category = getCategory(Integer.parseInt(cursor.getString(3))); Contact contact = new Contact(Integer.parseInt(cursor.getString(0)), cursor.getString(1), cursor.getString(2), category); // return contact
        return contact; } // Getting all contacts
    public List<Contact> getAllContacts() { List<Contact> contacts = new LinkedList<Contact>(); // build the query
        String query = "SELECT  * FROM " + TABLE_CONTACTS; // get reference to writable DB
        SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery(query, null); // iterate over all retrieved rows
        Contact contact = null; if (cursor.moveToFirst()) { do { contact = new Contact(); contact.setId(Integer.parseInt(cursor.getString(0))); contact.setName(cursor.getString(1)); contact.setUrl(cursor.getString(2)); Category category = getCategory(Integer.parseInt(cursor.getString(3))); contact.setCategory(category); // Add category to categories
 contacts.add(contact); } while (cursor.moveToNext()); } // return books
        return contacts; } // Updating single contact
    public int updateContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, contact.getName()); values.put(KEY_URL, contact.getUrl()); values.put(KEY_CATEGORY_ID, contact.getCategory().getId()); // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?", new String[] { String.valueOf(contact.getId()) }); } // Deleting single contact
    public void deleteContact(Contact contact) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_CONTACTS, KEY_ID + " = ?", new String[] { String.valueOf(contact.getId()) }); db.close(); } /** * All CRUD(Create, Read, Update, Delete) Operations for Contacts */
    
    // Adding a single category
    public void createCategory(Category category) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, category.getName()); db.insert(TABLE_CATEGORIES, null, values); db.close(); } // Getting single contact
    public Category getCategory(int id) { SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.query(TABLE_CATEGORIES, new String[] { KEY_ID, KEY_NAME }, KEY_ID + "=?", new String[] { String.valueOf(id) }, null, null, null, null); if (cursor != null) cursor.moveToFirst(); Category category = new Category(Integer.parseInt(cursor.getString(0)), cursor.getString(1)); // return contact
        return category; } // Getting all categories
    public List<Category> getAllCategories() { List<Category> categories = new LinkedList<Category>(); // build the query
        String query = "SELECT  * FROM " + TABLE_CATEGORIES; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(query, null); // iterate over the categories
        Category category = null; if (cursor.moveToFirst()) { do { category = new Category(); category.setId(Integer.parseInt(cursor.getString(0))); category.setName(cursor.getString(1)); // Add category to categories
 categories.add(category); } while (cursor.moveToNext()); } // return categories
        return categories; } // Updating single contact
    public int updateCategory(Category category) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(KEY_NAME, category.getName()); // updating row
        return db.update(TABLE_CATEGORIES, values, KEY_ID + " = ?", new String[] { String.valueOf(category.getId()) }); } // Deleting single contact
    public void deleteCategory(Category category) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(TABLE_CATEGORIES, KEY_ID + " = ?", new String[] { String.valueOf(category.getId()) }); db.close(); } }

 

在屬性中,我說明了數據庫的一些相關參數,如數據庫版本,數據庫名和表名。我還在數據庫中定義了表的屬性名稱。

onCreate()方法負責了表格的創建。而onUpgrade()方法中,則說明了數據庫升級后,需要刪除所有數據,重新創建表格。

此外,我還編寫了進行數據庫操作的CRUD方法。這些方法的核心實際上是一些操作數據庫的SQL語句。如果上面的CRUD方法無法滿足數據庫操作的需求,你還可以根據需要增加方法。

 

 

數據庫使用

在之前編寫的MainActivity的onCreate()方法中,調用數據庫:

...... @Override public void onCreate() { ...... ContactsManager cm = new ContactsManager(this); // add categories to the database
        cm.createCategory(new Category("Friend")); cm.createCategory(new Category("Enermy")); // add contact to the database
        Category cat1 = cm.getCategory(1); cm.createContact(new Contact("vamei", "http://www.cnblogs.com/vamei", cat1)); // retrieve and display
        Toast.makeText(this, cm.getContact(1).getName(), Toast.LENGTH_LONG).show(); } ......

上面進行了簡單的數據存儲和讀取。效果如下:

我將在下一講中,利用數據庫實現更復雜的功能。

 

adb查看數據庫

adb是安卓提供的命令行工具。你可以在計算機上使用該命令行,查看安卓設備中的SQLite數據庫。首先,查看連接在計算機上的安卓設備:

adb devices -l

該命令會列出所有的設備及其端口。

 

打開某個設備:

adb -s 192.168.56.101:5555 shell

-s參數說明了設備的端口。這樣就進入了該設備的命令行Shell。我們可以在該命令行使用常用的如cd, ls, pwd命令。

 

應用的數據庫存在下面文件夾中:

/data/data/me.vamei.vamei/databases/

其中的me.vamei.vamei是我們正在編寫的應用。

 

之前部分已經創建了contactsManager數據庫。使用sqlite3打開:

sqlite3 /data/data/me.vamei.vamei/databases/contactsManager

將進入SQLite提供的命令行。可以按照SQLite終端的使用方法操作。例如

.tables   #顯示所有的表格

或者直接使用SQL語句:

select * from categories;

使用結束后,按Ctrl + D推出SQLite終端。

 

在開發過程中,這一命令行工具可以幫助我們快捷查詢數據庫狀態,方便debug。

 

總結

SQLiteOpenHelper

adb終端查看數據庫


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM