[英](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: 我有一个JSONParser类,其中有:
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. 让您的JSONParser类构造函数接受Context参数。 In the activity/fragment where you instantiate the JSONParser, pass the context.
在实例化JSONParser的活动/片段中,传递上下文。 Pass this context to the Database class.
将此上下文传递给Database类。 This is the clean way of doing it.
这是干净的方法。 You could also use the application context like @Ivan commented.
您也可以使用应用程序上下文,例如@Ivan注释。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.