2

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.

ekashking
  • 387
  • 6
  • 19

3 Answers3

1

try this.

if(getActivity()!=null){    
  ((MainActivity) getActivity()).openGallery(); 
}
Vasant
  • 3,475
  • 3
  • 19
  • 33
  • 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 '17 at 14:51
  • can you try making getinstance method into Mainactivity and call? – Vasant May 01 '17 at 02:34
0

try to use context of that fragment and do something like

 ((MainActivity) mContext).openGallery();   
vaibhav
  • 312
  • 2
  • 10
0

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.

Neoh
  • 15,906
  • 14
  • 66
  • 78