简体   繁体   English

如何将上下文从活动传递到活动?

[英]How to pass context from activity to activity?

I have a main activity, and it summons another activity to display some data. 我有一个主要的活动,它召唤另一个活动来显示一些数据。

I have a private database helper object that I use throughout the main activity code. 我有一个私有数据库助手对象,我在整个主要活动代码中使用。 Is there a way to pass the context of my main activity to my sub activity in an elegant way? 有没有办法以优雅的方式将我的主要活动的上下文传递给我的子活动? (ie, from subclass, something like getCallingActivityContext() ) (即,从子类,类似于getCallingActivityContext()

I could always create new database helper objects. 我总是可以创建新的数据库帮助程序对象。

Extending the Application class helps you to allow declare/access global variables. 扩展Application类可帮助您允许声明/访问全局变量。 You can set your variables from any activity to ApplicationContext and access it from other activity without using bundle. 您可以将变量从任何活动设置为ApplicationContext ,并在不使用bundle的情况下从其他活动访问它。

How to declare global variables in Android? 如何在Android中声明全局变量? will help you. 会帮助你。

For your case, I would recommend you to extend instead the Application class . 对于您的情况,我建议您扩展Application类 All your activities have access to the Application context by calling getApplicationContext() at any time. 您的所有活动都可以通过随时调用getApplicationContext()来访问Application上下文。 Check here the 1st answer for an example. 在这里查看第一个答案的例子。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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