我正在 android 中编写一个内容提供程序。我想编写查询实现。我正在 contentProvider 的查询函数中创建一个 DbHelper 对象。但是当我创建这个时,我收到错误,即我无法访问此内容提供程序类中的 MainActivity.this 。我需要 MainActivity.this 以便我可以初始化 DbHelper 并使用我在 DbHelper 类中已实现的函数查询。我该如何解决这个问题?
代码:
public class CourseContentProvider extends ContentProvider {
@Override
public Cursor query(Uri arg0, String[] arg1, String arg2, String[] arg3,
String arg4) {
// TODO Auto-generated method stub
if (sURIMatcher.match(arg0)==COURSE) {
MyDbHelper obj = new MyDbHelper(MainActivity.this);//Error msg here: No enclosing instance of the type MainActivity is accessible in scope
}
return null;
}
//other auto generated functions
}
谢谢。
最佳答案
要获取Context
,只需在扩展ContentProvider
的类中调用getContext()
示例:
@Override
public boolean onCreate() {
Context context = getContext();
DBHelper = new DatabaseHelper(context);
db = DBHelper.getWritableDatabase();
return (db == null) ? false : true;
}
关于java - 如何在 android 中的 contentProvider 类中获取 mainactivity.this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22543757/