Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is isAdded() same as null != getActivity() in Android Fragment?

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
}
like image 601
Maher Abuthraa Avatar asked Dec 18 '22 07:12

Maher Abuthraa


1 Answers

isAdded() is better to use in pretty much all circumstances for these 2 reasons:

  1. 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

  2. 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;
}
like image 54
Ken Wolf Avatar answered Dec 27 '22 09:12

Ken Wolf