从另一个 class 访问 class 个私有成员

Accessing class private members from another class

我是编程新手,我从 Java 和 Android 开始。我想创建一个数据库,所以我遵循了官方文档:https://developer.android.com/training/basics/data-storage/databases.html

当合同 class 上创建和维护数据库的成员是私有字符串(SQL_CREATE_ENTRIES 和 SQL_DELETE_ENTRIES)时,我的问题就来了。在另一个文件上定义 DBHelper class,我无法按照它在文档中出现的方式访问该成员(FeedReaderDbHelper class 只是像在其范围内一样使用它们)。所以 Android Studio 只是把句子放在红色上并说:'Cannot resolve symbol'.

我应该在这里做什么?我也阅读了 setters/getters 不推荐用于 Android 的文档。

SQL_CREATE_ENTRIESSQL_DELETE_ENTRIES 放入 DBHelper class。

来自文档,

"A contract class is a container for constants that define names for URIs, tables, and columns."

只有数据库的模式应该放在那里。与更改数据库有关的逻辑应放在 DBHelper class.

on the Contract class, the members to create and maintain the database are private strings (SQL_CREATE_ENTRIES and SQL_DELETE_ENTRIES). Defining the DBHelper class on another file, I just cannot access that members the way it appears on the documentation (the FeedReaderDbHelper class just use them as if they were inside it scope)

那些 private 字段应该放在 SQLiteOpenHelper class 中。它们在 class 的范围内用于创建和删除由 class 管理的 table。您不应该在其他地方使用那些 SQL 字符串。

例如,

public class FeedReaderDbHelper extends SQLiteOpenHelper {

    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    private static final String SQL_CREATE_ENTRIES =
        "CREATE TABLE " + FeedEntry.TABLE_NAME + " (" +
        FeedEntry._ID + " INTEGER PRIMARY KEY," +
        FeedEntry.COLUMN_NAME_ENTRY_ID + TEXT_TYPE + COMMA_SEP +
        FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
        ... // Any other options for the CREATE command
        " )";

    private static final String SQL_DELETE_ENTRIES =
        "DROP TABLE IF EXISTS " + FeedEntry.TABLE_NAME;

    // 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 = "FeedReader.db";

    public FeedReaderDbHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // This database is only a cache for online data, so its upgrade policy is
        // to simply to discard the data and start over
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    /* Inner class that defines the table contents */
    public static abstract class FeedEntry implements BaseColumns {
        public static final String TABLE_NAME = "entry";
        public static final String COLUMN_NAME_ENTRY_ID = "entryid";
        public static final String COLUMN_NAME_TITLE = "title";
        public static final String COLUMN_NAME_SUBTITLE = "subtitle";
        ...
    }

}