android in practice_create model、table class and sqlitehelper(MyMoviesDataBases project)
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- /TheModelBaseclass,whichbothMovieandCategoryextend,containsonlyalongid.
- publicclassModelBase{
- protectedlongid;
- publiclonggetId(){
- returnthis.id;
- }
- publicvoidsetId(longid){
- this.id=id;
- }
- @Override
- publicStringtoString(){
- return"ModelBase[id="+this.id+"]";
- }
- @Override
- publicinthashCode(){
- finalintprime=31;
- intresult=1;
- result=prime*result+(int)(this.id^(this.id>>>32));
- returnresult;
- }
- @Override
- publicbooleanequals(Objectobj){
- if(this==obj){
- returntrue;
- }
- if(obj==null){
- returnfalse;
- }
- if(!(objinstanceofModelBase)){
- returnfalse;
- }
- ModelBaseother=(ModelBase)obj;
- if(this.id!=other.id){
- returnfalse;
- }
- returntrue;
- }
- }
Movie model: [html] view plain copy
- publicclassMovieextendsModelBase{
- privateStringproviderId;
- privateStringname;
- privateintyear;
- privatedoublerating;
- privateStringurl;
- privateStringhomepage;
- privateStringtrailer;
- privateStringtagline;
- privateStringthumbUrl;
- privateStringimageUrl;
- privateSet<Category>categories;
- //note,inthereal-worldmakingthesemodelbeansimmutablewouldbeabetterapproach
- //(thatistosay,notmakingthemJavaBeans,butmakignimmutablemodelclasseswithBuilder)
- publicMovie(){
- this.categories=newLinkedHashSet<Category>();
- }
- publicStringgetProviderId(){
- returnthis.providerId;
- }
- publicvoidsetProviderId(StringproviderId){
- this.providerId=providerId;
- }
- publicStringgetName(){
- returnthis.name;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- publicintgetYear(){
- returnthis.year;
- }
- publicvoidsetYear(intyear){
- this.year=year;
- }
- publicdoublegetRating(){
- returnthis.rating;
- }
- publicvoidsetRating(doublerating){
- this.rating=rating;
- }
- publicStringgetUrl(){
- returnthis.url;
- }
- publicvoidsetUrl(Stringurl){
- this.url=url;
- }
- publicStringgetHomepage(){
- returnthis.homepage;
- }
- publicvoidsetHomepage(Stringhomepage){
- this.homepage=homepage;
- }
- publicStringgetTrailer(){
- returnthis.trailer;
- }
- publicvoidsetTrailer(Stringtrailer){
- this.trailer=trailer;
- }
- publicStringgetTagline(){
- returnthis.tagline;
- }
- publicvoidsetTagline(Stringtagline){
- this.tagline=tagline;
- }
- publicStringgetThumbUrl(){
- returnthis.thumbUrl;
- }
- publicvoidsetThumbUrl(StringthumbUrl){
- this.thumbUrl=thumbUrl;
- }
- publicStringgetImageUrl(){
- returnthis.imageUrl;
- }
- publicvoidsetImageUrl(StringimageUrl){
- this.imageUrl=imageUrl;
- }
- publicSet<Category>getCategories(){
- returnthis.categories;
- }
- publicvoidsetCategories(Set<Category>categories){
- this.categories=categories;
- }
- @Override
- publicStringtoString(){
- return"Movie[categories="+this.categories+",homepage="+this.homepage+",name="+this.name
- +",providerId="+this.providerId+",rating="+this.rating+",tagline="+this.tagline
- +",thumbUrl="+this.thumbUrl+",imageUrl="+this.imageUrl+",trailer="+this.trailer+",url="
- +this.url+",year="+this.year+"]";
- }
- @Override
- publicinthashCode(){
- finalintprime=31;
- intresult=super.hashCode();
- result=prime*result+((this.categories==null)?0:this.categories.hashCode());
- result=prime*result+((this.homepage==null)?0:this.homepage.hashCode());
- //uppernamesohashCodeisconsistentwithequals(equalsignorescase)
- result=prime*result+((this.name==null)?0:this.name.toUpperCase().hashCode());
- result=prime*result+((this.providerId==null)?0:this.providerId.hashCode());
- longtemp;
- temp=Double.doubleToLongBits(this.rating);
- result=prime*result+(int)(temp^(temp>>>32));
- result=prime*result+((this.tagline==null)?0:this.tagline.hashCode());
- result=prime*result+((this.thumbUrl==null)?0:this.thumbUrl.hashCode());
- result=prime*result+((this.imageUrl==null)?0:this.imageUrl.hashCode());
- result=prime*result+((this.trailer==null)?0:this.trailer.hashCode());
- result=prime*result+((this.url==null)?0:this.url.hashCode());
- result=prime*result+this.year;
- returnresult;
- }
- @Override
- publicbooleanequals(Objectobj){
- if(this==obj){
- returntrue;
- }
- if(!super.equals(obj)){
- returnfalse;
- }
- if(!(objinstanceofMovie)){
- returnfalse;
- }
- Movieother=(Movie)obj;
- if(this.categories==null){
- if(other.categories!=null){
- returnfalse;
- }
- }elseif(!this.categories.equals(other.categories)){
- returnfalse;
- }
- if(this.homepage==null){
- if(other.homepage!=null){
- returnfalse;
- }
- }elseif(!this.homepage.equals(other.homepage)){
- returnfalse;
- }
- if(this.name==null){
- if(other.name!=null){
- returnfalse;
- //namecheckignorescase
- }
- }elseif(!this.name.equalsIgnoreCase(other.name)){
- returnfalse;
- }
- if(this.providerId==null){
- if(other.providerId!=null){
- returnfalse;
- }
- }elseif(!this.providerId.equals(other.providerId)){
- returnfalse;
- }
- if(Double.doubleToLongBits(this.rating)!=Double.doubleToLongBits(other.rating)){
- returnfalse;
- }
- if(this.tagline==null){
- if(other.tagline!=null){
- returnfalse;
- }
- }elseif(!this.tagline.equals(other.tagline)){
- returnfalse;
- }
- if(this.thumbUrl==null){
- if(other.thumbUrl!=null){
- returnfalse;
- }
- }elseif(!this.thumbUrl.equals(other.thumbUrl)){
- returnfalse;
- }
- if(this.imageUrl==null){
- if(other.imageUrl!=null){
- returnfalse;
- }
- }elseif(!this.imageUrl.equals(other.imageUrl)){
- returnfalse;
- }
- if(this.trailer==null){
- if(other.trailer!=null){
- returnfalse;
- }
- }elseif(!this.trailer.equals(other.trailer)){
- returnfalse;
- }
- if(this.url==null){
- if(other.url!=null){
- returnfalse;
- }
- }elseif(!this.url.equals(other.url)){
- returnfalse;
- }
- if(this.year!=other.year){
- returnfalse;
- }
- returntrue;
- }
- }
- publicclassCategoryextendsModelBaseimplementsComparable<Category>{
- //NOTEinreal-worldandroidappyoumightwantaCategoryFactory
- //orfactorymethodhere,tocutdownonnumberofobjectscreated
- privateStringname;
- publicCategory(){
- }
- publicCategory(longid,Stringname){
- this.id=id;
- this.name=name;
- }
- publicStringgetName(){
- returnthis.name;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- }
- @Override
- publicStringtoString(){
- returnthis.name;
- }
- @Override
- publicintcompareTo(Categoryanother){
- if(another==null){
- return-1;
- }
- if(this.name==null){
- return1;
- }
- returnthis.name.compareTo(another.name);
- }
- @Override
- publicinthashCode(){
- finalintprime=31;
- intresult=super.hashCode();
- //uppernamesohashCodeisconsistentwithequals(equalsignorescase)
- result=prime*result+((this.name==null)?0:this.name.toUpperCase().hashCode());
- returnresult;
- }
- @Override
- publicbooleanequals(Objectobj){
- if(this==obj){
- returntrue;
- }
- if(!super.equals(obj)){
- returnfalse;
- }
- if(!(objinstanceofCategory)){
- returnfalse;
- }
- Categoryother=(Category)obj;
- if(this.name==null){
- if(other.name!=null){
- returnfalse;
- //namecheckignorescase
- }
- }elseif(!this.name.equalsIgnoreCase(other.name)){
- returnfalse;
- }
- returntrue;
- }
- }
predefine Constant class:Constants、DataConstants: [html] view plain copy
- publicclassConstants{
- publicstaticfinalStringLOG_TAG="MyMovies";
- privateConstants(){
- }
- }
- publicclassDataConstants{
- privatestaticfinalStringAPP_PACKAGE_NAME="example.mymoviesdatabases";
- privatestaticfinalStringEXTERNAL_DATA_DIR_NAME="mymoviesdata";
- publicstaticfinalStringEXTERNAL_DATA_PATH=
- Environment.getExternalStorageDirectory()+"/"+DataConstants.EXTERNAL_DATA_DIR_NAME;
- publicstaticfinalStringDATABASE_NAME="mymovies.db";
- publicstaticfinalStringDATABASE_PATH=
- Environment.getDataDirectory()+"/data/"+DataConstants.APP_PACKAGE_NAME+"/databases/"
- +DataConstants.DATABASE_NAME;
- privateDataConstants(){
- }
- }
MovieTable table class:
The MovieTable class with static methods and inner class MovieColumns.
[html] view plain copy- publicfinalclassMovieTable{
- publicstaticfinalStringTABLE_NAME="movie";
- //BaseColumnsisprovidedbyAndroid,anditdefinesthe_idcolumn
- publicstaticclassMovieColumnsimplementsBaseColumns{
- publicstaticfinalStringHOMEPAGE="homepage";
- publicstaticfinalStringNAME="movie_name";
- publicstaticfinalStringRATING="rating";
- publicstaticfinalStringTAGLINE="tagline";
- publicstaticfinalStringTHUMB_URL="thumb_url";
- publicstaticfinalStringIMAGE_URL="image_url";
- publicstaticfinalStringTRAILER="trailer";
- publicstaticfinalStringURL="url";
- publicstaticfinalStringYEAR="year";
- }
- publicstaticvoidonCreate(SQLiteDatabasedb){
- StringBuildersb=newStringBuilder();
- //movietable
- sb.append("CREATETABLE"+MovieTable.TABLE_NAME+"(");
- sb.append(BaseColumns._ID+"INTEGERPRIMARYKEY,");
- sb.append(MovieColumns.HOMEPAGE+"TEXT,");
- sb.append(MovieColumns.NAME+"TEXTUNIQUENOTNULL,");
- //movienamesaren'tunique,butforsimplificationweconstrain
- sb.append(MovieColumns.RATING+"INTEGER,");
- sb.append(MovieColumns.TAGLINE+"TEXT,");
- sb.append(MovieColumns.THUMB_URL+"TEXT,");
- sb.append(MovieColumns.IMAGE_URL+"TEXT,");
- sb.append(MovieColumns.TRAILER+"TEXT,");
- sb.append(MovieColumns.URL+"TEXT,");
- sb.append(MovieColumns.YEAR+"INTEGER");
- sb.append(");");
- db.execSQL(sb.toString());
- }
- publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
- db.execSQL("DROPTABLEIFEXISTS"+MovieTable.TABLE_NAME);
- MovieTable.onCreate(db);
- }
- }
with static methods and inner class CategoryColumns:
- publicclassCategoryTable{
- publicstaticfinalStringTABLE_NAME="category";
- publicstaticclassCategoryColumnsimplementsBaseColumns{
- publicstaticfinalStringNAME="name";
- }
- publicstaticvoidonCreate(SQLiteDatabasedb){
- StringBuildersb=newStringBuilder();
- //categorytable
- sb.append("CREATETABLE"+CategoryTable.TABLE_NAME+"(");
- sb.append(BaseColumns._ID+"INTEGERPRIMARYKEY,");
- sb.append(CategoryColumns.NAME+"TEXTUNIQUENOTNULL");
- sb.append(");");
- db.execSQL(sb.toString());
- }
- publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
- db.execSQL("DROPTABLEIFEXISTS"+CategoryTable.TABLE_NAME);
- CategoryTable.onCreate(db);
- }
- }
MovieCategoryTable table class
[html] view plain copy
- publicclassMovieCategoryTable{
- publicstaticfinalStringTABLE_NAME="movie_category";
- publicstaticclassMovieCategoryColumns{
- publicstaticfinalStringMOVIE_ID="movie_id";
- publicstaticfinalStringCATEGORY_ID="category_id";
- }
- publicstaticvoidonCreate(SQLiteDatabasedb){
- StringBuildersb=newStringBuilder();
- //movie_categorymappingtable
- sb.append("CREATETABLE"+MovieCategoryTable.TABLE_NAME+"(");
- sb.append(MovieCategoryColumns.MOVIE_ID+"INTEGERNOTNULL,");
- sb.append(MovieCategoryColumns.CATEGORY_ID+"INTEGERNOTNULL,");
- sb.append("FOREIGNKEY("+MovieCategoryColumns.MOVIE_ID+")REFERENCES"+MovieTable.TABLE_NAME+"("
- +BaseColumns._ID+"),");
- sb.append("FOREIGNKEY("+MovieCategoryColumns.CATEGORY_ID+")REFERENCES"+CategoryTable.TABLE_NAME+"("
- +BaseColumns._ID+"),");
- sb.append("PRIMARYKEY("+MovieCategoryColumns.MOVIE_ID+","+MovieCategoryColumns.CATEGORY_ID+")");
- sb.append(");");
- db.execSQL(sb.toString());
- }
- publicstaticvoidonUpgrade(SQLiteDatabasedb,intoldVersion,intnewVersion){
- db.execSQL("DROPTABLEIFEXISTS"+MovieCategoryTable.TABLE_NAME);
- MovieCategoryTable.onCreate(db);
- }
- }
last,The SQLiteOpenHelper used for creating and updating databases.
we need to somehow tell Android tobuild those tables,This is done by extending SQLiteOpenHelper.
- publicclassOpenHelperextendsSQLiteOpenHelper{
- privatestaticfinalintDATABASE_VERSION=1;
- privateContextcontext;
- publicOpenHelper(finalContextcontext){
- super(context,DataConstants.DATABASE_NAME,null,DATABASE_VERSION);
- this.context=context;
- }
- publicvoidonOpen(finalSQLiteDatabasedb){
- super.onOpen(db);
- if(!db.isReadOnly()){
- //versionsofSQLiteolderthan3.6.19don'tsupportforeignkeys
- //makesureforeignkeysupportisturnedonifit'sthere
- db.execSQL("PRAGMAforeign_keys=ON;");
- //thenwechecktomakesurethey'reon
- Cursorc=db.rawQuery("PRAGMAforeign_keys",null);
- if(c.moveToFirst()){
- intresult=c.getInt(0);
- Log.i(Constants.LOG_TAG,"SQLiteforeignkeysupport(1ison,0isoff):"+result);
- }else{
- Log.i(Constants.LOG_TAG,"SQLiteforeignkeysupportNOTAVAILABLE");
- }
- if(!c.isClosed()){
- c.close();
- }
- }
- }
- @Override
- publicvoidonCreate(finalSQLiteDatabasedb){
- //TODOAuto-generatedmethodstub
- Log.i(Constants.LOG_TAG,"DataHelper.OpenHelperonCreatecreatingdatabase"+DataConstants.DATABASE_NAME);
- CategoryTable.onCreate(db);
- //populateinitialcategories(oneway,thereareseveral,thisworksokforsmalldataset)
- CategoryDaocategoryDao=newCategoryDao(db);
- String[]categories=context.getResources().getStringArray(R.array.tmdb_categories);
- for(Stringcat:categories){
- categoryDao.save(newCategory(0,cat));
- }
- MovieTable.onCreate(db);
- MovieCategoryTable.onCreate(db);
- }
- @Override
- publicvoidonUpgrade(finalSQLiteDatabasedb,finalintoldVersion,finalintnewVersion){
- //TODOAuto-generatedmethodstub
- Log.i(Constants.LOG_TAG,"SQLiteOpenHelperonUpgrade-oldVersion:"+oldVersion+"newVersion:"
- +newVersion);
- MovieCategoryTable.onUpgrade(db,oldVersion,newVersion);
- MovieTable.onUpgrade(db,oldVersion,newVersion);
- CategoryTable.onUpgrade(db,oldVersion,newVersion);
- }
- }
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- <?xmlversion="1.0"encoding="utf-8"?>
- <resources>
- <!--UsedinView/Spinner1.java-->
- <string-arrayname="tmdb_categories">
- <item>Action</item>
- <item>Adventure</item>
- <item>Animation</item>
- <item>Comedy</item>
- <item>Crime</item>
- <item>Disaster</item>
- <item>Documentary</item>
- <item>Drama</item>
- <item>Eastern</item>
- <item>Erotic</item>
- <item>Family</item>
- <item>FanFilm</item>
- <item>Fantasy</item>
- <item>FilmNoir</item>
- <item>History</item>
- <item>Holiday</item>
- <item>Horror</item>
- <item>Indie</item>
- <item>Music</item>
- <item>Musical</item>
- <item>Mystery</item>
- <item>NeoNoir</item>
- <item>RoadMovie</item>
- <item>Romance</item>
- <item>ScienceFiction</item>
- <item>Short</item>
- <item>Sport</item>
- <item>Suspense</item>
- <item>Thriller</item>
- <item>War</item>
- <item>Western</item>
- </string-array>
- </resources>
- //populateinitialcategories(oneway,thereareseveral,thisworksokforsmalldataset)
- CategoryDaocategoryDao=newCategoryDao(db);
- String[]categories=context.getResources().getStringArray(R.array.tmdb_categories);
- for(Stringcat:categories){
- categoryDao.save(newCategory(0,cat));
- }
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.
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
更多相关文章
- 代码中设置drawableleft
- android 3.0 隐藏 系统标题栏
- Android开发中activity切换动画的实现
- Android(安卓)学习 笔记_05. 文件下载
- Android中直播视频技术探究之—摄像头Camera视频源数据采集解析
- 技术博客汇总
- android 2.3 wifi (一)
- AndRoid Notification的清空和修改
- Android中的Chronometer