一尘不染

如何在Android中使用合约类?

java

我有点困惑,因为我不知道如何在这里解释该教程: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个变量不在Contract类中?还是助手类不是合同类的内部类?

希望你能帮我


阅读 189

收藏
2020-12-03

共1个答案

一尘不染

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

合同类定义用于帮助应用程序使用内容提供者的内容URI,列名,意图操作和其他功能的常量。提供商不自动包含合同类别;提供者的开发人员必须定义它们,然后将其提供给其他开发人员。

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

我喜欢将合同类视为数据库架构,或者换句话说,它定义了数据库的设置方式。您可能会注意到,合同类中的所有内容都声明为静态的。这是因为您将永远不会实例化Contract类,而仅引用其中定义的常量。您可以在我的示例中看到,我的Contract类仅声明了一堆静态最终变量。该Contract类可以是其自己的文件,例如,我的文件称为TransitContract.java。

举例来说,您想更改其中一列的名称。您无需更改多个文件,只需更改合同类中列的值即可。您不在合约类内部进行任何类型的计算工作。

另一方面,SQLLiteOpenhelper类是Google提供的,以简化数据库的使用。在这里,您可以实现创建和设置初始数据库的方法。请参阅http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html。在实现这些方法之后,您要做的就是实例化您的助手类的实例,然后调用helperClassInstance.getWriteableDatabase()(或getReadableDataBase()),然后您的助手类会在必要时自动处理创建新数据库的工作,或返回已经存在的那个,等等。

该帮助程序通常实现为内部类,但也可以是其自己的独立类。但是,您要实现它。

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

这是使用您的代码的示例。 我实际上没有测试此代码,因此可能会有错误。如您所见,您可以在您认为必要的任何地方实例化db
helper。在此示例中,我在主要活动的onCreate中进行了此操作,但实际上,这是不好的做法。

数据库合同

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
        };
    }
2020-12-03