【问题标题】:Why is Context "becoming" null on Application class?为什么应用程序类上的上下文“变为”空?
【发布时间】:2013-02-06 17:15:15
【问题描述】:

应用程序使用问题

我正在重写一个应用程序(第一个“版本”在分析方面几乎什么都没有,最终导致一堆我想摆脱的问题)并且我正在努力解决一个问题在第一个版本中从未出现过。

事情是:我有一个地理数据类。它只提供字符串数组,我可以将它们塞进微调器适配器中。由于我使用了 values xml 文件,因此该类需要访问 Context 以获取适当的资源。

由于我在应用程序的几个点中使用了这个地理数据,我认为我可以创建一个类来扩展应用程序,并在 onCreate 中实例化地理类,我认为只加载一次并使用它会更有效我想要多少次。这适用于我的第一个版本:

这是 MyApplication 类

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我检查过,结果发现我提供的上下文是空的......而且我不明白为什么或我做错了什么

【问题讨论】:

  • 尝试上下文 = getApplicationContext();或者将活动类本身的实例传递给 GeographyClass。
  • 而不是 MyApplication.context = getApplicationContext(); 输入如下内容:MyApplication.context = this;

标签: android nullpointerexception android-context


【解决方案1】:

好的,我解决了(我发誓我已经对此发表了评论,但既然它已经消失了......)。 问题是,我不习惯使用 Application 类,我忘记在 Manifest 文件中声明 MyApplication。菜鸟错误。我一宣布,应用就运行正常

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 1970-01-01
    • 1970-01-01
    • 2023-02-26
    • 1970-01-01
    • 2011-12-11
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多