Question

I have a question concerning the use of getActivity().

If I have for example these 2 different uses:

Here I just use getActivity() to provide a Context:

Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT);

And here I use it to get assets:

getActivity().getAssets();

My question is, is there any difference between those 2 lines if the Activity has not been added to the Fragment yet?

Is it possible to get a null pointer if getActivity() is only used as a Context?

I hope my question is clear...

UPDATE: For the ones down voting, at least please explain why...

Thank you

Was it helpful?

Solution

Finally I came up with this solution for my Fragments, and I did not get any error since:

I will actually get the context for the Fragment as soon as possible, in the method onAttach():

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    mContext = activity;
}

Thanks to this, I can use the Activity's context anywhere in the class.

For the cases where I need to get elements from the Activity itself, I will do it in the method onActivityCreated() that guarantees that the Activity will be fully initialized.

For example:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    //Get the device screen size
    Display display = getActivity().getWindowManager().getDefaultDisplay();
    (...)
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top