Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between getView() and getActivity()?

What is the difference between getView() and getActivity()?

I have used both methods but don't understand the basic difference even methodology of usage are also same in android:

ListView deliverItemList = (ListView) getView().findViewById(R.id.load_item_list);
ListView deliverItemList = (ListView) getActivity().findViewById(R.id.load_item_list);

I have assumed that getView() may produce NullPointerException, share your knowledge with me and which method is recommended?

like image 485
Abdul Rahman Avatar asked Sep 10 '15 12:09

Abdul Rahman


People also ask

What is difference between getActivity and requireActivity?

The only difference is requireActivity throw an IllegalStateException if the Activity is null. but getActivity return null when that Fragment is not attached to the Activity. requireActivity() returned exception and its message. Certainly, requireActivity() throws a more explicit exception.

What is required activity in Android?

requireActivity() a method that returns the non-null activity instance to fragment or throws an exception. If you are 100% sure that in your fragment's lifecycle, activity is not null, use requireActivity() as it needs no !! notation inside code, otherwise put it inside try-catch block to avoid NullPointerException.


2 Answers

getActivity() returns the Activity hosting the Fragment, while getView() returns the view you inflated and returned by onCreateView. The latter returns a value != null only after onCreateView returns

like image 62
Blackbelt Avatar answered Sep 21 '22 21:09

Blackbelt


From android docs:

getActivity() returns the Activity this fragment is currently associated with, and getView() returns the root view for the fragment's layout (the one returned by onCreateView(LayoutInflater, ViewGroup, Bundle)), if provided.

So, in your case, by the following line of code:

getView().findViewById(R.id.load_item_list);

you are searching for the view in your fragment, but using the following line of code:

getActivity().findViewById(R.id.load_item_list);

you are searching for the view in your activity hosting your fragment.

About your question of which one to use, it depends. If you are trying to inflate fragment, you need to inflate your xml in onCreateView, and using that inflated view you search for your views like this:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.your_layout, container, false);
    ListView lv = (ListView)v.findViewById(R.id.view_id);
}
like image 20
yrazlik Avatar answered Sep 22 '22 21:09

yrazlik