如何在android中使用契约类?

我有点困惑,因为我不知道如何解释这个教程在这里: http : //developer.android.com/training/basics/data-storage/databases.html#DbHelper

我的代码直到现在看起来像这样:

public final class DatabaseContract { // To prevent someone from accidentally instantiating the contract class, // give it an empty constructor. public DatabaseContract() {} public static abstract class Table1 implements BaseColumns { public static final String TABLE_NAME = "nameOfTable"; public static final String COLUMN_NAME_COL1 = "column1"; public static final String COLUMN_NAME_COL2 = "column2"; public static final String COLUMN_NAME_COL3 = "column3"; } public class DatabaseHelper extends SQLiteOpenHelper { // If you change the database schema, you must increment the database version. public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "database.db"; private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; private static final String SQL_CREATE_ENTRIES = "CREATE TABLE " + Table1.TABLE_NAME + " (" + Table1._ID + " INTEGER PRIMARY KEY," + Table1.COLUMN_NAME_COL1 + TEXT_TYPE + COMMA_SEP + Table1.COLUMN_NAME_COL2 + TEXT_TYPE + COMMA_SEP + Table1.COLUMN_NAME_COL3 + TEXT_TYPE + COMMA_SEP + " )"; private static final String SQL_DELETE_ALL_ENTRIES = "DROP TABLE IF EXISTS " + Table1.TABLE_NAME; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Method is called during creation of the database @Override public void onCreate(SQLiteDatabase db) { db.execSQL(SQL_CREATE_ENTRIES); } // Method is called during an upgrade of the database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(DatabaseHelper.class.getName(), "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL(SQL_DELETE_ALL_ENTRIES); onCreate(db); } } } 

我是否正确地解释了它,还是把Helper类中的前6个variables放在合同类之外? 还是应该帮助者类不是合同类的内部类?

希望你能帮我

Related of "如何在android中使用契约类?"

您的合同基本上定义了您的数据库,以及人们应该如何通过内容提供者与之交互。

契约类定义了可帮助应用程序处理内容URI,列名,意向动作和内容提供者的其他特征的常量。 合同类别不会自动包含在提供者中; 提供者的开发人员必须定义它们,然后将其提供给其他开发人员。

话虽如此,你不一定需要一个内容提供者来使用合同类。 我的例子包含内容提供者使用的常量(MIME和URI部分)。 如果您不使用内容提供程序,则不需要这些部分。

我喜欢把契约类看作数据库模式,或者换句话说就是定义数据库设置的方式。 您可能会注意到,合同类中的所有内容都被声明为静态的。 那是因为你永远不会实例化一个Contract类,而只能引用其中定义的常量。 你可以在我的例子中看到我的Contract类只是声明了一堆静态的最终variables。 这个Contract类可以是它自己的文件,例如我的文件叫做TransitContract.java。

比方说,你想改变你的一列的名字。 而不是对多个文件进行更改,您只需更改合同类中列的值即可。 你没有在合同类中做任何计算工作。

另一方面,SQLLiteOpenhelper类是Google提供的用于处理数据库的简单方法。 这是您实现创build和设置初始数据库的方法的地方。 请参阅http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html 。 在你实现这些方法之后,你所要做的就是实例化一个你的helper类的实例,然后调用helperClassInstance.getWriteableDatabase()(或者getReadableDataBase()),然后你的helper类会自动处理创build一个新的数据库,或者返回已经存在的那个等等

这个助手通常作为一个内部类来实现,但可以是它自己的独立类。 但是,你想要实现它。

我强烈build议您查看Google提供的记事本示例,因为它有一个很好的示例,说明如何设置合同类。 请注意,他们也使用内容提供者。 如果您有兴趣了解内容提供商,我build议您阅读http://developer.android.com/guide/topics/providers/content-provider-basics.html 内容提供者和合同类进一步深入。

这是一个使用你的代码的例子。 我没有真正testing这个代码,所以它可能有错误。 正如你所看到的,你可以在你认为有必要的地方实例化你的db helper。 在这个例子中,我在主要活动的onCreate中做了这个,但实际上这是不好的做法。

DatabaseContract.java

 public final class DatabaseContract { public static final int DATABASE_VERSION = 1; public static final String DATABASE_NAME = "database.db"; private static final String TEXT_TYPE = " TEXT"; private static final String COMMA_SEP = ","; // To prevent someone from accidentally instantiating the contract class, // give it an empty constructor. private DatabaseContract() {} public static abstract class Table1 implements BaseColumns { public static final String TABLE_NAME = "nameOfTable"; public static final String COLUMN_NAME_COL1 = "column1"; public static final String COLUMN_NAME_COL2 = "column2"; public static final String COLUMN_NAME_COL3 = "column3"; public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + COLUMN_NAME_COL1 + TEXT_TYPE + COMMA_SEP + COLUMN_NAME_COL2 + TEXT_TYPE + COMMA_SEP + COLUMN_NAME_COL3 + TEXT_TYPE + " )"; public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME; } } 

DatabaseHelper.java

 public class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DatabaseContract.DATABASE_NAME, null, DatabaseContract.DATABASE_VERSION); } // Method is called during creation of the database @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DatabaseContract.Table1.CREATE_TABLE); } // Method is called during an upgrade of the database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL(DatabaseContract.Table1.DELETE_TABLE); onCreate(db); } } 

MainActivity.java

 public class MainActivity extends Activity { public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Create new helper DatabaseHelper dbHelper = new DatabaseHelper(getContext()); // Get the database. If it does not exist, this is where it will // also be created. SQLiteDatabase db = dbHelper.getWriteableDatabase(); // Create insert entries ContentValues values = new ContentValues(); values.put(DatabaseContract.Table1.COLUMN_NAME_COL1, "value1"); values.put(DatabaseContract.Table1.COLUMN_NAME_COL2, "value2"); values.put(DatabaseContract.Table1.COLUMN_NAME_COL3, "value3"); // Insert the new row, returning the primary key value of the new row long newRowId; newRowId = db.insert( DatabaseContract.Table1.TABLE_NAME, null, values); } } 

和我的例子

 public final class TransitContract { public static final String AUTHORITY = "com.example.TransitProvider"; public static final String SCHEME = "content://"; public static final String SLASH = "/"; public static final String DATABASE_NAME = "transit.db"; /* An array list of all the SQL create table statements */ public static final String[] SQL_CREATE_TABLE_ARRAY = { Agency.CREATE_TABLE, CalendarDates.CREATE_TABLE, Calendar.CREATE_TABLE, Routes.CREATE_TABLE, Shapes.CREATE_TABLE, Stops.CREATE_TABLE, StopTimes.CREATE_TABLE, Trips.CREATE_TABLE }; /** * Array of resource ids for each GTFS data file that will be loaded into * database */ public static final int[] RAW_IDS = { R.raw.agency, R.raw.calendar_dates, R.raw.calendar, R.raw.routes, R.raw.shapes, R.raw.stops, R.raw.stop_times, R.raw.trips, }; /* Do not allow this class to be instantiated */ private TransitContract() {} public static final class Agency implements BaseColumns { /* Do not allow this class to be instantiated */ private Agency() {} public static final String TABLE_NAME = "Agency"; public static final String KEY_AGENCY_ID = "AgencyId"; public static final String KEY_NAME = "Name"; public static final String KEY_URL = "Url"; public static final String KEY_TIMEZONE = "Timezone"; public static final String KEY_LANG = "Language"; public static final String KEY_PHONE = "PhoneNumber"; public static final String KEY_FARE_URL = "FareUrl"; /* * URI definitions */ /** * The content style URI */ public static final Uri CONTENT_URI = Uri.parse(SCHEME + AUTHORITY + SLASH + TABLE_NAME); /** * The content URI base for a single row. An ID must be appended. */ public static final Uri CONTENT_ID_URI_BASE = Uri.parse(SCHEME + AUTHORITY + SLASH + TABLE_NAME + SLASH); /** * The default sort order for this table */ public static final String DEFAULT_SORT_ORDER = KEY_AGENCY_ID + " ASC"; /* * MIME type definitions */ /** * The MIME type of {@link #CONTENT_URI} providing rows */ public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE + "/vnd.com.marylandtransitcommuters.agency"; /** * The MIME type of a {@link #CONTENT_URI} single row */ public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE + "/vnd.com.marylandtransitcommuters.agency"; /** * SQL Statement to create the routes table */ public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" + _ID + " INTEGER PRIMARY KEY," + KEY_AGENCY_ID + " TEXT," + KEY_NAME + " TEXT," + KEY_URL + " TEXT," + KEY_TIMEZONE + " TEXT," + KEY_LANG + " TEXT," + KEY_PHONE + " TEXT," + KEY_FARE_URL + " TEXT" + ");"; /** * SQL statement to delete the table */ public static final String DELETE_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME; /** * Array of all the columns. Makes for cleaner code */ public static final String[] KEY_ARRAY = { KEY_AGENCY_ID, KEY_NAME, KEY_URL, KEY_TIMEZONE, KEY_LANG, KEY_PHONE, KEY_FARE_URL }; }