简体   繁体   中英

(Android / Java) How to give a context as argument if the class does not have activity?

I have a JSONParser class where I have this:

Database db = new Database(/* Need context here! */);

In the Database class I have this:

public Database(Context context) {
    super(context, DATABASE_NAME, null, 1);
    SQLiteDatabase db = this.getWritableDatabase();
}

How am I supposed to give a context in the Database constructor?

Thanks for any help...

Have your JSONParser class constructor take a Context parameter. In the activity/fragment where you instantiate the JSONParser, pass the context. Pass this context to the Database class. This is the clean way of doing it. You could also use the application context like @Ivan commented.

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