android in practice_create model、table class and sqlitehelper(MyMoviesDataBases project)

In essence, 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 simple interface and DAOs for our model objects.last,create a data manager layer to wrap around those DAOs.

Designing a data access layer:


design table relations:


In general, if you need 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 to use 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:

  1. /The ModelBase class, which both Movie and Category extend, contains only a long id.  
  2. public class ModelBase {  
  3.        protected long id;  
  4.        public long getId() {  
  5.           return this.id;  
  6.        }  
  7.        public void setId(long id) {  
  8.           this.id = id;  
  9.        }  
  10.        @Override  
  11.        public String toString() {  
  12.           return "ModelBase [id=" + this.id + "]";  
  13.        }  
  14.        @Override  
  15.        public int hashCode() {  
  16.           final int prime = 31;  
  17.           int result = 1;  
  18.           result = prime * result + (int) (this.id ^ (this.id >>> 32));  
  19.           return result;  
  20.        }  
  21.   
  22.        @Override  
  23.        public boolean equals(Object obj) {  
  24.           if (this == obj) {  
  25.              return true;  
  26.           }  
  27.           if (obj == null) {  
  28.              return false;  
  29.           }  
  30.           if (!(obj instanceof ModelBase)) {  
  31.              return false;  
  32.           }  
  33.           ModelBase other = (ModelBase) obj;  
  34.           if (this.id != other.id) {  
  35.              return false;  
  36.           }  
  37.           return true;  
  38.        }  
  39. }  

Movie model:
  1. public class Movie extends ModelBase {  
  2.        private String providerId;  
  3.        private String name;  
  4.        private int year;  
  5.        private double rating;  
  6.        private String url;  
  7.        private String homepage;  
  8.        private String trailer;  
  9.        private String tagline;  
  10.        private String thumbUrl;  
  11.        private String imageUrl;  
  12.        private Set<Category> categories;  
  13.   
  14.        // note, in the real-world making these model beans immutable would be a better approach  
  15.        // (that is to say, not making them JavaBeans, but makign immutable model classes with Builder)  
  16.   
  17.        public Movie() {  
  18.           this.categories = new LinkedHashSet<Category>();  
  19.        }  
  20.   
  21.        public String getProviderId() {  
  22.           return this.providerId;  
  23.        }  
  24.   
  25.        public void setProviderId(String providerId) {  
  26.           this.providerId = providerId;  
  27.        }  
  28.   
  29.        public String getName() {  
  30.           return this.name;  
  31.        }  
  32.   
  33.        public void setName(String name) {  
  34.           this.name = name;  
  35.        }  
  36.   
  37.        public int getYear() {  
  38.           return this.year;  
  39.        }  
  40.   
  41.        public void setYear(int year) {  
  42.           this.year = year;  
  43.        }  
  44.   
  45.        public double getRating() {  
  46.           return this.rating;  
  47.        }  
  48.   
  49.        public void setRating(double rating) {  
  50.           this.rating = rating;  
  51.        }  
  52.   
  53.        public String getUrl() {  
  54.           return this.url;  
  55.        }  
  56.   
  57.        public void setUrl(String url) {  
  58.           this.url = url;  
  59.        }  
  60.   
  61.        public String getHomepage() {  
  62.           return this.homepage;  
  63.        }  
  64.   
  65.        public void setHomepage(String homepage) {  
  66.           this.homepage = homepage;  
  67.        }  
  68.   
  69.        public String getTrailer() {  
  70.           return this.trailer;  
  71.        }  
  72.   
  73.        public void setTrailer(String trailer) {  
  74.           this.trailer = trailer;  
  75.        }  
  76.   
  77.        public String getTagline() {  
  78.           return this.tagline;  
  79.        }  
  80.   
  81.        public void setTagline(String tagline) {  
  82.           this.tagline = tagline;  
  83.        }  
  84.   
  85.        public String getThumbUrl() {  
  86.           return this.thumbUrl;  
  87.        }  
  88.   
  89.        public void setThumbUrl(String thumbUrl) {  
  90.           this.thumbUrl = thumbUrl;  
  91.        }  
  92.   
  93.        public String getImageUrl() {  
  94.           return this.imageUrl;  
  95.        }  
  96.   
  97.        public void setImageUrl(String imageUrl) {  
  98.           this.imageUrl = imageUrl;  
  99.        }  
  100.   
  101.        public Set<Category> getCategories() {  
  102.           return this.categories;  
  103.        }  
  104.   
  105.        public void setCategories(Set<Category> categories) {  
  106.           this.categories = categories;  
  107.        }  
  108.   
  109.        @Override  
  110.        public String toString() {  
  111.           return "Movie [categories=" + this.categories + "homepage=" + this.homepage + "name=" + this.name  
  112.                    + ", providerId=" + this.providerId + "rating=" + this.rating + "tagline=" + this.tagline  
  113.                    + ", thumbUrl=" + this.thumbUrl + "imageUrl=" + this.imageUrl + "trailer=" + this.trailer + "url="  
  114.                    + this.url + ", year=" + this.year + "]";  
  115.        }  
  116.   
  117.        @Override  
  118.        public int hashCode() {  
  119.           final int prime = 31;  
  120.           int result = super.hashCode();  
  121.           result = prime * result + ((this.categories == null) ? 0 : this.categories.hashCode());  
  122.           result = prime * result + ((this.homepage == null) ? 0 : this.homepage.hashCode());  
  123.           // upper name so hashCode is consistent with equals (equals ignores case)  
  124.           result = prime * result + ((this.name == null) ? 0 : this.name.toUpperCase().hashCode());  
  125.           result = prime * result + ((this.providerId == null) ? 0 : this.providerId.hashCode());  
  126.           long temp;  
  127.           temp = Double.doubleToLongBits(this.rating);  
  128.           result = prime * result + (int) (temp ^ (temp >>> 32));  
  129.           result = prime * result + ((this.tagline == null) ? 0 : this.tagline.hashCode());  
  130.           result = prime * result + ((this.thumbUrl == null) ? 0 : this.thumbUrl.hashCode());  
  131.           result = prime * result + ((this.imageUrl == null) ? 0 : this.imageUrl.hashCode());  
  132.           result = prime * result + ((this.trailer == null) ? 0 : this.trailer.hashCode());  
  133.           result = prime * result + ((this.url == null) ? 0 : this.url.hashCode());  
  134.           result = prime * result + this.year;  
  135.           return result;  
  136.        }  
  137.   
  138.        @Override  
  139.        public boolean equals(Object obj) {  
  140.           if (this == obj) {  
  141.              return true;  
  142.           }  
  143.           if (!super.equals(obj)) {  
  144.              return false;  
  145.           }  
  146.           if (!(obj instanceof Movie)) {  
  147.              return false;  
  148.           }  
  149.           Movie other = (Movie) obj;  
  150.           if (this.categories == null) {  
  151.              if (other.categories != null) {  
  152.                 return false;  
  153.              }  
  154.           } else if (!this.categories.equals(other.categories)) {  
  155.              return false;  
  156.           }  
  157.           if (this.homepage == null) {  
  158.              if (other.homepage != null) {  
  159.                 return false;  
  160.              }  
  161.           } else if (!this.homepage.equals(other.homepage)) {  
  162.              return false;  
  163.           }  
  164.           if (this.name == null) {  
  165.              if (other.name != null) {  
  166.                 return false;  
  167.                 // name check ignores case  
  168.              }  
  169.           } else if (!this.name.equalsIgnoreCase(other.name)) {  
  170.              return false;  
  171.           }  
  172.           if (this.providerId == null) {  
  173.              if (other.providerId != null) {  
  174.                 return false;  
  175.              }  
  176.           } else if (!this.providerId.equals(other.providerId)) {  
  177.              return false;  
  178.           }  
  179.           if (Double.doubleToLongBits(this.rating) != Double.doubleToLongBits(other.rating)) {  
  180.              return false;  
  181.           }  
  182.           if (this.tagline == null) {  
  183.              if (other.tagline != null) {  
  184.                 return false;  
  185.              }  
  186.           } else if (!this.tagline.equals(other.tagline)) {  
  187.              return false;  
  188.           }  
  189.           if (this.thumbUrl == null) {  
  190.              if (other.thumbUrl != null) {  
  191.                 return false;  
  192.              }  
  193.           } else if (!this.thumbUrl.equals(other.thumbUrl)) {  
  194.              return false;  
  195.           }  
  196.           if (this.imageUrl == null) {  
  197.              if (other.imageUrl != null) {  
  198.                 return false;  
  199.              }  
  200.           } else if (!this.imageUrl.equals(other.imageUrl)) {  
  201.              return false;  
  202.           }  
  203.           if (this.trailer == null) {  
  204.              if (other.trailer != null) {  
  205.                 return false;  
  206.              }  
  207.           } else if (!this.trailer.equals(other.trailer)) {  
  208.              return false;  
  209.           }  
  210.           if (this.url == null) {  
  211.              if (other.url != null) {  
  212.                 return false;  
  213.              }  
  214.           } else if (!this.url.equals(other.url)) {  
  215.              return false;  
  216.           }  
  217.           if (this.year != other.year) {  
  218.              return false;  
  219.           }  
  220.           return true;  
  221.        }  
  222. }  
Category model:
  1. public class Category extends ModelBase implements Comparable<Category> {  
  2.        // NOTE in real-world android app you might want a CategoryFactory  
  3.        // or factory method here, to cut down on number of objects created  
  4.       private String name;  
  5.        public Category() {  
  6.        }  
  7.   
  8.        public Category(long id, String name) {  
  9.           this.id = id;  
  10.           this.name = name;  
  11.        }  
  12.   
  13.        public String getName() {  
  14.           return this.name;  
  15.        }  
  16.   
  17.        public void setName(String name) {  
  18.           this.name = name;  
  19.        }  
  20.   
  21.        @Override  
  22.        public String toString() {  
  23.           return this.name;  
  24.        }  
  25.   
  26.        @Override  
  27.        public int compareTo(Category another) {  
  28.           if (another == null) {  
  29.              return -1;  
  30.           }  
  31.           if (this.name == null) {  
  32.              return 1;  
  33.           }  
  34.           return this.name.compareTo(another.name);  
  35.        }  
  36.   
  37.        @Override  
  38.        public int hashCode() {  
  39.           final int prime = 31;  
  40.           int result = super.hashCode();  
  41.           // upper name so hashCode is consistent with equals (equals ignores case)  
  42.           result = prime * result + ((this.name == null) ? 0 : this.name.toUpperCase().hashCode());  
  43.           return result;  
  44.        }  
  45.   
  46.        @Override  
  47.        public boolean equals(Object obj) {  
  48.           if (this == obj) {  
  49.              return true;  
  50.           }  
  51.           if (!super.equals(obj)) {  
  52.              return false;  
  53.           }  
  54.           if (!(obj instanceof Category)) {  
  55.              return false;  
  56.           }  
  57.           Category other = (Category) obj;  
  58.           if (this.name == null) {  
  59.              if (other.name != null) {  
  60.                 return false;  
  61.                 // name check ignores case  
  62.              }  
  63.           } else if (!this.name.equalsIgnoreCase(other.name)) {  
  64.              return false;  
  65.           }  
  66.           return true;  
  67.        }  
  68. }  


predefine Constant class:Constants、DataConstants:
  1. public class Constants {  
  2.        public static final String LOG_TAG = "MyMovies";  
  3.        private Constants() {  
  4.        }  
  5. }  
  1. public class DataConstants {  
  2.        private static final String APP_PACKAGE_NAME = "example.mymoviesdatabases";  
  3.        private static final String EXTERNAL_DATA_DIR_NAME = "mymoviesdata";  
  4.        public static final String EXTERNAL_DATA_PATH =  
  5.                 Environment.getExternalStorageDirectory() + "/" + DataConstants.EXTERNAL_DATA_DIR_NAME;  
  6.   
  7.        public static final String DATABASE_NAME = "mymovies.db";  
  8.        public static final String DATABASE_PATH =  
  9.                 Environment.getDataDirectory() + "/data/" + DataConstants.APP_PACKAGE_NAME + "/databases/"  
  10.                          + DataConstants.DATABASE_NAME;  
  11.   
  12.        private DataConstants() {  
  13.        }  
  14. }  

MovieTable  table class:

The MovieTable class with static methods and inner class MovieColumns.

  1. public final class MovieTable {  
  2.        public static final String TABLE_NAME = "movie";  
  3.        //BaseColumns is provided by Android, and it defines the _id column  
  4.        public static class MovieColumns implements BaseColumns{  
  5.               public static final String HOMEPAGE = "homepage";  
  6.               public static final String NAME = "movie_name";  
  7.               public static final String RATING = "rating";  
  8.               public static final String TAGLINE = "tagline";  
  9.               public static final String THUMB_URL = "thumb_url";  
  10.               public static final String IMAGE_URL = "image_url";  
  11.               public static final String TRAILER = "trailer";  
  12.               public static final String URL = "url";  
  13.               public static final String YEAR = "year";  
  14.        }  
  15.   
  16.        public static void onCreate(SQLiteDatabase db) {  
  17.            StringBuilder sb=new StringBuilder();  
  18.            // movie table  
  19.            sb.append("CREATE TABLE"+MovieTable.TABLE_NAME+"(");  
  20.            sb.append(BaseColumns._ID+"INTEGER PRIMARY KEY,");  
  21.            sb.append(MovieColumns.HOMEPAGE + " TEXT, ");  
  22.            sb.append(MovieColumns.NAME + " TEXT UNIQUE NOT NULL, ");  
  23.            // movie names aren't unique, but for simplification we constrain  
  24.            sb.append(MovieColumns.RATING + " INTEGER, ");  
  25.            sb.append(MovieColumns.TAGLINE + " TEXT, ");  
  26.            sb.append(MovieColumns.THUMB_URL + " TEXT, ");  
  27.            sb.append(MovieColumns.IMAGE_URL + " TEXT, ");  
  28.            sb.append(MovieColumns.TRAILER + " TEXT, ");  
  29.            sb.append(MovieColumns.URL + " TEXT, ");  
  30.            sb.append(MovieColumns.YEAR + " INTEGER");  
  31.            sb.append(");");  
  32.            db.execSQL(sb.toString());  
  33.        }  
  34.        public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  35.           db.execSQL("DROP TABLE IF EXISTS " + MovieTable.TABLE_NAME);  
  36.           MovieTable.onCreate(db);  
  37.      }  
  38. }  
CategoryTable table class,

with static methods and inner class CategoryColumns:

  1. public class CategoryTable {  
  2.        public static final String TABLE_NAME = "category";  
  3.        public static class CategoryColumns implements BaseColumns {  
  4.           public static final String NAME = "name";  
  5.        }  
  6.   
  7.        public static void onCreate(SQLiteDatabase db) {  
  8.           StringBuilder sb = new StringBuilder();  
  9.           // category table  
  10.           sb.append("CREATE TABLE " + CategoryTable.TABLE_NAME + " (");  
  11.           sb.append(BaseColumns._ID + " INTEGER PRIMARY KEY, ");  
  12.           sb.append(CategoryColumns.NAME + " TEXT UNIQUE NOT NULL");  
  13.           sb.append(");");  
  14.           db.execSQL(sb.toString());  
  15.        }  
  16.   
  17.        public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  18.           db.execSQL("DROP TABLE IF EXISTS " + CategoryTable.TABLE_NAME);  
  19.           CategoryTable.onCreate(db);  
  20.        }  
  21. }  

MovieCategoryTable table class

The MovieCategoryTable class showing the declaration of foreign key references
  1. public class MovieCategoryTable {  
  2.        public static final String TABLE_NAME = "movie_category";  
  3.        public static class MovieCategoryColumns {  
  4.           public static final String MOVIE_ID = "movie_id";  
  5.           public static final String CATEGORY_ID = "category_id";  
  6.        }  
  7.   
  8.        public static void onCreate(SQLiteDatabase db) {  
  9.           StringBuilder sb = new StringBuilder();  
  10.   
  11.           // movie_category mapping table  
  12.           sb.append("CREATE TABLE " + MovieCategoryTable.TABLE_NAME + " (");  
  13.           sb.append(MovieCategoryColumns.MOVIE_ID + " INTEGER NOT NULL, ");  
  14.           sb.append(MovieCategoryColumns.CATEGORY_ID + " INTEGER NOT NULL, ");  
  15.            
  16.           sb.append("FOREIGN KEY(" + MovieCategoryColumns.MOVIE_ID + ") REFERENCES " + MovieTable.TABLE_NAME + "("  
  17.                    + BaseColumns._ID + "), ");  
  18.           sb.append("FOREIGN KEY(" + MovieCategoryColumns.CATEGORY_ID + ") REFERENCES " + CategoryTable.TABLE_NAME + "("  
  19.                    + BaseColumns._ID + ") , ");  
  20.           sb.append("PRIMARY KEY ( " + MovieCategoryColumns.MOVIE_ID + ", " + MovieCategoryColumns.CATEGORY_ID + ")");  
  21.           sb.append(");");  
  22.           db.execSQL(sb.toString());  
  23.        }  
  24.   
  25.        public static void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  26.           db.execSQL("DROP TABLE IF EXISTS " + MovieCategoryTable.TABLE_NAME);  
  27.           MovieCategoryTable.onCreate(db);  
  28.        }  
  29. }  

last,The SQLiteOpenHelper used for creating and updating databases.

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

  1. public class OpenHelper extends SQLiteOpenHelper {  
  2.   
  3.     private static final int DATABASE_VERSION = 1;  
  4.     private Context context;  
  5.     public OpenHelper(final Context context){  
  6.          super(context, DataConstants.DATABASE_NAME, null, DATABASE_VERSION);  
  7.          this.context = context;  
  8.     }  
  9.     public void onOpen(final SQLiteDatabase db){  
  10.           super.onOpen(db);  
  11.           if(!db.isReadOnly()){  
  12.               // versions of SQLite older than 3.6.19 don't support foreign keys  
  13.               // make sure foreign key support is turned on if it's there           
  14.               db.execSQL("PRAGMA foreign_keys=ON;");  
  15.               // then we check to make sure they're on   
  16.               Cursor c=db.rawQuery("PRAGMA foreign_keys", null);  
  17.               if(c.moveToFirst()){  
  18.                   int result=c.getInt(0);  
  19.                   Log.i(Constants.LOG_TAG, "SQLite foreign key support (1 is on, 0 is off): " + result);  
  20.               }else{  
  21.                   Log.i(Constants.LOG_TAG, "SQLite foreign key support NOT AVAILABLE");  
  22.               }  
  23.               if(!c.isClosed()){  
  24.                   c.close();  
  25.               }  
  26.           }     
  27.     }  
  28.   
  29.     @Override  
  30.     public void onCreate(final SQLiteDatabase db) {  
  31.         // TODO Auto-generated method stub  
  32.          Log.i(Constants.LOG_TAG, "DataHelper.OpenHelper onCreate creating database " + DataConstants.DATABASE_NAME);  
  33.   
  34.           CategoryTable.onCreate(db);  
  35.           // populate initial categories (one way, there are several, this works ok for small data set)  
  36.           CategoryDao categoryDao = new CategoryDao(db);  
  37.           String[] categories = context.getResources().getStringArray(R.array.tmdb_categories);  
  38.           for (String cat : categories) {  
  39.              categoryDao.save(new Category(0, cat));  
  40.           }  
  41.           MovieTable.onCreate(db);  
  42.           MovieCategoryTable.onCreate(db);  
  43.     }  
  44.   
  45.     @Override  
  46.     public void onUpgrade(final SQLiteDatabase db, final int oldVersion, final int newVersion) {  
  47.         // TODO Auto-generated method stub  
  48.          Log.i(Constants.LOG_TAG, "SQLiteOpenHelper onUpgrade - oldVersion:" + oldVersion + " newVersion:"  
  49.                   + newVersion);  
  50.   
  51.         MovieCategoryTable.onUpgrade(db, oldVersion, newVersion);  
  52.         MovieTable.onUpgrade(db, oldVersion, newVersion);  
  53.         CategoryTable.onUpgrade(db, oldVersion, newVersion);  
  54.     }  
  55.   
  56. }  

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

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <!-- Used in View/Spinner1.java -->  
  4.     <string-array name="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>Fan Film</item>          
  17.         <item>Fantasy</item>          
  18.         <item>Film Noir</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>Neo Noir</item>                  
  27.         <item>Road Movie</item>  
  28.         <item>Romance</item>  
  29.         <item>Science Fiction</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:
  1. // populate initial categories (one way, there are several, this works ok for small data set)  
  2. CategoryDao categoryDao = new CategoryDao(db);  
  3. String[] categories = context.getResources().getStringArray(R.array.tmdb_categories);  
  4. for (String cat : categories) {  
  5.    categoryDao.save(new Category(0, cat));  
  6. }  
For small 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 a single 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 to create a SQLiteDatabase object. The SQLiteDatabase object is the keystone of
Android SQLite database operations. This is where we’ll create connections and perform data operations such as select, update, insert, and delete.

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


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


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

We have model objects for working with the data in our application’s Java code and table 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 our database, 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值