1
我在按照Android developers教程设置数据库,但我遇到了问题。这是我的schema文件:无法从数据库获取上下文和访问架构
public final class ContactsDBSchema {
public ContactsDBSchema(){};
public static abstract class ContactsEntry implements BaseColumns
{
public static final String TABLE_NAME = "contacts";
public static final String COLUMN_CONTACT__ID = "contact_id";
public static final String COLUMN_CONTACT__NAME = "contact_name";
public static final String COLUMN_CONTACT__PHONE = "contact_phone";
}
public class ContactsDBhelper extends SQLiteOpenHelper
{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "contacts.db";
public String SQL_CREATE_ENTRIES = "create table" + ContactsEntry.TABLE_NAME + ContactsEntry.COLUMN_CONTACT__ID +"INTEGER PRIMARY KEY AUTOINCREMENT," + ContactsEntry.COLUMN_CONTACT__NAME + "TEXT," + ContactsEntry.COLUMN_CONTACT__PHONE + "TEX";
public String SQL_DELETE_ENTRIES = "DROP TABLE IF EXISTS" + ContactsEntry.TABLE_NAME ;
public ContactsDBhelper(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) {
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onUpgrade(db, oldVersion, newVersion);
}
}
}
现在的问题是,当我试图从另一个类访问它像这样的:
public class ContactsDBprocess {
ContactsDBSchema.ContactsDBhelper contactsHelper = new ContactsDBSchema.ContactsDBhelper(getContext());
}
我无法正常访问辅助类。该getContext()
功能不工作,我得到一个错误:
Cannot resolve method
getContext
我试着这样做:
ContactsDBSchema.ContactsDBhelper contactsHelper = new ContactsDBSchema.ContactsDBhelper(this)
ContactsDBSchema.ContactsDBhelper contactsHelper = new ContactsDBSchema.ContactsDBhelper(getApplicationContext())
我仍然没有任何运气。有关如何解决此问题的任何建议?
你想在哪个类实例化ContactsDBhelper?你需要传递一个有效的'Context'作为构造函数参数。 – earthw0rmjim
您的'ContactDBProcess'类需要在具有'getContext()'的类中定义,或者需要扩展此类。或者你可以传递一个有效的'context'到它的构造函数中,然后使用该变量而不是'getContext()'。 – Shaishav