Android:getString导致Application子类中的NPE

时间:2013-05-08 22:36:22

标签: android nullpointerexception robolectric android-context getstring

我在应用程序中遇到了一个奇怪的错误。我有一个MyApplication班级Application。在其onCreate()方法中,我初始化了一些需要存储在字符串资源文件中的API密钥的第三方库。基本上,它可以在我可以测试的设备上正常工作:Nexus S和Galaxy SIII。但我从崩溃报告系统中得到了几个条目,如果我为MyApplication.onCreate()运行Robolectric测试,我从getString()方法得到NullPointerException。

我想知道是否有人有同样的问题,可能是什么原因?

测试的日志输出(崩溃报告也引用setupAnalyticsCrashReportingAndThirdPartySdks中的同一行):

java.lang.NullPointerException
at org.robolectric.shadows.ShadowResources.getResName(ShadowResources.java:100)
at org.robolectric.shadows.ShadowResources.getString(ShadowResources.java:130)
at android.content.res.Resources.getString(Resources.java)
at org.robolectric.shadows.ShadowContext.getString(ShadowContext.java:54)
at android.content.Context.getString(Context.java)
at com.myapp.android.MyApplication.setupAnalyticsCrashReportingAndThirdPartySdks(MyApplication.java:113)
at com.myapp.android.MyApplication.onCreate(MyApplication.java:42)
at com.myapp.android.util.UtilitiesTest.setUp(UtilitiesTest.java:44)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
at org.robolectric.RobolectricTestRunner$2.evaluate(RobolectricTestRunner.java:106)
at org.junit.runners.BlockJUnit4ClassRunner.runNotIgnored(BlockJUnit4ClassRunner.java:79)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:71)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:49)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:63)

更新:代码的一小部分:

public class MyApplication extends Application

{

private static MyApplication _instance;

@Override
public void onCreate()
{
    super.onCreate();

    setupAnalyticsCrashReportingAndThirdPartySdks();
}

public MyApplication()
{
    _instance = this;
}

public static MyApplication getInstance()
{
    return _instance;
}

private void setupAnalyticsCrashReportingAndThirdPartySdks()
{
    String env = getString(R.string.environment); // Crash here
    if (env != null && env.equalsIgnoreCase("dev"))
    {
        FlurryAnalytics.setDebugMode(true);
    }
}

}

0 个答案:

没有答案