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