SQLite。

       先上代码

[java] view plaincopy

  1. 1.     @Override  
  2. 2.     protected void onCreate(Bundle savedInstanceState) {  
  3. 3.         super.onCreate(savedInstanceState);  
  4. 4.           
  5.         //打开或创建test.db数据库  
  6. 6.         SQLiteDatabase db = openOrCreateDatabase("test.db", Context.MODE_PRIVATE, null);  
  7. 7.         db.execSQL("DROP TABLE IF EXISTS person");  
  8.         //创建person表  
  9. 9.         db.execSQL("CREATE TABLE person (_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age SMALLINT)");  
  10.         Person person = new Person();  
  11.         person.name = "john";  
  12.         person.age = 30;  
  13. 13.         //插入数据  
  14.         db.execSQL("INSERT INTO person VALUES (NULL, ?, ?)", new Object[]{person.name, person.age});  
  15.           
  16.         person.name = "david";  
  17.         person.age = 33;  
  18. 18.         //ContentValues以键值对的形式存放数据  
  19.         ContentValues cv = new ContentValues();  
  20.         cv.put("name", person.name);  
  21.         cv.put("age", person.age);  
  22. 22.         //插入ContentValues中的数据  
  23.         db.insert("person", null, cv);  
  24.           
  25.         cv = new ContentValues();  
  26.         cv.put("age", 35);  
  27. 27.         //更新数据  
  28.         db.update("person", cv, "name = ?", new String[]{"john"});  
  29.           
  30.         Cursor c = db.rawQuery("SELECT * FROM person WHERE age >= ?", new String[]{"33"});  
  31.         while (c.moveToNext()) {  
  32.             int _id = c.getInt(c.getColumnIndex("_id"));  
  33.             String name = c.getString(c.getColumnIndex("name"));  
  34.             int age = c.getInt(c.getColumnIndex("age"));  
  35.             Log.i("db", "_id=>" + _id + ", name=>" + name + ", age=>" + age);  
  36.         }  
  37.         c.close();  
  38.           
  39. 39.         //删除数据  
  40.         db.delete("person", "age < ?", new String[]{"35"});  
  41.           
  42. 42.         //关闭当前数据库  
  43.         db.close();  
  44.           
  45. 45.         //删除test.db数据库  
  46. //      deleteDatabase("test.db");  
  47.     }  

在执行完上面的代码后,系统就会在/data/data/[PACKAGE_NAME]/databases目录下生成一个“test.db”的数据库文件,如图:

 

上面的代码中基本上囊括了大部分的数据库操作;对于添加、更新和删除来说,我们都可以使用

[java] view plaincopy

1. db.executeSQL(String sql);  

  1. db.executeSQL(String sql, Object[] bindArgs);//sql语句中使用占位符,然后第二个参数是实际的参数集  

除了统一的形式之外,他们还有各自的操作方法:

[java] view plaincopy

1. db.insert(String table, String nullColumnHack, ContentValues values);  

2. db.update(String table, Contentvalues values, String whereClause, String whereArgs);  

3. db.delete(String table, String whereClause, String whereArgs);  

以上三个方法的第一个参数都是表示要操作的表名;insert中的第二个参数表示如果插入的数据每一列都为空的话,需要指定此行中某一列的名称,系统将此列设置为NULL,不至于出现错误;insert中的第三个参数是ContentValues类型的变量,是键值对组成的Map,key代表列名,value代表该列要插入的值;update的第二个参数也很类似,只不过它是更新该字段key为最新的value值,第三个参数whereClause表示WHERE表达式,比如“age > ? and age < ?”等,最后的whereArgs参数是占位符的实际参数值;delete方法的参数也是一样。

下面来说说查询操作。查询操作相对于上面的几种操作要复杂些,因为我们经常要面对着各种各样的查询条件,所以系统也考虑到这种复杂性,为我们提供了较为丰富的查询形式:

[java] view plaincopy

1. db.rawQuery(String sql, String[] selectionArgs);  

2. db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy);  

3. db.query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  

4. db.query(String distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit);  

上面几种都是常用的查询方法,第一种最为简单,将所有的SQL语句都组织到一个字符串中,使用占位符代替实际参数,selectionArgs就是占位符实际参数集;下面的几种参数都很类似,columns表示要查询的列所有名称集,selection表示WHERE之后的条件语句,可以使用占位符,groupBy指定分组的列名,having指定分组条件,配合groupBy使用,orderBy指定排序的列名,limit指定分页参数,distinct可以指定“true”或“false”表示要不要过滤重复值。需要注意的是,selection、groupBy、having、orderBy、limit这几个参数中不包括“WHERE”、“GROUP BY”、“HAVING”、“ORDER BY”、“LIMIT”等SQL关键字。
最后,他们同时返回一个Cursor对象,代表数据集的游标,有点类似于JavaSE中的ResultSet。

下面是Cursor对象的常用方法:

[java] view plaincopy

  1. c.move(int offset); //以当前位置为参考,移动到指定行  
  2. c.moveToFirst();    //移动到第一行  
  3. c.moveToLast();     //移动到最后一行  
  4. c.moveToPosition(int position); //移动到指定行  
  5. c.moveToPrevious(); //移动到前一行  
  6. c.moveToNext();     //移动到下一行  
  7. c.isFirst();        //是否指向第一条  
  8. c.isLast();     //是否指向最后一条  
  9. c.isBeforeFirst();  //是否指向第一条之前  

10. c.isAfterLast();    //是否指向最后一条之后  

  1. c.isNull(int columnIndex);  //指定列是否为空(列基数为0)  

12. c.isClosed();       //游标是否已关闭  

13. c.getCount();       //总数据项数  

14. c.getPosition();    //返回当前游标所指向的行数  

15. c.getColumnIndex(String columnName);//返回某列名对应的列索引值  

16. c.getString(int columnIndex);   //返回当前行指定列的值  

在上面的代码示例中,已经用到了这几个常用方法中的一些,关于更多的信息,大家可以参考官方文档中的说明。

最后当我们完成了对数据库的操作后,记得调用SQLiteDatabase的close()方法释放数据库连接,否则容易出现SQLiteException。

上面就是SQLite的基本应用,但在实际开发中,为了能够更好的管理和维护数据库,我们会封装一个继承自SQLiteOpenHelper类的数据库操作类,然后以这个类为基础,再封装我们的业务逻辑方法。

下面,我们就以一个实例来讲解具体的用法,我们新建一个名为db的项目,结构如下:

 

其中DBHelper继承了SQLiteOpenHelper,作为维护和管理数据库的基类,DBManager是建立在DBHelper之上,封装了常用的业务方法,Person是我们的person表对应的JavaBean,MainActivity就是我们显示的界面。

下面我们先来看一下DBHelper:

[java] view plaincopy

1. package com.scott.db;  

  1. 2.   

3. import android.content.Context;  

4. import android.database.sqlite.SQLiteDatabase;  

5. import android.database.sqlite.SQLiteOpenHelper;  

  1. 6.   

7. public class DBHelper extends SQLiteOpenHelper {  

  1. 8.   
  2. 9.     private static final String DATABASE_NAME = "test.db";  
  3.     private static final int DATABASE_VERSION = 1;  
  4.       
  5.     public DBHelper(Context context) {  
  6. 13.         //CursorFactory设置为null,使用默认值  
  7.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  8.     }  
  9.   
  10. 17.     //数据库第一次被创建时onCreate会被调用  
  11.     @Override  
  12.     public void onCreate(SQLiteDatabase db) {  
  13.         db.execSQL("CREATE TABLE IF NOT EXISTS person" +  
  14.                 "(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR, age INTEGER, info TEXT)");  
  15.     }  
  16.   
  17.     //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade  
  18.     @Override  
  19.     public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  20.         db.execSQL("ALTER TABLE person ADD COLUMN other STRING");  
  21.     }  
  22. }  

正如上面所述,数据库第一次创建时onCreate方法会被调用,我们可以执行创建表的语句,当系统发现版本变化之后,会调用onUpgrade方法,我们可以执行修改表结构等语句。

为了方便我们面向对象的使用数据,我们建一个Person类,对应person表中的字段,如下:

[java] view plaincopy

1. package com.scott.db;  

  1. 2.   

3. public class Person {  

  1. 4.     public int _id;  
  2. 5.     public String name;  
  3. 6.     public int age;  
  4. 7.     public String info;  
  5. 8.       
  6. 9.     public Person() {  
  7.     }  
  8.       
  9.     public Person(String name, int age, String info) {  
  10.         this.name = name;  
  11.         this.age = age;  
  12.         this.info = info;  
  13.     }  
  14. }  

然后,我们需要一个DBManager,来封装我们所有的业务方法,代码如下:

[java] view plaincopy

1. package com.scott.db;  

  1. 2.   

3. import java.util.ArrayList;  

4. import java.util.List;  

  1. 5.   

6. import android.content.ContentValues;  

7. import android.content.Context;  

8. import android.database.Cursor;  

9. import android.database.sqlite.SQLiteDatabase;  

  1.   
  2. public class DBManager {  
  3.     private DBHelper helper;  
  4.     private SQLiteDatabase db;  
  5.       
  6.     public DBManager(Context context) {  
  7.         helper = new DBHelper(context);  
  8.         //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName, 0, mFactory);  
  9. 18.         //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里  
  10.         db = helper.getWritableDatabase();  
  11.     }  
  12.       
  13.     /** 
  14.      * add persons 
  15.      * @param persons 
  16.      */  
  17.     public void add(List<Person> persons) {  
  18. 27.         db.beginTransaction();  //开始事务  
  19.         try {  
  20.             for (Person person : persons) {  
  21.                 db.execSQL("INSERT INTO person VALUES(null, ?, ?, ?)", new Object[]{person.name, person.age, person.info});  
  22.             }  
  23. 32.             db.setTransactionSuccessful();  //设置事务成功完成  
  24.         } finally {  
  25. 34.             db.endTransaction();    //结束事务  
  26.         }  
  27.     }  
  28.       
  29.     /** 
  30.      * update person's age 
  31.      * @param person 
  32.      */  
  33.     public void updateAge(Person person) {  
  34.         ContentValues cv = new ContentValues();  
  35.         cv.put("age", person.age);  
  36.         db.update("person", cv, "name = ?", new String[]{person.name});  
  37.     }  
  38.       
  39.     /** 
  40.      * delete old person 
  41.      * @param person 
  42.      */  
  43.     public void deleteOldPerson(Person person) {  
  44.         db.delete("person", "age >= ?", new String[]{String.valueOf(person.age)});  
  45.     }  
  46.       
  47.     /** 
  48.      * query all persons, return list 
  49.      * @return List<Person> 
  50.      */  
  51.     public List<Person> query() {  
  52.         ArrayList<Person> persons = new ArrayList<Person>();  
  53.         Cursor c = queryTheCursor();  
  54.         while (c.moveToNext()) {  
  55.             Person person = new Person();  
  56.             person._id = c.getInt(c.getColumnIndex("_id"));  
  57.             person.name = c.getString(c.getColumnIndex("name"));  
  58.             person.age = c.getInt(c.getColumnIndex("age"));  
  59.             person.info = c.getString(c.getColumnIndex("info"));  
  60.             persons.add(person);  
  61.         }  
  62.         c.close();  
  63.         return persons;  
  64.     }  
  65.       
  66.     /** 
  67.      * query all persons, return cursor 
  68.      * @return  Cursor 
  69.      */  
  70.     public Cursor queryTheCursor() {  
  71.         Cursor c = db.rawQuery("SELECT * FROM person", null);  
  72.         return c;  
  73.     }  
  74.       
  75.     /** 
  76.      * close database 
  77.      */  
  78.     public void closeDB() {  
  79.         db.close();  
  80.     }  
  81. }  

我们在DBManager构造方法中实例化DBHelper并获取一个SQLiteDatabase对象,作为整个应用的数据库实例;在添加多个Person信息时,我们采用了事务处理,确保数据完整性;最后我们提供了一个closeDB方法,释放数据库资源,这一个步骤在我们整个应用关闭时执行,这个环节容易被忘记,所以朋友们要注意。

我们获取数据库实例时使用了getWritableDatabase()方法,也许朋友们会有疑问,在getWritableDatabase()和getReadableDatabase()中,你为什么选择前者作为整个应用的数据库实例呢?在这里我想和大家着重分析一下这一点。

我们来看一下SQLiteOpenHelper中的getReadableDatabase()方法:

[java] view plaincopy

1. public synchronized SQLiteDatabase getReadableDatabase() {  

  1. 2.     if (mDatabase != null && mDatabase.isOpen()) {  
  2.         // 如果发现mDatabase不为空并且已经打开则直接返回  
  3. 4.         return mDatabase;  
  4. 5.     }  
  5. 6.   
  6. 7.     if (mIsInitializing) {  
  7.         // 如果正在初始化则抛出异常  
  8. 9.         throw new IllegalStateException("getReadableDatabase called recursively");  
  9.     }  
  10.   
  11.     // 开始实例化数据库mDatabase  
  12.   
  13.     try {  
  14. 15.         // 注意这里是调用了getWritableDatabase()方法  
  15.         return getWritableDatabase();  
  16.     } catch (SQLiteException e) {  
  17.         if (mName == null)  
  18.             throw e; // Can't open a temp database read-only!  
  19.         Log.e(TAG, "Couldn't open " + mName + " for writing (will try read-only):", e);  
  20.     }  
  21.   
  22. 23.     // 如果无法以可读写模式打开数据库 则以只读方式打开  
  23.   
  24.     SQLiteDatabase db = null;  
  25.     try {  
  26.         mIsInitializing = true;  
  27. 28.         String path = mContext.getDatabasePath(mName).getPath();// 获取数据库路径  
  28. 29.         // 以只读方式打开数据库  
  29.         db = SQLiteDatabase.openDatabase(path, mFactory, SQLiteDatabase.OPEN_READONLY);  
  30.         if (db.getVersion() != mNewVersion) {  
  31.             throw new SQLiteException("Can't upgrade read-only database from version " + db.getVersion() + " to "  
  32.                     + mNewVersion + ": " + path);  
  33.         }  
  34.   
  35.         onOpen(db);  
  36.         Log.w(TAG, "Opened " + mName + " in read-only mode");  
  37. 38.         mDatabase = db;// 为mDatabase指定新打开的数据库  
  38. 39.         return mDatabase;// 返回打开的数据库  
  39.     } finally {  
  40.         mIsInitializing = false;  
  41.         if (db != null && db != mDatabase)  
  42.             db.close();  
  43.     }  
  44. }  

在getReadableDatabase()方法中,首先判断是否已存在数据库实例并且是打开状态,如果是,则直接返回该实例,否则试图获取一个可读写模式的数据库实例,如果遇到磁盘空间已满等情况获取失败的话,再以只读模式打开数据库,获取数据库实例并返回,然后为mDatabase赋值为最新打开的数据库实例。既然有可能调用到getWritableDatabase()方法,我们就要看一下了:

[java] view plaincopy

1. public synchronized SQLiteDatabase getWritableDatabase() {  

  1. 2.     if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {  
  2.         // 如果mDatabase不为空已打开并且不是只读模式 则返回该实例  
  3. 4.         return mDatabase;  
  4. 5.     }  
  5. 6.   
  6. 7.     if (mIsInitializing) {  
  7. 8.         throw new IllegalStateException("getWritableDatabase called recursively");  
  8. 9.     }  
  9.   
  10.     // If we have a read-only database open, someone could be using it  
  11.     // (though they shouldn't), which would cause a lock to be held on  
  12.     // the file, and our attempts to open the database read-write would  
  13.     // fail waiting for the file lock. To prevent that, we acquire the  
  14.     // lock on the read-only database, which shuts out other users.  
  15.   
  16.     boolean success = false;  
  17.     SQLiteDatabase db = null;  
  18. 19.     // 如果mDatabase不为空则加锁 阻止其他的操作  
  19.     if (mDatabase != null)  
  20.         mDatabase.lock();  
  21.     try {  
  22.         mIsInitializing = true;  
  23.         if (mName == null) {  
  24.             db = SQLiteDatabase.create(null);  
  25.         } else {  
  26. 27.             // 打开或创建数据库  
  27.             db = mContext.openOrCreateDatabase(mName, 0, mFactory);  
  28.         }  
  29.         // 获取数据库版本(如果刚创建的数据库,版本为0)  
  30.         int version = db.getVersion();  
  31.         // 比较版本(我们代码中的版本mNewVersion为1)  
  32.         if (version != mNewVersion) {  
  33. 34.             db.beginTransaction();// 开始事务  
  34.             try {  
  35.                 if (version == 0) {  
  36. 37.                     // 执行我们的onCreate方法  
  37.                     onCreate(db);  
  38.                 } else {  
  39. 40.                     // 如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法  
  40.                     onUpgrade(db, version, mNewVersion);  
  41.                 }  
  42. 43.                 db.setVersion(mNewVersion);// 设置最新版本  
  43. 44.                 db.setTransactionSuccessful();// 设置事务成功  
  44.             } finally {  
  45. 46.                 db.endTransaction();// 结束事务  
  46.             }  
  47.         }  
  48.   
  49.         onOpen(db);  
  50.         success = true;  
  51. 52.         return db;// 返回可读写模式的数据库实例  
  52.     } finally {  
  53.         mIsInitializing = false;  
  54.         if (success) {  
  55. 56.             // 打开成功  
  56.             if (mDatabase != null) {  
  57. 58.                 // 如果mDatabase有值则先关闭  
  58.                 try {  
  59.                     mDatabase.close();  
  60.                 } catch (Exception e) {  
  61.                 }  
  62. 63.                 mDatabase.unlock();// 解锁  
  63.             }  
  64.             mDatabase = db;// 赋值给mDatabase  
  65.         } else {  
  66. 67.             // 打开失败的情况:解锁、关闭  
  67.             if (mDatabase != null)  
  68.                 mDatabase.unlock();  
  69.             if (db != null)  
  70.                 db.close();  
  71.         }  
  72.     }  
  73. }  

大家可以看到,几个关键步骤是,首先判断mDatabase如果不为空已打开并不是只读模式则直接返回,否则如果mDatabase不为空则加锁,然后开始打开或创建数据库,比较版本,根据版本号来调用相应的方法,为数据库设置新版本号,最后释放旧的不为空的mDatabase并解锁,把新打开的数据库实例赋予mDatabase,并返回最新实例。

看完上面的过程之后,大家或许就清楚了许多,如果不是在遇到磁盘空间已满等情况,getReadableDatabase()一般都会返回和getWritableDatabase()一样的数据库实例,所以我们在DBManager构造方法中使用getWritableDatabase()获取整个应用所使用的数据库实例是可行的。当然如果你真的担心这种情况会发生,那么你可以先用getWritableDatabase()获取数据实例,如果遇到异常,再试图用getReadableDatabase()获取实例,当然这个时候你获取的实例只能读不能写了。

最后,让我们看一下如何使用这些数据操作方法来显示数据,下面是MainActivity.java的布局文件和代码:

[html] view plaincopy

1. <?xml version="1.0" encoding="utf-8"?>  

2. <LinearLayout xmlns:andro  

  1. 3.     android:orientation="vertical"  
  2. 4.     android:layout_width="fill_parent"  
  3. 5.     android:layout_height="fill_parent">  
  4. 6.     <Button  
  5. 7.         android:layout_width="fill_parent"  
  6. 8.         android:layout_height="wrap_content"  
  7. 9.         android:text="add"  
  8.         android:onClick="add"/>  
  9.     <Button  
  10.         android:layout_width="fill_parent"  
  11.         android:layout_height="wrap_content"  
  12.         android:text="update"  
  13.         android:onClick="update"/>  
  14.     <Button  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="delete"  
  18.         android:onClick="delete"/>  
  19.     <Button  
  20.         android:layout_width="fill_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:text="query"  
  23.         android:onClick="query"/>  
  24.     <Button  
  25.         android:layout_width="fill_parent"  
  26.         android:layout_height="wrap_content"  
  27.         android:text="queryTheCursor"  
  28.         android:onClick="queryTheCursor"/>  
  29.     <ListView  
  30.         android:  
  31.         android:layout_width="fill_parent"  
  32.         android:layout_height="wrap_content"/>  
  33. </LinearLayout>  

 

[java] view plaincopy

1. package com.scott.db;  

  1. 2.   

3. import java.util.ArrayList;  

4. import java.util.HashMap;  

5. import java.util.List;  

6. import java.util.Map;  

  1. 7.   

8. import android.app.Activity;  

9. import android.database.Cursor;  

  1. import android.database.CursorWrapper;  
  2. import android.os.Bundle;  
  3. import android.view.View;  
  4. import android.widget.ListView;  
  5. import android.widget.SimpleAdapter;  
  6. import android.widget.SimpleCursorAdapter;  
  7.   
  8.   
  9. public class MainActivity extends Activity {  
  10.      
  11.     private DBManager mgr;  
  12.     private ListView listView;  
  13.       
  14.     @Override  
  15.     public void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.main);  
  18.         listView = (ListView) findViewById(R.id.listView);  
  19.         //初始化DBManager  
  20.         mgr = new DBManager(this);  
  21.     }  
  22.       
  23.     @Override  
  24.     protected void onDestroy() {  
  25.         super.onDestroy();  
  26.         //应用的最后一个Activity关闭时应释放DB  
  27.         mgr.closeDB();  
  28.     }  
  29.       
  30.     public void add(View view) {  
  31.         ArrayList<Person> persons = new ArrayList<Person>();  
  32.           
  33.         Person person1 = new Person("Ella", 22, "lively girl");  
  34.         Person person2 = new Person("Jenny", 22, "beautiful girl");  
  35.         Person person3 = new Person("Jessica", 23, "sexy girl");  
  36.         Person person4 = new Person("Kelly", 23, "hot baby");  
  37.         Person person5 = new Person("Jane", 25, "a pretty woman");  
  38.           
  39.         persons.add(person1);  
  40.         persons.add(person2);  
  41.         persons.add(person3);  
  42.         persons.add(person4);  
  43.         persons.add(person5);  
  44.           
  45.         mgr.add(persons);  
  46.     }  
  47.       
  48.     public void update(View view) {  
  49.         Person person = new Person();  
  50.         person.name = "Jane";  
  51.         person.age = 30;  
  52.         mgr.updateAge(person);  
  53.     }  
  54.       
  55.     public void delete(View view) {  
  56.         Person person = new Person();  
  57.         person.age = 30;  
  58.         mgr.deleteOldPerson(person);  
  59.     }  
  60.       
  61.     public void query(View view) {  
  62.         List<Person> persons = mgr.query();  
  63.         ArrayList<Map<String, String>> list = new ArrayList<Map<String, String>>();  
  64.         for (Person person : persons) {  
  65.             HashMap<String, String> map = new HashMap<String, String>();  
  66.             map.put("name", person.name);  
  67.             map.put("info", person.age + " years old, " + person.info);  
  68.             list.add(map);  
  69.         }  
  70.         SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2,  
  71.                     new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});  
  72.         listView.setAdapter(adapter);  
  73.     }  
  74.       
  75.     public void queryTheCursor(View view) {  
  76.         Cursor c = mgr.queryTheCursor();  
  77. 86.         startManagingCursor(c); //托付给activity根据自己的生命周期去管理Cursor的生命周期  
  78.         CursorWrapper cursorWrapper = new CursorWrapper(c) {  
  79.             @Override  
  80.             public String getString(int columnIndex) {  
  81. 90.                 //将简介前加上年龄  
  82.                 if (getColumnName(columnIndex).equals("info")) {  
  83.                     int age = getInt(getColumnIndex("age"));  
  84.                     return age + " years old, " + super.getString(columnIndex);  
  85.                 }  
  86.                 return super.getString(columnIndex);  
  87.             }  
  88.         };  
  89. 98.         //确保查询结果中有"_id"列  
  90.         SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2,   
  91. 100.                 cursorWrapper, new String[]{"name", "info"}, new int[]{android.R.id.text1, android.R.id.text2});  
  92. 101.         ListView listView = (ListView) findViewById(R.id.listView);  
  93. 102.         listView.setAdapter(adapter);  
  94. 103.     }  

104. }  

这里需要注意的是SimpleCursorAdapter的应用,当我们使用这个适配器时,我们必须先得到一个Cursor对象,这里面有几个问题:如何管理Cursor的生命周期,如果包装Cursor,Cursor结果集都需要注意什么。

如果手动去管理Cursor的话会非常的麻烦,还有一定的风险,处理不当的话运行期间就会出现异常,幸好Activity为我们提供了startManagingCursor(Cursor cursor)方法,它会根据Activity的生命周期去管理当前的Cursor对象,下面是该方法的说明:

[java] view plaincopy

1. /** 

  1. 2.      * This method allows the activity to take care of managing the given 
  2. 3.      * {@link Cursor}'s lifecycle for you based on the activity's lifecycle. 
  3. 4.      * That is, when the activity is stopped it will automatically call 
  4. 5.      * {@link Cursor#deactivate} on the given Cursor, and when it is later restarted 
  5. 6.      * it will call {@link Cursor#requery} for you.  When the activity is 
  6. 7.      * destroyed, all managed Cursors will be closed automatically. 
  7. 8.      *  
  8. 9.      * @param c The Cursor to be managed. 
  9.      *  
  10.      * @see #managedQuery(android.net.Uri , String[], String, String[], String) 
  11.      * @see #stopManagingCursor 
  12.      */  

文中提到,startManagingCursor方法会根据Activity的生命周期去管理当前的Cursor对象的生命周期,就是说当Activity停止时他会自动调用Cursor的deactivate方法,禁用游标,当Activity重新回到屏幕时它会调用Cursor的requery方法再次查询,当Activity摧毁时,被管理的Cursor都会自动关闭释放。

如何包装Cursor:我们会使用到CursorWrapper对象去包装我们的Cursor对象,实现我们需要的数据转换工作,这个CursorWrapper实际上是实现了Cursor接口。我们查询获取到的Cursor其实是Cursor的引用,而系统实际返回给我们的必然是Cursor接口的一个实现类的对象实例,我们用CursorWrapper包装这个实例,然后再使用SimpleCursorAdapter将结果显示到列表上。

Cursor结果集需要注意些什么:一个最需要注意的是,在我们的结果集中必须要包含一个“_id”的列,否则SimpleCursorAdapter就会翻脸不认人,为什么一定要这样呢?因为这源于SQLite的规范,主键以“_id”为标准。解决办法有三:第一,建表时根据规范去做;第二,查询时用别名,例如:SELECT id AS _id FROM person;第三,在CursorWrapper里做文章:

[java] view plaincopy

1. CursorWrapper cursorWrapper = new CursorWrapper(c) {  

  1. 2.     @Override  
  2. 3.     public int getColumnIndexOrThrow(String columnName) throws IllegalArgumentException {  
  3. 4.         if (columnName.equals("_id")) {  
  4. 5.             return super.getColumnIndex("id");  
  5. 6.         }  
  6. 7.         return super.getColumnIndexOrThrow(columnName);  
  7. 8.     }  

9. };  

如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。

 

 

 

 

相关文章:

  • 2021-04-01
  • 2022-02-28
  • 2022-12-23
  • 2022-12-23
  • 2021-05-04
  • 2021-08-23
  • 2022-12-23
猜你喜欢
  • 2021-05-17
  • 2021-11-30
  • 2022-12-23
  • 2021-12-01
  • 2021-12-18
  • 2021-12-28
  • 2021-10-31
相关资源
相似解决方案