当前位置: 移动技术网 > IT编程>开发语言>Java > 遇到Attempt to invoke virtual method ‘java.lang.Object android.content.Context.的解决方案

遇到Attempt to invoke virtual method ‘java.lang.Object android.content.Context.的解决方案

2020年09月27日  | 移动技术网IT编程  | 我要评论
java.lang.NullPointerException:Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference今天遇到一个问题 ,在Fragment中使用Recyclerview设置空布局的时候出现如上问题:View view = LayoutInflater.fro.

今天遇到一个问题 ,在Fragment中使用Recyclerview设置空布局的时候,

View view = LayoutInflater.from(getContext()).inflate(R.layout.item_today_plan_container, null);

出现如上问题:

java.lang.NullPointerException:

Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference

遇到该问题的原因是:返回的是一个fragment,而该fragment位于另一个fragment中,则返回该fragment后可能会出现获取不到getActivity和getContent的情况,您将执行导致加个判断就行了

问题解决:可以使用getActivity(),它返回与fragment关联的活动,需要判断当前getActivity是否为空

if (getActivity() != null) {

     // Code goes here.

}

本文地址:https://blog.csdn.net/ZytheMoon/article/details/108838023

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网