2021年4月8日星期四

NullPointerException after calling activity method from fragment

So today I decided to updat a lot of deprecated libraries that I was using on my app. I was also adding new classes using koltin instead of java, because I plan to migrate to it soon.

One of the libraries I had to remove was

implementation "androidx.lifecycle:lifecycle-extensions:${versions.lifecycleExtensions}"  

and I replaced it with

implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${versions.lifecycle}"  implementation "androidx.lifecycle:lifecycle-livedata-ktx:${versions.lifecycle}"  

After changing all the instances of my viewmodels, a new problem was showing, and I read that I had to add the new Fragment library:

implementation "androidx.fragment:fragment-ktx:$fragment_version"  

With this library I started running with a new problem that I haven't been able to solve yet. I have one activity and multiple fragments (Jetpack). I had one method on my activity:

FloatingActionButton fab;    public void showFab() {     fab.show();  }  

and on my child fragment:

@Override      public View onCreateView(LayoutInflater inflater, ViewGroup container,                               Bundle savedInstanceState) {                // some code          ((MyActivity) getActivity()).showFab();            return view;      }  

The problem is that now, for some reason, my fab variable (and all other activity's local variables) are set to null, and this leads to the NullPointerException that I'm facing.

I also tried changing my approach, and use an interface to communicate those two instead, but the onAttachFragment method is deprecated and don't know which method should I use.

My app was running and working just fine before all of these libraries changes.

What am I missing here?

Thanks!

https://stackoverflow.com/questions/67015366/nullpointerexception-after-calling-activity-method-from-fragment April 09, 2021 at 01:07PM

没有评论:

发表评论