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
  • 950
  • 9
  • 20
  • 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

1 Answers1

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,140
  • 1
  • 14
  • 19