Mr_and_Mrs_D
Mr_and_Mrs_D

Reputation: 34046

Fragments in android - when is the Activity that called them available?

Would this be correct :

public class DetailsFragment extends Fragment {

    private final Intent intent = getActivity().getIntent();
    // use intent here and there
}

I know in servlets one must wait for init() to have the context available. What is the situation in android ? Do we have to do things like this in the OnCreate ? As an added question - is this kind of use of final fields frowned upon ? Does it mess up the lifecycle ?

Links welcome :)

Upvotes: 0

Views: 48

Answers (1)

CommonsWare
CommonsWare

Reputation: 1007399

Would this be correct :

No, as getActivity() will return null during the initialization step.

What is the situation in android ?

getActivity() definitely returns the Activity in onCreateView(), onActivityCreated(), and later lifecycle methods. It may return the Activity in onCreate(), but I do not recall ever implementing onCreate() on a fragment, so I cannot say for certain.

As an added question - is this kind of use of final fields frowned upon ?

Well, since this one will not work (see above), code crashes are generally frowned upon... :-)

Upvotes: 1

Related Questions