4

Once upon a time my debugger hit the breakpoint on Log.d:

@Override
public void onDataChanged(DataTypeChanged dataType) {
    if (!isDetached()) {
        if(getActivity()==null){
            Log.d(CommonConstants.DEBUG_TAG, "Yes, it is null.");
        }
        List<WeekViewCoreTask> tasks = DataProvider
                .getWeekViewCoreTasks(getActivity().getApplicationContext());

        mWeekView.setTasks(tasks);
    }
}

getActivity() returns null when isDetached() returns false

I thought this never could occur. How this could occur: getActivity() had returned null when isDetached() had returned false?

Sergey
  • 1,020
  • 11
  • 22
  • Hi sergey you are extends your application from Activity or Fragment.Please let me know. If your extends your application from Activity means you will call getBaseActivity() instead of getActivity().getApplicationContext(). If you extends your application from Fragment means your will use getActivity() instead of getActivity().getApplicationContext(). Hope it should helpful for you. Thanks – Jebasuthan Jan 29 '14 at 16:05
  • http://stackoverflow.com/questions/11536166/android-get-activity-returns-null check this – Zohra Khan Jan 29 '14 at 17:05

2 Answers2

7

Not 100% sure on this, but according to the Android docs, isDetached() will only return true if a Fragment has been explicitly detached from its Activity. There are several other reasons a Fragment's parent Activity could be null, though. It might be best to instead call isAdded to check if the Fragment is currently attach to its Activity

NasaGeek
  • 2,138
  • 1
  • 15
  • 19
0

According to the Android docs, isDetached()

Return true if the fragment has been explicitly detached from the UI. That is, FragmentTransaction.detach(Fragment) has been used on it.

which means isDetached() represents the UI status, it has nothing to do with the attachment to its Activity.

A Fragment will be detached from its Activity only after onDetach() method is called. At that point, isDetached() can both be true or false depending on whether FragmentTransaction.detach(Fragment) has been used on the fragment.