Search code examples
androidandroid-fragmentsmvp

MVP for Android, how should we provide a fragment with arugments?


I am studying Model View Presenter for Android

I've been through many tutorials and examples but it would seem none demonstrate how we should give a fragment arguments.

Let me go through an example of what I mean

BurgerListFragment

This fragment shows a RecyclerView of burgers. The underlying adapter contains a array of objects that represent burgers.

BurgerDetailFragment

When we click on a burger from BurgerListFragment, this event is passed to our presenter which then communicates back to the view that BurgerDetailFragment should be shown.

However, we must pass BurgerDetailFragment the burger object that was clicked.

So typically it would be like this

public static BurgerDetailFragment newInstance(Burger burger){
 BurgerDetailFragment burgerDetailFragment = new BurgerDetailFragment();
 Bundle args = new Bundle();
 args.putParcelable(BURGER_KEY,burger);
 burgerDetailFragment.setArguments(args);
 return burgerDetailFragment;      
}

However, my confusion comes from BurgerListFragment being told by the presenter to show BurgerDetailFragment as it getting data from the model to give to another view and view should not communicate to the model!

If you have any questions let me know

NOTE 1 In my example, I am aware that two fragments are directly communicating with each other is bad but it is just for this sample and is in fact another question I have for another day!


Solution

  • The way I manage this sort of thing is to have a value in my model which represents the currently selected data.

    Hopefully the following diagram gives you a good idea of what I mean:

    MVP Burger Diagram

    In practice you would presumably keep your Burger data in the local database. The BurgerListPresenter asks the model for a list of all Burgers which it would load the db.

    When the user selects a burger the presenter puts this data back in the model. This could be stored as the id of the selected burger in SharedPrefs for example.

    BurgerDetailsPresenter asks the model for the current selected burger. The model would check the SharedPrefs for the id of the current burger then load it from the database.

    This way the two Fragments are completely unaware of each other, as are the two Presenters.