简体   繁体   中英

getInstance(this) not working on a class without activity

here is my class, I want to call a method from DatabaseAccess class:

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:

private DatabaseAccess(Context context) {
    this.openHelper = new DatabaseOpenHelper(context);
}

It doesn't accept "this" as a context

how to fix this?

It's because this must refer to object being of Context class or its child. Activity is subclass of Context your other classes are not. 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.

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. You can fix this by calling the method with the field context you've declared above:

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 :

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM