[英]getInstance(this) not working on a class without activity
here is my class, I want to call a method from DatabaseAccess class: 这是我的课程,我想从DatabaseAccess类调用方法:
public class CardAdapter extends RecyclerView.Adapter<CardAdapter.ViewHolder> {
List<Person> mItems;
public Context context;
private static SQLiteDatabase database;
private SQLiteOpenHelper openHelper;
public CardAdapter() {
super();
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
databaseAccess.open();
List<String> kandidatet = DatabaseAccess.getKandidatet();
database.close();
Person p;
mItems = new ArrayList<>();
for (int i = 0; i < kandidatet.size(); i++) {
p = new Person();
p.setName(kandidatet.get(i));
mItems.add(p);
}
.....
....
...
}
the error is in this row: 错误在此行中:
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(this);
here is the method in the class DatabaseAccess: 这是类DatabaseAccess中的方法:
private DatabaseAccess(Context context) {
this.openHelper = new DatabaseOpenHelper(context);
}
It doesn't accept "this" as a context 它不接受“ this”作为上下文
how to fix this? 如何解决这个问题?
It's because this
must refer to object being of Context
class or its child. 因为
this
必须引用Context
类或其子对象。 Activity
is subclass of Context
your other classes are not. Activity
是Context
的子类,而其他类则不是。 To work around this you can pass context to the adapter object upon its creation: 要解决此问题,您可以在创建适配器对象时将上下文传递给它:
public CardAdapter(Context context) {
...
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(context);
this
refers to the class you're currently in. You must call this
from an activity if you want it to be a valid context
since activity implements Context
interface. this
指的是你目前所在的班级。你必须调用this
,如果你希望它是一个有效的从活动context
,因为活动实现了Context
接口。
Since you're calling it from a class which does not extend Activity
, surely you get an error since this
is not a Context
in that case. 因为您是从不扩展
Activity
的类中调用它的,所以肯定会收到错误,因为在这种情况下this
不是Context
。 You can fix this by calling the method with the field context
you've declared above: 您可以通过在上面声明的字段
context
调用方法来解决此问题:
DatabaseAccess databaseAccess = DatabaseAccess.getInstance(context);
Before you do that, you'll need to initialize this field with a proper context, which you can do by changing the constructor to accept the Context
: 在执行此操作之前,您需要使用适当的上下文初始化此字段,可以通过更改构造函数以接受
Context
:
public CardAdapter(Context ctx){
context = ctx;
//the rest of the code.
Be aware that now you also need to change the call of the constructor to new CardAdapter(this)
if you're calling it from the activity (or getActivity
if you're calling it from a Fragment). 请注意,如果您从活动中调用构造函数,则现在还需要将其构造函数的调用更改为
new CardAdapter(this)
(如果从Fragment中调用,则将其更改为getActivity
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.