getResources()从静态方法,没有上下文 [英] getResources() from static method, without context
问题描述
我工作的一个 SQLiteOpenHelper
从中我会读通过数据库静态方法(因为数据库反正共享)。是否有可能获得应用上下文是这样的:
I'm working on a SQLiteOpenHelper
from which I'll read databases via static methods (since the databases are shared anyway). Is it possible to get the application context to something like:
public static final Context context = XXX;
应该可以吧?由于我明明只有从目前的应用程序,并调用资源和数据库的应用程序内共享。
It should be possible right? Since I'm obviously only calling from the current app and both resources and databases are shared inside the app.
需要明确的是:我想要访问的资源和 SQLiteDatabases
(如果我碰巧是错的有关上下文的方法)
To be clear: I want to access Resources and the SQLiteDatabases
(if I happen to be wrong about the context approach).
是否有可能实现?
编辑:
是否有可能从内像这样获得上下文(没有传递给它作为一个参数)
Is it possible to get the context from inside something like this (without passing it as a parameter)
public class foo{
foo(){
XXX.getResources();
}
}
EDIT2:
试图@britzl:拳头想法
Trying @britzl:s fist idea
public class SpendoBase extends Application{
private static Context context;
public SpendoBase(){
System.out.println("SPENDOBASE: " + this);
System.out.println("SPENDOBASE: " + this.getBaseContext());
}
public static Context getContext(){
return this.context;
}
}
我如何获得上下文的持有?无论是在构造函数或形成的getContext();
诗的 getBaseContext()
返回null,而 getApplicationContext
thows一个 NullPointerException异常
。
Ps the getBaseContext()
returns null, and getApplicationContext
thows a nullPointerException
.
推荐答案
我看到你的问题,有三种可能的解决方案:
I see three possible solutions to your problem:
-
创建自己的应用程序的子类,并设置在清单文件的应用程序类。在子类中,你可以有一个静态getInstance()方法,将您提供从应用程序中的任何位置的应用程序上下文(从而参考资料)。例如:
Create your own subclass of Application and set that as your application class in the manifest file. In your subclass you could have a static getInstance() method that would provide you with the application context (and thus Resources) from anywhere within your application. Example:
public class BaseApplication extends Application {
private static BaseApplication instance;
public BaseApplication() {
super();
instance = this;
}
public static BaseApplication getInstance() {
return instance;
}
}
和在AndroidManifest.xml:
And in AndroidManifest.xml:
<application android:name="com.example.BaseApplication" ...>
...activities
</application>
传递一个上下文你在SQLiteOpenHelper拨打任何电话
Pass a context to any calls you make in your SQLiteOpenHelper
使用注入的资源比如依赖注入
Inject the Resources instance using dependency injection
这篇关于getResources()从静态方法,没有上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!