Inessence, cursors iterate over result sets and provide access to data one row at a time.


first,We’ll want simple model objects,second,we need create table class with static methods and OpenSqliteHelper to create our database.third,a simpleinterface andDAOs for ourmodel objects.last,create a data manager layer to wrap aroundthose DAOs.

Designing a data access layer:


design table relations:


In general, if youneed to share your data with other applications you must create a ContentProvider.if you don’t need to share data, it’s usually simpler to use a
database directly.if we want touse a ContentProvider to expose our tables later, must have an _id column,which is the primary key.e

now the src code is:


create Model objects

ModelBase class:

[html] view plain copy
  1. /TheModelBaseclass,whichbothMovieandCategoryextend,containsonlyalongid.
  2. publicclassModelBase{
  3. protectedlongid;
  4. publiclonggetId(){
  5. returnthis.id;
  6. }
  7. publicvoidsetId(longid){
  8. this.id=id;
  9. }
  10. @Override
  11. publicStringtoString(){
  12. return"ModelBase[id="+this.id+"]";
  13. }
  14. @Override
  15. publicinthashCode(){
  16. finalintprime=31;
  17. intresult=1;
  18. result=prime*result+(int)(this.id^(this.id>>>32));
  19. returnresult;
  20. }
  21. @Override
  22. publicbooleanequals(Objectobj){
  23. if(this==obj){
  24. returntrue;
  25. }
  26. if(obj==null){
  27. returnfalse;
  28. }
  29. if(!(objinstanceofModelBase)){
  30. returnfalse;
  31. }
  32. ModelBaseother=(ModelBase)obj;
  33. if(this.id!=other.id){
  34. returnfalse;
  35. }
  36. returntrue;
  37. }
  38. }

Movie model: [html] view plain copy
  1. publicclassMovieextendsModelBase{
  2. privateStringproviderId;
  3. privateStringname;
  4. privateintyear;
  5. privatedoublerating;
  6. privateStringurl;
  7. privateStringhomepage;
  8. privateStringtrailer;
  9. privateStringtagline;
  10. privateStringthumbUrl;
  11. privateStringimageUrl;
  12. privateSet<Category>categories;
  13. //note,inthereal-worldmakingthesemodelbeansimmutablewouldbeabetterapproach
  14. //(thatistosay,notmakingthemJavaBeans,butmakignimmutablemodelclasseswithBuilder)
  15. publicMovie(){
  16. this.categories=newLinkedHashSet<Category>();
  17. }
  18. publicStringgetProviderId(){
  19. returnthis.providerId;
  20. }
  21. publicvoidsetProviderId(StringproviderId){
  22. this.providerId=providerId;
  23. }
  24. publicStringgetName(){
  25. returnthis.name;
  26. }
  27. publicvoidsetName(Stringname){
  28. this.name=name;
  29. }
  30. publicintgetYear(){
  31. returnthis.year;
  32. }
  33. publicvoidsetYear(intyear){
  34. this.year=year;
  35. }
  36. publicdoublegetRating(){
  37. returnthis.rating;
  38. }
  39. publicvoidsetRating(doublerating){
  40. this.rating=rating;
  41. }
  42. publicStringgetUrl(){
  43. returnthis.url;
  44. }
  45. publicvoidsetUrl(Stringurl){
  46. this.url=url;
  47. }
  48. publicStringgetHomepage(){
  49. returnthis.homepage;
  50. }
  51. publicvoidsetHomepage(Stringhomepage){
  52. this.homepage=homepage;
  53. }
  54. publicStringgetTrailer(){
  55. returnthis.trailer;
  56. }
  57. publicvoidsetTrailer(Stringtrailer){
  58. this.trailer=trailer;
  59. }
  60. publicStringgetTagline(){
  61. returnthis.tagline;
  62. }
  63. publicvoidsetTagline(Stringtagline){
  64. this.tagline=tagline;
  65. }
  66. publicStringgetThumbUrl(){
  67. returnthis.thumbUrl;
  68. }
  69. publicvoidsetThumbUrl(StringthumbUrl){
  70. this.thumbUrl=thumbUrl;
  71. }
  72. publicStringgetImageUrl(){
  73. returnthis.imageUrl;
  74. }
  75. publicvoidsetImageUrl(StringimageUrl){
  76. this.imageUrl=imageUrl;
  77. }
  78. publicSet<Category>getCategories(){
  79. returnthis.categories;
  80. }
  81. publicvoidsetCategories(Set<Category>categories){
  82. this.categories=categories;
  83. }
  84. @Override
  85. publicStringtoString(){
  86. return"Movie[categories="+this.categories+",homepage="+this.homepage+",name="+this.name
  87. +",providerId="+this.providerId+",rating="+this.rating+",tagline="+this.tagline
  88. +",thumbUrl="+this.thumbUrl+",imageUrl="+this.imageUrl+",trailer="+this.trailer+",url="
  89. +this.url+",year="+this.year+"]";
  90. }
  91. @Override
  92. publicinthashCode(){
  93. finalintprime=31;
  94. intresult=super.hashCode();
  95. result=prime*result+((this.categories==null)?0:this.categories.hashCode());
  96. result=prime*result+((this.homepage==null)?0:this.homepage.hashCode());
  97. //uppernamesohashCodeisconsistentwithequals(equalsignorescase)
  98. result=prime*result+((this.name==null)?0:this.name.toUpperCase().hashCode());
  99. result=prime*result+((this.providerId==null)?0:this.providerId.hashCode());
  100. longtemp;
  101. temp=Double.doubleToLongBits(this.rating);
  102. result=prime*result+(int)(temp^(temp>>>32));
  103. result=prime*result+((this.tagline==null)?0:this.tagline.hashCode());
  104. result=prime*result+((this.thumbUrl==null)?0:this.thumbUrl.hashCode());
  105. result=prime*result+((this.imageUrl==null)?0:this.imageUrl.hashCode());
  106. result=prime*result+((this.trailer==null)?0:this.trailer.hashCode());
  107. result=prime*result+((this.url==null)?0:this.url.hashCode());
  108. result=prime*result+this.year;
  109. returnresult;
  110. }
  111. @Override
  112. publicbooleanequals(Objectobj){
  113. if(this==obj){
  114. returntrue;
  115. }
  116. if(!super.equals(obj)){
  117. returnfalse;
  118. }
  119. if(!(objinstanceofMovie)){
  120. returnfalse;
  121. }
  122. Movieother=(Movie)obj;
  123. if(this.categories==null){
  124. if(other.categories!=null){
  125. returnfalse;
  126. }
  127. }elseif(!this.categories.equals(other.categories)){
  128. returnfalse;
  129. }
  130. if(this.homepage==null){
  131. if(other.homepage!=null){
  132. returnfalse;
  133. }
  134. }elseif(!this.homepage.equals(other.homepage)){
  135. returnfalse;
  136. }
  137. if(this.name==null){
  138. if(other.name!=null){
  139. returnfalse;
  140. //namecheckignorescase
  141. }
  142. }elseif(!this.name.equalsIgnoreCase(other.name)){
  143. returnfalse;
  144. }
  145. if(this.providerId==null){
  146. if(other.providerId!=null){
  147. returnfalse;
  148. }
  149. }elseif(!this.providerId.equals(other.providerId)){
  150. returnfalse;
  151. }
  152. if(Double.doubleToLongBits(this.rating)!=Double.doubleToLongBits(other.rating)){
  153. returnfalse;
  154. }
  155. if(this.tagline==null){
  156. if(other.tagline!=null){
  157. returnfalse;
  158. }
  159. }elseif(!this.tagline.equals(other.tagline)){
  160. returnfalse;
  161. }
  162. if(this.thumbUrl==null){
  163. if(other.thumbUrl!=null){
  164. returnfalse;
  165. }
  166. }elseif(!this.thumbUrl.equals(other.thumbUrl)){
  167. returnfalse;
  168. }
  169. if(this.imageUrl==null){
  170. if(other.imageUrl!=null){
  171. returnfalse;
  172. }
  173. }elseif(!this.imageUrl.equals(other.imageUrl)){
  174. returnfalse;
  175. }
  176. if(this.trailer==null){
  177. if(other.trailer!=null){
  178. returnfalse;
  179. }
  180. }elseif(!this.trailer.equals(other.trailer)){
  181. returnfalse;
  182. }
  183. if(this.url==null){
  184. if(other.url!=null){
  185. returnfalse;
  186. }
  187. }elseif(!this.url.equals(other.url)){
  188. returnfalse;
  189. }
  190. if(this.year!=other.year){
  191. returnfalse;
  192. }
  193. returntrue;
  194. }
  195. }
Category model: [html] view plain copy
  1. publicclassCategoryextendsModelBaseimplementsComparable<Category>{
  2. //NOTEinreal-worldandroidappyoumightwantaCategoryFactory
  3. //orfactorymethodhere,tocutdownonnumberofobjectscreated
  4. privateStringname;
  5. publicCategory(){
  6. }
  7. publicCategory(longid,Stringname){
  8. this.id=id;
  9. this.name=name;
  10. }
  11. publicStringgetName(){
  12. returnthis.name;
  13. }
  14. publicvoidsetName(Stringname){
  15. this.name=name;
  16. }
  17. @Override
  18. publicStringtoString(){
  19. returnthis.name;
  20. }
  21. @Override
  22. publicintcompareTo(Categoryanother){
  23. if(another==null){
  24. return-1;
  25. }
  26. if(this.name==null){
  27. return1;
  28. }
  29. returnthis.name.compareTo(another.name);
  30. }
  31. @Override
  32. publicinthashCode(){
  33. finalintprime=31;
  34. intresult=super.hashCode();
  35. //uppernamesohashCodeisconsistentwithequals(equalsignorescase)
  36. result=prime*result+((this.name==null)?0:this.name.toUpperCase().hashCode());
  37. returnresult;
  38. }
  39. @Override
  40. publicbooleanequals(Objectobj){
  41. if(this==obj){
  42. returntrue;
  43. }
  44. if(!super.equals(obj)){
  45. returnfalse;
  46. }
  47. if(!(objinstanceofCategory)){
  48. returnfalse;
  49. }
  50. Categoryother=(Category)obj;
  51. if(this.name==null){
  52. if(other.name!=null){
  53. returnfalse;
  54. //namecheckignorescase
  55. }
  56. }elseif(!this.name.equalsIgnoreCase(other.name)){
  57. returnfalse;
  58. }
  59. returntrue;
  60. }
  61. }


predefine Constant class:Constants、DataConstants: [html] view plain copy
  1. publicclassConstants{
  2. publicstaticfinalStringLOG_TAG="MyMovies";
  3. privateConstants(){
  4. }
  5. }
[html] view plain copy
  1. publicclassDataConstants{
  2. privatestaticfinalStringAPP_PACKAGE_NAME="example.mymoviesdatabases";
  3. privatestaticfinalStringEXTERNAL_DATA_DIR_NAME="mymoviesdata";
  4. publicstaticfinalStringEXTERNAL_DATA_PATH=
  5. Environment.getExternalStorageDirectory()+"/"+DataConstants.EXTERNAL_DATA_DIR_NAME;
  6. publicstaticfinalStringDATABASE_NAME="mymovies.db";
  7. publicstaticfinalStringDATABASE_PATH=
  8. Environment.getDataDirectory()+"/data/"+DataConstants.APP_PACKAGE_NAME+"/databases/"
  9. +DataConstants.DATABASE_NAME;
  10. privateDataConstants(){
  11. }
  12. }

MovieTable table class:

The MovieTable class with static methods and inner class MovieColumns.

[html] view plain copy
  1. publicfinalclassMovieTable{
  2. publicstaticfinalStringTABLE_NAME="movie";
  3. //BaseColumnsisprovidedbyAndroid,anditdefinesthe_idcolumn
  4. publicstaticclassMovieColumnsimplementsBaseColumns{
  5. publicstaticfinalStringHOMEPAGE="homepage";
  6. publicstaticfinalStringNAME="movie_name";
  7. publicstaticfinalStringRATING="rating";
  8. publicstaticfinalStringTAGLINE="tagline";
  9. publicstaticfinalStringTHUMB_URL="thumb_url";
  10. publicstaticfinalStringIMAGE_URL="image_url";
  11. publicstaticfinalStringTRAILER="trailer";
  12. publicstaticfinalStringURL="url";
  13. publicstaticfinalStringYEAR="year";
  14. }
  15. publicstaticvoidonCreate(SQLiteDatabasedb){
  16. StringBuildersb=newStringBuilder();
  17. //movietable
  18. sb.append("CREATETABLE"+MovieTable.TABLE_NAME+"(");
  19. sb.append(BaseColumns._ID+"INTEGERPRIMARYKEY,");
  20. sb.append(MovieColumns.HOMEPAGE+"TEXT,");
  21. sb.append(MovieColumns.NAME+"TEXTUNIQUENOTNULL,");
  22. //movienamesaren'tunique,butforsimplificationweconstrain
  23. sb.append(MovieColumns.RATING+"INTEGER,");
  24. sb.append(MovieColumns.TAGLINE+"TEXT,");
  25. sb.append(MovieColumns.THUMB_URL+"TEXT,");
  26. sb.append(MovieColumns.IMAGE_URL+"TEXT,");
  27. sb.append(MovieColumns.TRAILER+"TEXT,");
  28. sb.append(MovieColumns.URL+"TEXT,");
  29. sb.append(MovieColumns.YEAR+"INTEGER");
  30. sb.append(");");
  31. db.execSQL(sb.toString());
  32. }
  33. publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  34. db.execSQL("DROPTABLEIFEXISTS"+MovieTable.TABLE_NAME);
  35. MovieTable.onCreate(db);
  36. }
  37. }
CategoryTable table class,

with static methods and inner class CategoryColumns:

[html] view plain copy
  1. publicclassCategoryTable{
  2. publicstaticfinalStringTABLE_NAME="category";
  3. publicstaticclassCategoryColumnsimplementsBaseColumns{
  4. publicstaticfinalStringNAME="name";
  5. }
  6. publicstaticvoidonCreate(SQLiteDatabasedb){
  7. StringBuildersb=newStringBuilder();
  8. //categorytable
  9. sb.append("CREATETABLE"+CategoryTable.TABLE_NAME+"(");
  10. sb.append(BaseColumns._ID+"INTEGERPRIMARYKEY,");
  11. sb.append(CategoryColumns.NAME+"TEXTUNIQUENOTNULL");
  12. sb.append(");");
  13. db.execSQL(sb.toString());
  14. }
  15. publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  16. db.execSQL("DROPTABLEIFEXISTS"+CategoryTable.TABLE_NAME);
  17. CategoryTable.onCreate(db);
  18. }
  19. }

MovieCategoryTable table class

The MovieCategoryTable class showing the declaration of foreign key references
[html] view plain copy
  1. publicclassMovieCategoryTable{
  2. publicstaticfinalStringTABLE_NAME="movie_category";
  3. publicstaticclassMovieCategoryColumns{
  4. publicstaticfinalStringMOVIE_ID="movie_id";
  5. publicstaticfinalStringCATEGORY_ID="category_id";
  6. }
  7. publicstaticvoidonCreate(SQLiteDatabasedb){
  8. StringBuildersb=newStringBuilder();
  9. //movie_categorymappingtable
  10. sb.append("CREATETABLE"+MovieCategoryTable.TABLE_NAME+"(");
  11. sb.append(MovieCategoryColumns.MOVIE_ID+"INTEGERNOTNULL,");
  12. sb.append(MovieCategoryColumns.CATEGORY_ID+"INTEGERNOTNULL,");
  13. sb.append("FOREIGNKEY("+MovieCategoryColumns.MOVIE_ID+")REFERENCES"+MovieTable.TABLE_NAME+"("
  14. +BaseColumns._ID+"),");
  15. sb.append("FOREIGNKEY("+MovieCategoryColumns.CATEGORY_ID+")REFERENCES"+CategoryTable.TABLE_NAME+"("
  16. +BaseColumns._ID+"),");
  17. sb.append("PRIMARYKEY("+MovieCategoryColumns.MOVIE_ID+","+MovieCategoryColumns.CATEGORY_ID+")");
  18. sb.append(");");
  19. db.execSQL(sb.toString());
  20. }
  21. publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
  22. db.execSQL("DROPTABLEIFEXISTS"+MovieCategoryTable.TABLE_NAME);
  23. MovieCategoryTable.onCreate(db);
  24. }
  25. }

last,The SQLiteOpenHelper used for creating and updating databases.

we need to somehow tell Android tobuild those tables,This is done by extending SQLiteOpenHelper.

[html] view plain copy
  1. publicclassOpenHelperextendsSQLiteOpenHelper{
  2. privatestaticfinalintDATABASE_VERSION=1;
  3. privateContextcontext;
  4. publicOpenHelper(finalContextcontext){
  5. super(context,DataConstants.DATABASE_NAME,null,DATABASE_VERSION);
  6. this.context=context;
  7. }
  8. publicvoidonOpen(finalSQLiteDatabasedb){
  9. super.onOpen(db);
  10. if(!db.isReadOnly()){
  11. //versionsofSQLiteolderthan3.6.19don'tsupportforeignkeys
  12. //makesureforeignkeysupportisturnedonifit'sthere
  13. db.execSQL("PRAGMAforeign_keys=ON;");
  14. //thenwechecktomakesurethey'reon
  15. Cursorc=db.rawQuery("PRAGMAforeign_keys",null);
  16. if(c.moveToFirst()){
  17. intresult=c.getInt(0);
  18. Log.i(Constants.LOG_TAG,"SQLiteforeignkeysupport(1ison,0isoff):"+result);
  19. }else{
  20. Log.i(Constants.LOG_TAG,"SQLiteforeignkeysupportNOTAVAILABLE");
  21. }
  22. if(!c.isClosed()){
  23. c.close();
  24. }
  25. }
  26. }
  27. @Override
  28. publicvoidonCreate(finalSQLiteDatabasedb){
  29. //TODOAuto-generatedmethodstub
  30. Log.i(Constants.LOG_TAG,"DataHelper.OpenHelperonCreatecreatingdatabase"+DataConstants.DATABASE_NAME);
  31. CategoryTable.onCreate(db);
  32. //populateinitialcategories(oneway,thereareseveral,thisworksokforsmalldataset)
  33. CategoryDaocategoryDao=newCategoryDao(db);
  34. String[]categories=context.getResources().getStringArray(R.array.tmdb_categories);
  35. for(Stringcat:categories){
  36. categoryDao.save(newCategory(0,cat));
  37. }
  38. MovieTable.onCreate(db);
  39. MovieCategoryTable.onCreate(db);
  40. }
  41. @Override
  42. publicvoidonUpgrade(finalSQLiteDatabasedb,finalintoldVersion,finalintnewVersion){
  43. //TODOAuto-generatedmethodstub
  44. Log.i(Constants.LOG_TAG,"SQLiteOpenHelperonUpgrade-oldVersion:"+oldVersion+"newVersion:"
  45. +newVersion);
  46. MovieCategoryTable.onUpgrade(db,oldVersion,newVersion);
  47. MovieTable.onUpgrade(db,oldVersion,newVersion);
  48. CategoryTable.onUpgrade(db,oldVersion,newVersion);
  49. }
  50. }

Each table object has a static method for onCreate and onUpgrade that’s called from OpenHelper’s methods.

To supply initial data of Category,we do this:

create arrays.xml

[html] view plain copy
  1. <?xmlversion="1.0"encoding="utf-8"?>
  2. <resources>
  3. <!--UsedinView/Spinner1.java-->
  4. <string-arrayname="tmdb_categories">
  5. <item>Action</item>
  6. <item>Adventure</item>
  7. <item>Animation</item>
  8. <item>Comedy</item>
  9. <item>Crime</item>
  10. <item>Disaster</item>
  11. <item>Documentary</item>
  12. <item>Drama</item>
  13. <item>Eastern</item>
  14. <item>Erotic</item>
  15. <item>Family</item>
  16. <item>FanFilm</item>
  17. <item>Fantasy</item>
  18. <item>FilmNoir</item>
  19. <item>History</item>
  20. <item>Holiday</item>
  21. <item>Horror</item>
  22. <item>Indie</item>
  23. <item>Music</item>
  24. <item>Musical</item>
  25. <item>Mystery</item>
  26. <item>NeoNoir</item>
  27. <item>RoadMovie</item>
  28. <item>Romance</item>
  29. <item>ScienceFiction</item>
  30. <item>Short</item>
  31. <item>Sport</item>
  32. <item>Suspense</item>
  33. <item>Thriller</item>
  34. <item>War</item>
  35. <item>Western</item>
  36. </string-array>
  37. </resources>
in the SqliteOpenHelper class onCreate method: [html] view plain copy
  1. //populateinitialcategories(oneway,thereareseveral,thisworksokforsmalldataset)
  2. CategoryDaocategoryDao=newCategoryDao(db);
  3. String[]categories=context.getResources().getStringArray(R.array.tmdb_categories);
  4. for(Stringcat:categories){
  5. categoryDao.save(newCategory(0,cat));
  6. }
Forsmall amounts of data this works fine.
for large volumes of data,you can create your SQLite db file ahead of time (each SQLite database is stored as asingle file).At runtime each application database is stored in a file at the /data/data/<packagename>/databases/ internal storage location.

database:

Once we have a SQLiteOpenHelper, we can use it from anywhere in our application tocreate a SQLiteDatabase object. The SQLiteDatabase object is the keystone of
Android SQLite database operations. This is where we’ll create connections and performdata operations such as select, update, insert, and delete.

here’s an example of using our OpenHelper to obtaina SQLiteDatabase reference:


SQLiteOpenHelper openHelper = new OpenHelper(this.context);
SQLiteDatabase db = openHelper.getWritableDatabase();


The getWritableDatabase method of SQLiteOpenHelper will call onCreate the firsttime it’s called, and thereafter will call onOpen.

We have model objects for working with the data in our application’s Java code andtable objects to keep the details for each table separate from one another. We also
have a SQLiteOpenHelper implementation that can be used to create and update ourdatabase, and to provide references to the SQLiteDatabase objects we’ll later use to

store and retrieve data

原blog:

http://blog.csdn.net/kaixinbingju/article/details/8468178

更多相关文章

  1. 代码中设置drawableleft
  2. android 3.0 隐藏 系统标题栏
  3. Android开发中activity切换动画的实现
  4. Android(安卓)学习 笔记_05. 文件下载
  5. Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
  6. 技术博客汇总
  7. android 2.3 wifi (一)
  8. AndRoid Notification的清空和修改
  9. Android中的Chronometer

随机推荐

  1. 【春节特辑】斐波那契数列的黄金分割
  2. 在 GitHub 公开源码,造成百万损失,大疆程序
  3. 做出这道题,说明你很有机会进入 Google
  4. 数据结构与算法——2-3树
  5. 花了 2 亿多,等了近 2 年,结果连个可用的网
  6. 剑指 offer 第一题: 二维数组中的查找
  7. 算法科普:有趣的游程编码
  8. Android(安卓)BLE开发小记
  9. 数据结构与算法——2-3-4树
  10. 图解剑指 offer 第二题: 替换空格