`
king_tt
  • 浏览: 2101540 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

Android中SQLite应用详解

 
阅读更多

上次我向大家介绍了SQLite的基本信息和使用过程,相信朋友们对SQLite已经有所了解了,那今天呢,我就和大家分享一下在Android中如何使用SQLite。

现在的主流移动设备像Android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动设备上的SQLite开发技巧。对于Android平台来说,系统内置了丰富的API来供开发人员操作SQLite,我们可以轻松的完成对数据的存取。

下面就向大家介绍一下SQLite常用的操作方法,为了方便,我将代码写在了Activity的onCreate中:

  1. @Override
  2. protectedvoidonCreate(BundlesavedInstanceState){
  3. super.onCreate(savedInstanceState);
  4. //打开或创建test.db数据库
  5. SQLiteDatabasedb=openOrCreateDatabase("test.db",Context.MODE_PRIVATE,null);
  6. db.execSQL("DROPTABLEIFEXISTSperson");
  7. //创建person表
  8. db.execSQL("CREATETABLEperson(_idINTEGERPRIMARYKEYAUTOINCREMENT,nameVARCHAR,ageSMALLINT)");
  9. Personperson=newPerson();
  10. person.name="john";
  11. person.age=30;
  12. //插入数据
  13. db.execSQL("INSERTINTOpersonVALUES(NULL,?,?)",newObject[]{person.name,person.age});
  14. person.name="david";
  15. person.age=33;
  16. //ContentValues以键值对的形式存放数据
  17. ContentValuescv=newContentValues();
  18. cv.put("name",person.name);
  19. cv.put("age",person.age);
  20. //插入ContentValues中的数据
  21. db.insert("person",null,cv);
  22. cv=newContentValues();
  23. cv.put("age",35);
  24. //更新数据
  25. db.update("person",cv,"name=?",newString[]{"john"});
  26. Cursorc=db.rawQuery("SELECT*FROMpersonWHEREage>=?",newString[]{"33"});
  27. while(c.moveToNext()){
  28. int_id=c.getInt(c.getColumnIndex("_id"));
  29. Stringname=c.getString(c.getColumnIndex("name"));
  30. intage=c.getInt(c.getColumnIndex("age"));
  31. Log.i("db","_id=>"+_id+",name=>"+name+",age=>"+age);
  32. }
  33. c.close();
  34. //删除数据
  35. db.delete("person","age<?",newString[]{"35"});
  36. //关闭当前数据库
  37. db.close();
  38. //删除test.db数据库
  39. //deleteDatabase("test.db");
  40. }
在执行完上面的代码后,系统就会在/data/data/[PACKAGE_NAME]/databases目录下生成一个“test.db”的数据库文件,如图:


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

  1. db.executeSQL(Stringsql);
  2. db.executeSQL(Stringsql,Object[]bindArgs);//sql语句中使用占位符,然后第二个参数是实际的参数集
除了统一的形式之外,他们还有各自的操作方法:

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

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

  1. db.rawQuery(Stringsql,String[]selectionArgs);
  2. db.query(Stringtable,String[]columns,Stringselection,String[]selectionArgs,StringgroupBy,Stringhaving,StringorderBy);
  3. db.query(Stringtable,String[]columns,Stringselection,String[]selectionArgs,StringgroupBy,Stringhaving,StringorderBy,Stringlimit);
  4. db.query(Stringdistinct,Stringtable,String[]columns,Stringselection,String[]selectionArgs,StringgroupBy,Stringhaving,StringorderBy,Stringlimit);
上面几种都是常用的查询方法,第一种最为简单,将所有的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对象的常用方法:

  1. c.move(intoffset);//以当前位置为参考,移动到指定行
  2. c.moveToFirst();//移动到第一行
  3. c.moveToLast();//移动到最后一行
  4. c.moveToPosition(intposition);//移动到指定行
  5. c.moveToPrevious();//移动到前一行
  6. c.moveToNext();//移动到下一行
  7. c.isFirst();//是否指向第一条
  8. c.isLast();//是否指向最后一条
  9. c.isBeforeFirst();//是否指向第一条之前
  10. c.isAfterLast();//是否指向最后一条之后
  11. c.isNull(intcolumnIndex);//指定列是否为空(列基数为0)
  12. c.isClosed();//游标是否已关闭
  13. c.getCount();//总数据项数
  14. c.getPosition();//返回当前游标所指向的行数
  15. c.getColumnIndex(StringcolumnName);//返回某列名对应的列索引值
  16. c.getString(intcolumnIndex);//返回当前行指定列的值

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

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

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

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


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

下面我们先来看一下DBHelper:

  1. packagecom.scott.db;
  2. importandroid.content.Context;
  3. importandroid.database.sqlite.SQLiteDatabase;
  4. importandroid.database.sqlite.SQLiteOpenHelper;
  5. publicclassDBHelperextendsSQLiteOpenHelper{
  6. privatestaticfinalStringDATABASE_NAME="test.db";
  7. privatestaticfinalintDATABASE_VERSION=1;
  8. publicDBHelper(Contextcontext){
  9. //CursorFactory设置为null,使用默认值
  10. super(context,DATABASE_NAME,null,DATABASE_VERSION);
  11. }
  12. //数据库第一次被创建时onCreate会被调用
  13. @Override
  14. publicvoidonCreate(SQLiteDatabasedb){
  15. db.execSQL("CREATETABLEIFNOTEXISTSperson"+
  16. "(_idINTEGERPRIMARYKEYAUTOINCREMENT,nameVARCHAR,ageINTEGER,infoTEXT)");
  17. }
  18. //如果DATABASE_VERSION值被改为2,系统发现现有数据库版本不同,即会调用onUpgrade
  19. @Override
  20. publicvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  21. db.execSQL("ALTERTABLEpersonADDCOLUMNotherSTRING");
  22. }
  23. }
正如上面所述,数据库第一次创建时onCreate方法会被调用,我们可以执行创建表的语句,当系统发现版本变化之后,会调用onUpgrade方法,我们可以执行修改表结构等语句。

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

  1. packagecom.scott.db;
  2. publicclassPerson{
  3. publicint_id;
  4. publicStringname;
  5. publicintage;
  6. publicStringinfo;
  7. publicPerson(){
  8. }
  9. publicPerson(Stringname,intage,Stringinfo){
  10. this.name=name;
  11. this.age=age;
  12. this.info=info;
  13. }
  14. }
然后,我们需要一个DBManager,来封装我们所有的业务方法,代码如下:

  1. packagecom.scott.db;
  2. importjava.util.ArrayList;
  3. importjava.util.List;
  4. importandroid.content.ContentValues;
  5. importandroid.content.Context;
  6. importandroid.database.Cursor;
  7. importandroid.database.sqlite.SQLiteDatabase;
  8. publicclassDBManager{
  9. privateDBHelperhelper;
  10. privateSQLiteDatabasedb;
  11. publicDBManager(Contextcontext){
  12. helper=newDBHelper(context);
  13. //因为getWritableDatabase内部调用了mContext.openOrCreateDatabase(mName,0,mFactory);
  14. //所以要确保context已初始化,我们可以把实例化DBManager的步骤放在Activity的onCreate里
  15. db=helper.getWritableDatabase();
  16. }
  17. /**
  18. *addpersons
  19. *@parampersons
  20. */
  21. publicvoidadd(List<Person>persons){
  22. db.beginTransaction();//开始事务
  23. try{
  24. for(Personperson:persons){
  25. db.execSQL("INSERTINTOpersonVALUES(null,?,?,?)",newObject[]{person.name,person.age,person.info});
  26. }
  27. db.setTransactionSuccessful();//设置事务成功完成
  28. }finally{
  29. db.endTransaction();//结束事务
  30. }
  31. }
  32. /**
  33. *updateperson'sage
  34. *@paramperson
  35. */
  36. publicvoidupdateAge(Personperson){
  37. ContentValuescv=newContentValues();
  38. cv.put("age",person.age);
  39. db.update("person",cv,"name=?",newString[]{person.name});
  40. }
  41. /**
  42. *deleteoldperson
  43. *@paramperson
  44. */
  45. publicvoiddeleteOldPerson(Personperson){
  46. db.delete("person","age>=?",newString[]{String.valueOf(person.age)});
  47. }
  48. /**
  49. *queryallpersons,returnlist
  50. *@returnList<Person>
  51. */
  52. publicList<Person>query(){
  53. ArrayList<Person>persons=newArrayList<Person>();
  54. Cursorc=queryTheCursor();
  55. while(c.moveToNext()){
  56. Personperson=newPerson();
  57. person._id=c.getInt(c.getColumnIndex("_id"));
  58. person.name=c.getString(c.getColumnIndex("name"));
  59. person.age=c.getInt(c.getColumnIndex("age"));
  60. person.info=c.getString(c.getColumnIndex("info"));
  61. persons.add(person);
  62. }
  63. c.close();
  64. returnpersons;
  65. }
  66. /**
  67. *queryallpersons,returncursor
  68. *@returnCursor
  69. */
  70. publicCursorqueryTheCursor(){
  71. Cursorc=db.rawQuery("SELECT*FROMperson",null);
  72. returnc;
  73. }
  74. /**
  75. *closedatabase
  76. */
  77. publicvoidcloseDB(){
  78. db.close();
  79. }
  80. }
我们在DBManager构造方法中实例化DBHelper并获取一个SQLiteDatabase对象,作为整个应用的数据库实例;在添加多个Person信息时,我们采用了事务处理,确保数据完整性;最后我们提供了一个closeDB方法,释放数据库资源,这一个步骤在我们整个应用关闭时执行,这个环节容易被忘记,所以朋友们要注意。

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

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

  1. publicsynchronizedSQLiteDatabasegetReadableDatabase(){
  2. if(mDatabase!=null&&mDatabase.isOpen()){
  3. //如果发现mDatabase不为空并且已经打开则直接返回
  4. returnmDatabase;
  5. }
  6. if(mIsInitializing){
  7. //如果正在初始化则抛出异常
  8. thrownewIllegalStateException("getReadableDatabasecalledrecursively");
  9. }
  10. //开始实例化数据库mDatabase
  11. try{
  12. //注意这里是调用了getWritableDatabase()方法
  13. returngetWritableDatabase();
  14. }catch(SQLiteExceptione){
  15. if(mName==null)
  16. throwe;//Can'topenatempdatabaseread-only!
  17. Log.e(TAG,"Couldn'topen"+mName+"forwriting(willtryread-only):",e);
  18. }
  19. //如果无法以可读写模式打开数据库则以只读方式打开
  20. SQLiteDatabasedb=null;
  21. try{
  22. mIsInitializing=true;
  23. Stringpath=mContext.getDatabasePath(mName).getPath();//获取数据库路径
  24. //以只读方式打开数据库
  25. db=SQLiteDatabase.openDatabase(path,mFactory,SQLiteDatabase.OPEN_READONLY);
  26. if(db.getVersion()!=mNewVersion){
  27. thrownewSQLiteException("Can'tupgraderead-onlydatabasefromversion"+db.getVersion()+"to"
  28. +mNewVersion+":"+path);
  29. }
  30. onOpen(db);
  31. Log.w(TAG,"Opened"+mName+"inread-onlymode");
  32. mDatabase=db;//为mDatabase指定新打开的数据库
  33. returnmDatabase;//返回打开的数据库
  34. }finally{
  35. mIsInitializing=false;
  36. if(db!=null&&db!=mDatabase)
  37. db.close();
  38. }
  39. }
在getReadableDatabase()方法中,首先判断是否已存在数据库实例并且是打开状态,如果是,则直接返回该实例,否则试图获取一个可读写模式的数据库实例,如果遇到磁盘空间已满等情况获取失败的话,再以只读模式打开数据库,获取数据库实例并返回,然后为mDatabase赋值为最新打开的数据库实例。既然有可能调用到getWritableDatabase()方法,我们就要看一下了:

  1. publicsynchronizedSQLiteDatabasegetWritableDatabase(){
  2. if(mDatabase!=null&&mDatabase.isOpen()&&!mDatabase.isReadOnly()){
  3. //如果mDatabase不为空已打开并且不是只读模式则返回该实例
  4. returnmDatabase;
  5. }
  6. if(mIsInitializing){
  7. thrownewIllegalStateException("getWritableDatabasecalledrecursively");
  8. }
  9. //Ifwehavearead-onlydatabaseopen,someonecouldbeusingit
  10. //(thoughtheyshouldn't),whichwouldcausealocktobeheldon
  11. //thefile,andourattemptstoopenthedatabaseread-writewould
  12. //failwaitingforthefilelock.Topreventthat,weacquirethe
  13. //lockontheread-onlydatabase,whichshutsoutotherusers.
  14. booleansuccess=false;
  15. SQLiteDatabasedb=null;
  16. //如果mDatabase不为空则加锁阻止其他的操作
  17. if(mDatabase!=null)
  18. mDatabase.lock();
  19. try{
  20. mIsInitializing=true;
  21. if(mName==null){
  22. db=SQLiteDatabase.create(null);
  23. }else{
  24. //打开或创建数据库
  25. db=mContext.openOrCreateDatabase(mName,0,mFactory);
  26. }
  27. //获取数据库版本(如果刚创建的数据库,版本为0)
  28. intversion=db.getVersion();
  29. //比较版本(我们代码中的版本mNewVersion为1)
  30. if(version!=mNewVersion){
  31. db.beginTransaction();//开始事务
  32. try{
  33. if(version==0){
  34. //执行我们的onCreate方法
  35. onCreate(db);
  36. }else{
  37. //如果我们应用升级了mNewVersion为2,而原版本为1则执行onUpgrade方法
  38. onUpgrade(db,version,mNewVersion);
  39. }
  40. db.setVersion(mNewVersion);//设置最新版本
  41. db.setTransactionSuccessful();//设置事务成功
  42. }finally{
  43. db.endTransaction();//结束事务
  44. }
  45. }
  46. onOpen(db);
  47. success=true;
  48. returndb;//返回可读写模式的数据库实例
  49. }finally{
  50. mIsInitializing=false;
  51. if(success){
  52. //打开成功
  53. if(mDatabase!=null){
  54. //如果mDatabase有值则先关闭
  55. try{
  56. mDatabase.close();
  57. }catch(Exceptione){
  58. }
  59. mDatabase.unlock();//解锁
  60. }
  61. mDatabase=db;//赋值给mDatabase
  62. }else{
  63. //打开失败的情况:解锁、关闭
  64. if(mDatabase!=null)
  65. mDatabase.unlock();
  66. if(db!=null)
  67. db.close();
  68. }
  69. }
  70. }
大家可以看到,几个关键步骤是,首先判断mDatabase如果不为空已打开并不是只读模式则直接返回,否则如果mDatabase不为空则加锁,然后开始打开或创建数据库,比较版本,根据版本号来调用相应的方法,为数据库设置新版本号,最后释放旧的不为空的mDatabase并解锁,把新打开的数据库实例赋予mDatabase,并返回最新实例。

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

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

  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">
  6. <Button
  7. android:layout_width="fill_parent"
  8. android:layout_height="wrap_content"
  9. android:text="add"
  10. android:onClick="add"/>
  11. <Button
  12. android:layout_width="fill_parent"
  13. android:layout_height="wrap_content"
  14. android:text="update"
  15. android:onClick="update"/>
  16. <Button
  17. android:layout_width="fill_parent"
  18. android:layout_height="wrap_content"
  19. android:text="delete"
  20. android:onClick="delete"/>
  21. <Button
  22. android:layout_width="fill_parent"
  23. android:layout_height="wrap_content"
  24. android:text="query"
  25. android:onClick="query"/>
  26. <Button
  27. android:layout_width="fill_parent"
  28. android:layout_height="wrap_content"
  29. android:text="queryTheCursor"
  30. android:onClick="queryTheCursor"/>
  31. <ListView
  32. android:id="@+id/listView"
  33. android:layout_width="fill_parent"
  34. android:layout_height="wrap_content"/>
  35. </LinearLayout>

  1. packagecom.scott.db;
  2. importjava.util.ArrayList;
  3. importjava.util.HashMap;
  4. importjava.util.List;
  5. importjava.util.Map;
  6. importandroid.app.Activity;
  7. importandroid.database.Cursor;
  8. importandroid.database.CursorWrapper;
  9. importandroid.os.Bundle;
  10. importandroid.view.View;
  11. importandroid.widget.ListView;
  12. importandroid.widget.SimpleAdapter;
  13. importandroid.widget.SimpleCursorAdapter;
  14. publicclassMainActivityextendsActivity{
  15. privateDBManagermgr;
  16. privateListViewlistView;
  17. @Override
  18. publicvoidonCreate(BundlesavedInstanceState){
  19. super.onCreate(savedInstanceState);
  20. setContentView(R.layout.main);
  21. listView=(ListView)findViewById(R.id.listView);
  22. //初始化DBManager
  23. mgr=newDBManager(this);
  24. }
  25. @Override
  26. protectedvoidonDestroy(){
  27. super.onDestroy();
  28. //应用的最后一个Activity关闭时应释放DB
  29. mgr.closeDB();
  30. }
  31. publicvoidadd(Viewview){
  32. ArrayList<Person>persons=newArrayList<Person>();
  33. Personperson1=newPerson("Ella",22,"livelygirl");
  34. Personperson2=newPerson("Jenny",22,"beautifulgirl");
  35. Personperson3=newPerson("Jessica",23,"sexygirl");
  36. Personperson4=newPerson("Kelly",23,"hotbaby");
  37. Personperson5=newPerson("Jane",25,"aprettywoman");
  38. persons.add(person1);
  39. persons.add(person2);
  40. persons.add(person3);
  41. persons.add(person4);
  42. persons.add(person5);
  43. mgr.add(persons);
  44. }
  45. publicvoidupdate(Viewview){
  46. Personperson=newPerson();
  47. person.name="Jane";
  48. person.age=30;
  49. mgr.updateAge(person);
  50. }
  51. publicvoiddelete(Viewview){
  52. Personperson=newPerson();
  53. person.age=30;
  54. mgr.deleteOldPerson(person);
  55. }
  56. publicvoidquery(Viewview){
  57. List<Person>persons=mgr.query();
  58. ArrayList<Map<String,String>>list=newArrayList<Map<String,String>>();
  59. for(Personperson:persons){
  60. HashMap<String,String>map=newHashMap<String,String>();
  61. map.put("name",person.name);
  62. map.put("info",person.age+"yearsold,"+person.info);
  63. list.add(map);
  64. }
  65. SimpleAdapteradapter=newSimpleAdapter(this,list,android.R.layout.simple_list_item_2,
  66. newString[]{"name","info"},newint[]{android.R.id.text1,android.R.id.text2});
  67. listView.setAdapter(adapter);
  68. }
  69. publicvoidqueryTheCursor(Viewview){
  70. Cursorc=mgr.queryTheCursor();
  71. startManagingCursor(c);//托付给activity根据自己的生命周期去管理Cursor的生命周期
  72. CursorWrappercursorWrapper=newCursorWrapper(c){
  73. @Override
  74. publicStringgetString(intcolumnIndex){
  75. //将简介前加上年龄
  76. if(getColumnName(columnIndex).equals("info")){
  77. intage=getInt(getColumnIndex("age"));
  78. returnage+"yearsold,"+super.getString(columnIndex);
  79. }
  80. returnsuper.getString(columnIndex);
  81. }
  82. };
  83. //确保查询结果中有"_id"列
  84. SimpleCursorAdapteradapter=newSimpleCursorAdapter(this,android.R.layout.simple_list_item_2,
  85. cursorWrapper,newString[]{"name","info"},newint[]{android.R.id.text1,android.R.id.text2});
  86. ListViewlistView=(ListView)findViewById(R.id.listView);
  87. listView.setAdapter(adapter);
  88. }
  89. }
这里需要注意的是SimpleCursorAdapter的应用,当我们使用这个适配器时,我们必须先得到一个Cursor对象,这里面有几个问题:如何管理Cursor的生命周期,如果包装Cursor,Cursor结果集都需要注意什么。

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

  1. /**
  2. *Thismethodallowstheactivitytotakecareofmanagingthegiven
  3. *{@linkCursor}'slifecycleforyoubasedontheactivity'slifecycle.
  4. *Thatis,whentheactivityisstoppeditwillautomaticallycall
  5. *{@linkCursor#deactivate}onthegivenCursor,andwhenitislaterrestarted
  6. *itwillcall{@linkCursor#requery}foryou.Whentheactivityis
  7. *destroyed,allmanagedCursorswillbeclosedautomatically.
  8. *
  9. *@paramcTheCursortobemanaged.
  10. *
  11. *@see#managedQuery(android.net.Uri,String[],String,String[],String)
  12. *@see#stopManagingCursor
  13. */
文中提到,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里做文章:

  1. CursorWrappercursorWrapper=newCursorWrapper(c){
  2. @Override
  3. publicintgetColumnIndexOrThrow(StringcolumnName)throwsIllegalArgumentException{
  4. if(columnName.equals("_id")){
  5. returnsuper.getColumnIndex("id");
  6. }
  7. returnsuper.getColumnIndexOrThrow(columnName);
  8. }
  9. };
如果试图从CursorWrapper里获取“_id”对应的列索引,我们就返回查询结果里“id”对应的列索引即可。

最后我们来看一下结果如何:


分享到:
评论

相关推荐

    android之SQLite数据库开发详解

    android之SQLite数据库开发详解: Android 开发中使用 SQLite 数据库 简介: SQLite 是一款非常流行的嵌入式数据库,它支持 SQL 查询,并且只用很少的内存。Android 在运行时集成了 SQLite,所以每个 Android 应用...

    Android中SQLite 使用方法详解

    Android中SQLite 使用方法详解 现在的主流移动设备像android、iPhone等都使用SQLite作为复杂数据的存储引擎,在我们为移动设备开发应用程序时,也许就要使用到SQLite来存储我们大量的数据,所以我们就需要掌握移动...

    Android应用开发详解

    《Android应用开发详解》 作者:郭宏志 编著 内容简介 本书分为三个部分,包括基础篇、技术篇和应用篇。由浅入深地讲述了Android应用开发的方方面面。 第一篇 基础篇 第1章 Android概述 Android概述,讲述了...

    Android SQLite详解及示例代码

    在Android中使用SQLite数据库的入门指南,打算分下面几部分与大家一起分享, 1、什么是SQLite 2、Android中使用SQLite 一、什么是SQLite SQLite是一款开源的、轻量级的、嵌入式的、关系型数据库。它在2000年由...

    深入Android SQLite 事务处理详解

    应用程序初始化时需要批量的向sqlite中插入大量数据,单独的使用for+Insert方法导致应用响应缓慢,因为 sqlite插入数据的时候默认一条语句就是一个事务,有多少条数据就有多少次磁盘操作。我的应用初始5000条记录也...

    基于Android SQLite的升级详解

    做Android应用,不可避免的会与SQLite打交道。随着应用的不断升级,原有的数据库结构可能已经不再适应新的功能,这时候,就需要对SQLite数据库的结构进行升级了。 SQLite提供了ALTER TABLE命令,允许用户重命名或...

    SQLite学习资料大全

    此资源(7zip压缩)包括: 1.SQLite权威指南 ...8.嵌入式数据库在SQLite中的应用 9.SQLite数据库文件格式全面分析 10.Android的SQLite使用教程 等等.. 下载一个不用去下载其他的了,资料很全面,谢谢下载!

    Android 实例分析ContentProvider详解

    ContentProvider是android的四大组件之一,同时与...android支持的Sqlite是不支持跨进程、跨应用访问的,因此,ContentProvider应运而生,为我们提供了可以跨进程、跨应用,并且可以屏蔽一些重要数据的访问机制

    《Android应用开发揭秘》附带光盘代码.

    《Android应用开发揭秘》全部实例源代码,配合《Android应用开发揭秘》使用 前言  第一部分 准备篇  第1章 Android开发简介  1.1 Android基本概念  1.1.1 Android简介  1.1.2 Android的系统构架  1.1.3 ...

    Android入门到精通源代码.

    1.3 Android应用程序构成 1.3.1 活动(Activity) 1.3.2 意图(Intent) 1.3.3 服务(Service) 1.3.4 内容提供器(ContentProvider) 1.4 Android网上资源 第2章 搭建Android开发环境 2.1 Android开发环境要求 2.2 ...

    《Android应用开发揭秘》源码

     杨丰盛,Android应用开发先驱,对Android有深入研究,实战经验极其丰富。精通Java、C、C++等语言,专注于移动通信软件开发,在机顶盒软件开发和MTK平台软件开发方面有非常深厚的积累。2007年获得中国软件行业协会...

    浅谈Android游戏开发之详解SQLite存储

    底层Linux内核只提供基本功能,其他的应用软件则由各公司自行开发,部分程序以Java编写。  什么是SQLite:  SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前...

    Android应用开发揭秘pdf高清版

    最重要的是还全面介绍了如何利用原生的C,C++(NDK)和Python、Lua等脚本语言(AndroidScriptingEnvironment)来开发Android应用,《Android应用开发揭秘》实战性强,书中的每个知识点都有配精心设计的示例,尤为...

    SQLite教程合集

    包括以下文档 : sqlite3使用详解.pdf SQLite教程.pdf 嵌入式数据库在sqlite3中的应用.pdf SQLite数据库文件格式全面分析.pdf android-database.pdf SQLite入门与分析.pdf

Global site tag (gtag.js) - Google Analytics