简体   繁体   English

(Android / Java)如果类没有活动,如何给上下文提供参数?

[英](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.

相关问题 如何将活动上下文放入非活动类android? - How to get activity context into a non-activity class android? Android-如何从Java类传递另一个活动应用程序上下文将片段扩展到asynctask? - Android - How to pass another activity application context from java class extends fragments to asynctask? 如何给一个论证课 <?> 上课 - How to give an argument Class<?> to Class<A> XML 文件是否也有其上下文或只有活动在 android 开发中具有 - Does XML files also have its context or does only activity have in android development 此Java策略模式是否具有冗余的Context类? - Does this Java Strategy pattern have a redundant Context class? 如何在没有上下文的android Holder类中使用Font Awesome? - How to use Font Awesome in android Holder class which does not have a context? 如何将(Android)应用程序上下文传递给Java类? - How to pass (Android) application context to a Java class? android / java有定时器类吗? - Does android/java have a timer class? 为什么用Java代码创建的Android Button()必须使用(this)作为上下文? - Why does an Android Button() created in the java code have to use (this) as the context? Android上一个Activity是否可以有多个Java类? - Is it possible to have more than one java class for one Activity on android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM