1

I have an activity with 3 tabs: A, B & C. For every tab, I’ve created a fragment (-f) and presenter (-p). The problem is that all three fragments (A-f, B-f, C-f) are the same, but presenters are not. So the question is how I can avoid code duplicity? I’ve tried to create a BaseFragment and extend it from A-f, B-f, C-f, but if I’m in A-f and something happens C-f (like UI update), then I receive java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.RecyclerView.setVisibility(int)' on a null object reference, because C-f at this is destroyed (am I right?) I don't want to create 3 same fragments with the same layouts.

P. Savrov
  • 1,064
  • 4
  • 17
  • 29

1 Answers1

1

I've done something similar and I've found using Views a lot simpler and less buggy. The android fragment managers can exhibit unpredictable behavior at times when executing various transactions. Here's a quick sample of how it can work:

YourActivity extends Activity {
      View a,b,c;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          a = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
          b = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
          c = getLayoutInflater().inflate(R.layout.YOUR_LAYOUT_ID, null);
      }
}

The activity is the presenter / controller for android, so I would go ahead and have the logic here instead of defining a presenter class for now. On each tab press you could then control which view to show. I don't see the code in which your are performing fragment transition so I cannot comment for sure if your fragment was destroyed.

Nelson Hoang
  • 413
  • 2
  • 11
  • thank you for option. For fragment transaction I use ViewPager. I'm not sure if using activity as a presenter is a good idea, I'll google it – P. Savrov Jul 28 '17 at 00:51
  • Fragments can work, but you'll get cases where you get a crash once in a blue moon and unfortunately there won't be a fix since you can't edit the android source. See https://stackoverflow.com/questions/18710561/can-i-use-view-pager-with-views-not-with-fragments for reference. In larger companies it makes sense to have lighter activites such as lyft as they've built out a MVC pattern https://github.com/lyft/scoop. For smaller projects I would highly recommend having your activities be the presenter / controller to bind data to views. – Nelson Hoang Jul 28 '17 at 01:01
  • In terms of MVC / MVP / MVVM though there is no "right" answer when it comes to architecture as expressed by Google engineer Dianne Hackborn https://plus.google.com/+DianneHackborn/posts/FXCCYxepsDU – Nelson Hoang Jul 28 '17 at 01:10