无法从数据库获取上下文和访问模式

时间:2016-07-23 03:40:31

标签: java android android-sqlite android-database

我正在按照Android developers教程设置数据库,但我遇到了问题。这是我的架构文件:

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()函数不起作用,我收到错误:

  

无法解决方法getContext

我试过这样做:

ContactsDBSchema.ContactsDBhelper contactsHelper = new ContactsDBSchema.ContactsDBhelper(this)

ContactsDBSchema.ContactsDBhelper contactsHelper = new ContactsDBSchema.ContactsDBhelper(getApplicationContext())

我仍然没有运气。关于如何解决这个问题的任何建议?

1 个答案:

答案 0 :(得分:0)

从项目的任何位置访问应用程序上下文的最简单方法是在Application子类中定义一个方法,如下所示:

public class MyApplication extends Application{
   private static Context context;

   @Override
   public void onCreate(){

      super.onCreate();

      MyApplication.context = getApplicationContext();


   }

   public static Context getAppContext(){
      return MyApplication.context;
   }
}

注意

如果您尚未在项目中扩展Application类,则可以这样做,但请记住在AndroidManifest中将应用程序的名称设置为您在上面创建的子类({{1 }})。

从这里开始,我们肯定可以随时随地访问上下文!

MyApplication

祝你好运,我希望这能帮到你!