android sliding menu getActivity returns null

2019-09-09 15:10发布

I've been searching for this for a while now and haven't found any solution so far,

so I have a sliding menu, and withing it I call getActivity(), so far so good, but when I get out of the app (home button) and come back in a few minutes, the getActivity() returns nullpointerexception

if anyone has a clue about this it would be much appreciated

thanks

1条回答
一夜七次
2楼-- · 2019-09-09 15:44

You have to be careful about exactly when you call getActivity(). It will return null in any call triggered by the parent activity's lifecycle all the way through onResume(). You have to make sure it is already attached to the parent activity before you can safely call it. Take a look at

http://developer.android.com/reference/android/support/v4/app/FragmentActivity.html#onResumeFragments()

Perhaps it will help you resolve your problem.

Depending on what you're trying to do, I would look into saving a pointer to the activity in the fragment so it can be referenced at times when getActivity might be null. That said, this could be kinda dangerous so be careful if that is the route you choose to take

查看更多
登录 后发表回答