应用程序使用问题
我正在重写一个应用程序(第一个“版本”在分析方面几乎没有,它最终堆积了一堆我想摆脱的问题)并且我遇到了一个问题在第一个版本中从未出现过。
事情是:我有一个地理数据类。它只提供字符串数组,我可以将其放入微调器适配器中。由于我使用了一个值 xml 文件,该类需要访问 Context 才能获得适当的资源。
因为我在应用程序的几个点使用了这个地理数据,我想我可以创建一个类来扩展应用程序,并在 onCreate 中实例化地理类,我认为只加载一次并使用它会更有效率它多次我想要的。这适用于我的第一个版本:
这是我的应用程序类
private static Context context;
public void onCreate(){
super.onCreate();
MyApplication.context = getApplicationContext();
geografiaEspana = GeographyClass.getInstance(context);
}
public static GeographyClass getGeografiaEspana() {
if(ctx==null){
Log.w("TAPABOOK", "Tapabook.context nulo");
}
if (geografiaEspana==null){
Log.w("TAPABOOK", "Tapabook.geografiaEspana nula, instanciando");
geografiaEspana = GeographyClass.getInstance(ctx);
}
Log.i("TAPABOOK", "Tapabook.geografiaEspana instanciada");
return geografiaEspana;
}
这是我的地理类
private static GeographyClass instance = null;
public static GeographySpain getInstance(Context context){
if(instance== null){
instance = new GeographySpain(context);
}
return instance;
}
public GeographySpain(Context context){
Resources res = context.getResources();
// load resources data
}
正如我所说,这在我的第一个版本中有效。但是,在我的新版本中,我在“Resources res = context.getResources();”这一行收到 NullPointerException。我已经检查过,事实证明我提供的上下文是空的......而且我不明白为什么或我做错了什么
最佳答案
好的,我解决了它(我发誓我已经对此发表了评论,但既然它不见了......)。 问题是,我不习惯使用 Application 类,而且我忘记在 Manifest 文件中声明 MyApplication 。菜鸟错误。我一声明它,应用程序就运行正常了
关于android - 为什么 Application 类上的 Context "becoming"为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15001276/