Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onAttach activity is null

Tags:

android

In creation of a fragment, I encountered getActivity() to be null. So to narrow down the problem, I kept a local copy of activity in onAttach(Activity activity), which by definition is when it is attached to an activity.

However, I logged the activity in onAttach, and it is still null.

I'm only running into this problem in 2.3.6 and below.

Is this a known problem with support package?

like image 850
SIr Codealot Avatar asked Mar 21 '13 16:03

SIr Codealot


1 Answers

The series of methods called to bring a fragment up to resumed state are:

  • onAttach(Activity) called once the fragment is associated with its activity.
  • onCreate(Bundle) called to do initial creation of the fragment.
  • onCreateView(LayoutInflater, ViewGroup, Bundle) creates and returns the view hierarchy associated with the fragment.
  • onActivityCreated(Bundle) tells the fragment that its activity has completed its own Activity.onCreate().
  • onViewStateRestored(Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored.
  • onStart() makes the fragment visible to the user (based on its containing activity being started).
  • onResume() makes the fragment interacting with the user (based on its containing activity being resumed).

The bold method should be the one where getActivity doesn't return null anymore.

the onAttach method should not be used to call methods of the activity object, It should be used to initialise callback interfaces. An example of these interfaces can be found here.

like image 71
Tobrun Avatar answered Oct 18 '22 01:10

Tobrun