Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Here is what I use to trigger method on MainActvity.java from my Fragment page:

((MainActivity) getActivity()).openGallery();   

Once I get to slide in the fragment page for the first time after opening app, and execute this code, IT WORKS. But, when I hide that fragment page and then bring it back, and execute that code again, the app crashes, saying something like:

 Attempt to invoke virtual method 'void com.test.test7.MainActivity.openGallery()' on a null object reference

None of the answers I found cover this problem, when it works for the first time and the crashes at the second time.

Any help is apreciated.

Hmmm. It works!!!!! .... But, .... I don't see the logic. It's not like i'm making getActivity() not null anywhere in between. It's just conditioning whether it's null or not. And then, what if it's null? – ekashking Apr 29, 2017 at 14:51

You can refer to the documentation under Section "Handling the Fragment Lifecycle". Basically somewhere in your code you called ((MainActivity) getActivity()).openGallery() while the fragment is not attached to activity, hence parent context return null.

You should not assume that activity context is always available because more often than not the fragment gets detached and reattached again. You should

  • (if context is necessary for you) only call getContext() in methods where fragment is guaranteed to be attached (see previous link on available fragment callbacks), or

  • always perform a conditional check to ensure (MainActivity) getActivity() is not null before use.

  • Thanks for contributing an answer to Stack Overflow!

    • Please be sure to answer the question. Provide details and share your research!

    But avoid

    • Asking for help, clarification, or responding to other answers.
    • Making statements based on opinion; back them up with references or personal experience.

    To learn more, see our tips on writing great answers.