[英]getActivity null in fragment when app resumes
So if the user is on my app and they click home and go to several other apps and then come back, then the activity will be recreated and getActivity
will be null when I call on it in my fragment. 因此,如果用户在我的应用程序上,然后单击主页并转到其他几个应用程序,然后再返回,则将重新创建该活动,并且当我在片段中对其进行调用时,
getActivity
将为null。
A solution I found was to create a static variable and store getActivity
in the onCreateView
. 我发现的一个解决方案是创建一个静态变量并将
getActivity
存储在onCreateView
。
I feel like this isn't a good solution. 我觉得这不是一个好的解决方案。 Is there any other way that I can go about this?
我还有其他方法可以解决这个问题吗?
I tried using a non static variable and storing it in OncreateView and onAttach, but getActivity will be null. 我尝试使用非静态变量并将其存储在OncreateView和onAttach中,但getActivity将为null。
Here is the error I will get when I use getActivity
if I don't save it as a static variable. 如果不将其保存为静态变量,这就是使用
getActivity
时出现的错误。 I use it in my AsyncTask
for ProcessDialog in my Fragment. 我在Fragment的ProcessDialog的
AsyncTask
使用它。
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources$Theme android.content.Context.getTheme()' on a null object reference
Thanks. 谢谢。
If you are sure that onAttach(Activity activity)
also has null, then I suspect you have multiple instance of same fragment at the same time. 如果您确定
onAttach(Activity activity)
也为null,那么我怀疑您同时有多个相同片段的实例。 Print the fragment instance in onResume and check the instances. 在onResume中打印片段实例并检查实例。
Are you implementing the method onActivityCreated ? 您是否正在实现onActivityCreated方法? You should use getActivity inside this method.
您应该在此方法内使用getActivity。
Another workaround would be use onAttach to keep your Activity. 另一个解决方法是使用onAttach来保持您的活动。
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mActivity = activity;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.