Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible for an Activity to get Garbage Collected and not a child Fragment?

This call, which occurs in a Fragment, occasionally crashes due to a NullPointerException, especially when the app is not running in the foreground:

getActivity().getApplication());

This call occurs when feedback comes back from the server or when there's a need to redraw the fragment. I'm not sure why that call would throw a NPE, can the fragment remain in memory while the Activity gets GCed?

If it makes a difference, I'm using a SwipeyTab ViewPager to display different fragments.

like image 526
StackOverflowed Avatar asked Jun 17 '12 11:06

StackOverflowed


People also ask

How do I make sure an object is not garbage collected?

We have three ways to achieve same - 1) Increasing the Heap -Eden space size . 2) Create Singleton class with Static reference . 3) Override finalize() method and never let that object dereference. Save this answer.

Is fragment the child of an activity?

A Fragment is not an Activity. Fragments are hosted inside a FragmentActivity.

When and how does an object memory get freed by garbage collector?

The garbage collector will free the memory after you "destroy" the reference. i. 3 Setting the object reference to null.

What happens to fragment when activity is destroyed?

A paused Fragment is still alive (all state and member information is retained by the system), but it will be destroyed if the Activity is destroyed. If the user presses the Back button and the Fragment is returned from the back stack, the lifecycle resumes with the onCreateView() callback.


2 Answers

Fragments can't exist without an attached Activity. If the activity is destroyed, then so will the fragment. Also note that getActivity() will return null until onAttach() is called on the fragment.

like image 138
Alex Lockwood Avatar answered Sep 20 '22 15:09

Alex Lockwood


The issue was there was a long running thread on the Fragment, which returned results after the Fragment was deattached from the Activity. It seems strange for the Fragment to exist without being attached to an Activity (after it was already attached).

like image 21
StackOverflowed Avatar answered Sep 21 '22 15:09

StackOverflowed