I am using YouTubePlayerSupportFragment
in one of my fragments but I am not using it inside the layout file but initialising it programmatically. Some of the users are facing this crash at runtime:
Fatal Exception: java.lang.IllegalStateException: Fragment YoutubeLessonFragment{3a2e875} not attached to a context.
at android.support.v4.app.Fragment.requireContext(Fragment.java:614)
at android.support.v4.app.Fragment.getResources(Fragment.java:678)
at android.support.v4.app.Fragment.getString(Fragment.java:700)
at com.musicmuni.riyaz.youtubelesson.YoutubeLessonFragment.loadYoutubeVideo(YoutubeLessonFragment.java:168)
at com.musicmuni.riyaz.youtubelesson.YoutubeLessonPresenter$2.onModuleLoaded(YoutubeLessonPresenter.java:188)
at com.musicmuni.riyaz.data.AppDataRepositoryImpl$10.run(AppDataRepositoryImpl.java:187)
at android.os.Handler.handleCallback(Handler.java:754)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:163)
at android.app.ActivityThread.main(ActivityThread.java:6221)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
My code for initialising the youtube fragment goes like this:
private YouTubePlayerSupportFragment youtubePlayerFrag;
.........
public void loadYoutubeVideo(String videoId) {
mVideoId = videoId;
if(getContext() != null) {
youtubePlayerFrag = YouTubePlayerSupportFragment.newInstance();
youtubePlayerFrag.initialize(getString(R.string.youtube_api_developer_key),
this);
getChildFragmentManager().beginTransaction().add(R.id.flYoutubeVideoHolder,
youtubePlayerFrag).commit();
}
}
where loadYoutubeVideo(...)
gets a callback from a background running thread loading the required video id. Any pointers here?
Probably your Fragment
in not attached to the activity
while you are calling getString()
method.
because the docs says:
Fragments now have requireContext(), requireActivity(), requireHost(), and requireFragmentManager() methods, which return a NonNull object of the equivalent get methods or throw an IllegalStateException.
You might want to check if the fragment is attached to the activity or not, by calling isAdded()
method of fragment.
Also you can pass the argument directly to newInstance(..args..)
rather that creating initialise()
method.