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
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
Related
Like many others, I'm struggling with this error:
java.lang.IllegalStateException: Fragment xyz not attached to Activity
This question offers some ideas on how to deal with this. There are no explanations to the question however, why does a Fragment detach from their Activity in the first place? Does an understanding of why this happens help me to design my app in a way to avoid this happening?
In may case I do not have some asynchronous task and call getResources() when it completes; I call getResources() in the onCreate() method of the Fragment. And sometimes, when I'm navigating my app rather fast, said error surfaces. Is it to be expected that the Fragment is not even necessarily attached to its Activity during its own onCreate() method?
Secondly, the solutions provided in the linked question (guarding getResources() with isAdded() and getActivity() != null) don't help me. There is no reasonable way to deal with getResources() not being available.
Because Android supposes that Activities may be destroyed and recreated to accommodate configuration changes. Fragments, in contrast, are not.
Is it to be expected that the Fragment is not even necessarily attached to its Activity during its own onCreate() method?
Yes, it is "expected." Bad design IMO, but expected.
I have a button that I want to change its value often, so my Activity has a private variable :
private Button p1_button = (Button)findViewById(R.id.firstbut);
This simple line makes my app crash. If I put inside the onCreate it works and I can interact with the button (change text etc).
EDIT : I think I found the reason. I should initialize AFTER setcontentview ?
EDIT: Thank you for the constructive answers. I have now a different problem I removed the initialization and I did it on onCreate and it works (But I keeped the p1_button declaration as a private field). But when I tried to modify the button in a different method of my activity (just changing the text), it crashes again. So the return value of findViewById is "local" to the method where it is called and I should setcontentview in every method that access UI elements ?
Do not call findViewById() until after you call setContentView(). Otherwise, the widget will not exist.
More generally, do not call inherited methods on Activity until after super.onCreate(), unless specifically advised to do so.
It depends where you are calling this line.
http://i.stack.imgur.com/6EQaU.png
The onCreate() method contains a call to setContentView() and before this is called, Android has no idea what to do with your button as it hasn't been inflated yet!
Therefore as a really easy rule of thumb, always make sure setContentView (or if you're dealing with fragments onCreateView()) have been called and completed. Only then will findViewById() work.
If you would like further guidance, please post some code in which the crash occurs.
edit: I tried to add the image properly but don't have enough rep.
To understand this you need to know the Activity lifecycle. You are trying to look a view which has not yet been created by Android.
As per the android lifecycle explained here "http://developer.android.com/training/basics/activity-lifecycle/starting.html". In onCreate() method the activity is created and you can access different views of the activity. If you will try to look for view before onCreate() the app will crash as it does not know whether that view exists or not.
I found a really strange behavior in the Fragment lifecycle.
After several tests on one Fragment, I realized than I got this execution order every time:
onCreateView()
onStart()
onCreateOptionsMenu()
I am really surprised because I was convinced that onStart would only be called after the execution of onCreateOptionsMenu.
FYI, I was trying to set a MenuItem as a global class variable in onCreateOptionsMenu to be able to use it in onStart. Of course I got a null pointer because of the execution order explained above.
It seems the more I dig into the Fragment's lifecycle, the more I am lost and the documentation only details the main methods, never the ones such as onCreateOptionsMenu, onPrepareOptionsMenu, onCreateContextMenu etc.
Does someone has any additional information about this, the documentation is not really helpful...
Thank you
Check this out https://github.com/xxv/android-lifecycle. There you can see a full lifecycle for both fragment and activity.
I have an Android app with TabManager. Due to change of Android API, I need to upgrade my app for Activity to contain the Fragment. To provide backward compatibility, I use ActionBarSherlock.
My App is working fine. However, looking at the Google Play Developer Console, there is always few crash reports on "java.lang.NullPointerException" on the line with getSherlockActivity(), I think only less than 0.1% out of total users are affected.
For example,
// Example 1
File file = new File(getSherlockActivity().getCacheDir(), "filename");
// Example 2
getSherlockActivity().setSupportProgressBarIndeterminateVisibility(false);
My question:
1. Should I change all the getSherlockActivity() to getActivity()? Or under certain rule, it is mandatory to use one of them?
2. What is the difference between them?
Thanks a lot.
The only difference is that with getSherlockActivity () you get the result of getActivity() but casted as a SherlockActivity. This allows to get access to the ABS specific apis.
If you just need something that is general enough to be in the Activity class, just use getActivity(). It will highlight this, otherwise highlight the fact that you use something that is ABS specific using getSherlockActivity ().
The NPE can come from :
using getActivity() (or siblings...) before onAttach has been executed
using getActivity() (or siblings...) after onDetach has been executed
So the solution is to check if your fragment is attached before using its activity :
if( isAttached() ) {
getActivity()....
}
Same topic
The NullPointerException is normally
Caution: If you need a Context object within your Fragment, you can call getActivity(). However, be careful to call getActivity() only when the fragment is attached to an activity. When the fragment is not yet attached, or was detached during the end of its lifecycle, getActivity() will return null.
This exception probably means that the code is being exectuted when the fragment is not attached to an activity.
The reference returned by getSherlockActivity() is set when the Fragment is attached, and then cleared (set to null) when the Fragment is detached. If your code tries to reference getSherlockActivity() before or after this, you would get a null-pointer.
getSherlockActivity is just a shortcut to:
(SherlockActivity) getActivity()
So in your case there is no problem to use getActivity() instead in Example 1 but in Example 2 it will not work since it is a method of SherlockActivity.
Situation
My activity waits on an Async operation and after it hears back from async operation, it needs to pass information to 2 fragments inside it.
Requirement
1. Both fragments need their onCreateView calls to be done for them to have their layouts loaded,
2. They need for themselves to be attached to their activity so that getActivity() works.
I wrote a setData() method in both the fragments and am looking for the "correct" place in the activity's lifecycle to invoke them.
onCreate() of the activity does not work, onStart() of the activity does not work and onStart() of the fragment does not work.
Nothing works, what am I missing here?
The official documentation for the Fragment lifecycle explains this clearly - please refer to it and then ask follow-up questions if something is unclear.
This Image will be helpful to understand both life cycles together.
As many people complaints and it is somewhat valid argument that this life cycle is too complicated, in Google I/O 2018,They have suggested to use Architecture component Framework. Please check this Docs
when you are at Activity2---->backpress--->Fragment2(Activity1)---means Activity1 again attach from fragment2 so on OnAactivityCreated() method Activity1 is completely loaded ....so at that we can call setData() method of your Activity1...
onAttachFragment()-activity is called before onCreate()-activity and after onAttach()-fragment
Call onDestroy on onStop of your fragment. This should call onCreate when the fragment is launched.
Let me know if works as an ideal solution for your problem.