从父活动调用Fragment方法会产生NullPointerException吗?

时间:2017-02-13 11:22:02

标签: java android nullpointerexception

当应用程序关闭时,我从MainActivity的onCreate()onClick of Notification调用了fragment方法。但它给NullPointerException()说,

Attempt to invoke virtual method 'OneFragment.refreshMaterial(int, int, int, int)' on a null object reference '

我从MainActivity调用了fragment方法,如下所示,

OneFragment fragment = (OneFragment)getSupportFragmentManager().findFragmentById(R.id.container_body);
fragment.refreshMaterial();

1 个答案:

答案 0 :(得分:0)

您需要检查您的片段是否为空并且在使用之前是否可见

OneFragment fragment = (OneFragment)getSupportFragmentManager().findFragmentById(R.id.container_body);

if(fragment != null && fragment.isVisible())
      fragment.refreshMaterial();