获取应用程序上下文返回null [英] Get application context returns null
问题描述
下面的模式已被吹捧为的方法来从我的Android应用程序在任何地方得到应用程序上下文。但有时这样做 MyApp.getContext()
返回null。我试图通过删除更改架构静态
从的getContext()
,这样我会做的MyApp .getInstance()的getContext()
。它仍然返回null。我该如何解决这个问题? 如何让我的应用程序的情况下从任何地方在我的应用程序?
公共类MyApp的扩展应用{
私有静态MyApp的实例;
公共静态的MyApp的getInstance(){
返回实例;
}
公共静态上下文的getContext(){
返回instance.getApplicationContext();
}
@覆盖
公共无效的onCreate(){
super.onCreate();
例如=这一点;
}
}
在 创建()的onCreate
的实例getApplicationContext()
( mContext
),然后调用 MyApp.getContext()
来自世界各地的在你的应用程序,你会得到你应用程序上下文静态。
公共类MyApp的扩展应用{
//私有静态MyApp的实例;
私有静态语境mContext;
公共静态的MyApp的getInstance(){
返回实例;
}
公共静态上下文的getContext(){
//返回instance.getApplicationContext();
返回mContext;
}
@覆盖
公共无效的onCreate(){
super.onCreate();
//实例=这一点;
mContext = getApplicationContext();
}
}
记住要申报到的AndroidManifest.xml
<应用机器人:名称=com.mypackage.MyApp>
...
...
...
< /用途>
The following schema has been touted as the way to get application context from anywhere within my android app. But sometimes doing MyApp.getContext()
returns null. I tried changing the schema by removing static
from getContext()
so that I would do MyApp.getInstance().getContext()
. It still returns null. How do I fix this? How do I get my application's context from anywhere within my app?
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext() {
return instance.getApplicationContext();
}
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
}
Create in onCreate()
an instance of getApplicationContext()
(mContext
) then call MyApp.getContext()
from everywhere in your app and you will get your application context statically.
public class MyApp extends Application {
//private static MyApp instance;
private static Context mContext;
public static MyApp getInstance() {
return instance;
}
public static Context getContext() {
// return instance.getApplicationContext();
return mContext;
}
@Override
public void onCreate() {
super.onCreate();
// instance = this;
mContext = getApplicationContext();
}
}
Remember to declare into your AndroidManifest.xml
<application android:name="com.mypackage.MyApp">
...
...
...
</application>
这篇关于获取应用程序上下文返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!