I wonder if these two methods leads to same results or one is better to use than the other.
if(isAdded()){
//do something with activity since fragment is currently added to its activity.
}
And
if(null != getActivity()){
//do something with activity. Its not null
}
isAdded()
is better to use in pretty much all circumstances for these 2 reasons:
isAdded()
returns true if the Fragment is currently added to its
activity. getActivity()
just returns the associated activity. In most cases this will return the same boolean but better to be safe
It is less code to write
Source code:
http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Fragment.java/
/**
* Return the Activity this fragment is currently associated with.
*/
final public Activity getActivity() {
return mActivity;
}
/**
* Return true if the fragment is currently added to its activity.
*/
final public boolean isAdded() {
return mActivity != null && mAdded;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With