gpt4 book ai didi

android - 即使对象不为空,也出现空指针异常

转载 作者:行者123 更新时间:2023-11-29 14:45:52 25 4
gpt4 key购买 nike

我遇到了一个有点奇怪的问题。我正在尝试从资源中获取字符串,我有一个非 activity class,我在其中获取 context,如下所示:

App app= App.getInstance();
if (app != null) {
return app.getResources().getString(R.string.overview);
}

调试时控件进入 if 语句,这意味着 app 不为空。

应用类:

public class App extends Application {

private static App app = new App ();

private App () {

}

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

public static App getInstance() {
if (app == null) {
app = new App ();
}
return app;
}
}

一切似乎都很好,但是当我运行它时出现空指针异常:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
at android.content.ContextWrapper.getResources(ContextWrapper.java:87)
at com.emanager.ui.adapters.HomePagerAdapter.getPageTitle(HomePagerAdapter.java:45)
at android.support.design.widget.TabLayout.populateFromPagerAdapter(TabLayout.java:773)
at android.support.design.widget.TabLayout.setPagerAdapter(TabLayout.java:764)
at android.support.design.widget.TabLayout.setupWithViewPager(TabLayout.java:716)
at com.emanager.ui.activities.HomeActivity.onCreate(HomeActivity.java:65)
at android.app.Activity.performCreate(Activity.java:6237)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1107)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2369)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476) 
at android.app.ActivityThread.-wrap11(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 

我试过其他一些方法,但似乎没有解决它。

如何修复此异常?

最佳答案

您不应该自己创建应用程序,它会在您的应用程序运行后在 Activity 开始之前创建。

试试这个:

public class App extends Application {

private static App app;

@Override
public void onCreate() {
super.onCreate();
app = this;
}

public static App getInstance() {
return app;
}
}

关于android - 即使对象不为空,也出现空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38288005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com