Search code examples
androidandroid-activityfragment

getActivity() had returned null when isDetached() had returned false


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?


Solution

  • 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