MVP Android: how to pass data from one activity to another? - java

I have the following doubt and I'm wondering if this breaks or not the MVP pattern.
My project has Activity1 where an user can fill a form and then the presenter, related to that activity, on a button click retrieves data from a database based on the information given by the user and put it into a list.
Activity2 has the job to display the objects of this list.
Is it ok (according to MVP) that Activity1 put the list into an Intent and then start Activity2 with that Intent? (I don't think so).
Should the presenter of the Activity1 pass the list to the presenter of the Activity2? But how can this be done if presenters can't communicate each other?

Personally I use a single Activity with Fragments which makes it easy to pass data around. For inter-activity communication, I just use Intents as you have suggested.

If you're using Kotlin you should check Navigation Component related topics.
Navigation component is the a best practice when navigation between Activities/Fragments and allows you to pass data as arguments between them.
On the other hand you can pass those arguments in your intent view Bundle and retrieve them in the second activity, separating the logic from the view layer, and only calling a method to present the data.

Related

How to change layout on button click in android app?

I am new in Android so correct me if i am wrong. When another activity is opened, the first one is destroyed. So i have to pass all variables to the new activty if i don't want to lose the data. Or, can I run another not UI thread that manages my data?
Basically I need to change layout in my app on button click. Is there any way to do it within the same activity or i have to start another activity with the new layout?
You can use one activity in your app and do what you want in fragments. Navigation is good tool to use for relating fragments to each other.
well initially you can use a single activity and in that activity you can call multiple fragments as per your need,
and for the data you can use MVVM architecture with room architecture, it saves your lots of time and code.
and go with navigation graph if you want a quick and easy implementation.
you can start all this with this demo.

Question about BottomNavigationView in Android

I have general questions about BottomNavigationView. I would like to have a BottomNavigationView in each of my Activities in an App for ordering something (e.g. food). It should have 4 buttoms:
Back
Info
Stats
My Orders
With 'Back' the app should just go back to the previous activity. The buttoms 'Stats' and 'My Orders' should switch to a persistent activity that should not be destroyed when not being displayed. 'My Orders' should display the last orders. The buttom 'Info' should only display some information about the current item or current menu (depending from which activity it is called). So basically I have 2 questions:
Should the Activities 'Info', 'Stats', and 'My Orders' be real Activities or just Fragments? Normally I think that at leat 'Stats', and 'My Orders' should be real Activities as they are persistent. But in many BottomNavigationView only Fragments are used?
How can I pass content information to the Activity/Fragment 'Info'. This Activity/Fragment should display information based on the Activity is was called from. Let's say the Activities are different dishes. Do I have to create a separate Info-Activity/Fragment for each dish? Or can I somehow define a dynamic Activity/Fragment that displayes information based on the current Activity?
I'd appreciate every comment and I'd really appreciate your help.
The recommended approach is Single Activity and Multiple fragments.
You can do this using Jetpack's Navigation Component
In case you need to pass data from an Activity/Fragment to the new calling Fragment, it can be done by setting arguments on the calling fragment and then getting it on the called fragment. If there is something which requires to be dynamic, for example- dishes fragment, make a single fragment and common layout and load the data dynamically from the backend.
For Setting Arguments, this should help
How to pass a variable from Activity to Fragment, and pass it back?
Note: You can use fragment without using Navigation Components but you have to use FragmentManager and FragmentTransaction and also have to maintain the Backstack by yourself which could be quite complicated

View Model can be heavy if we use single activity based architecture

As google suggests single activity based application. I have a situation where I need clarification.
I have one activity containing 3 fragments and each fragment is linked to different fragments having other screens.
should I use only one viewmodel for each tabs or should I use one view model having different screens.
As I have only one activity and view Model resides till activity is destroyed. Do all viewModel that I will create for each screen will contain data until activity is destroyed. If this is the case will it make my app heavy.
should I use only one viewmodel for each tabs or should I use one view model having different screens.
You should use the smallest scope for each ViewModel possible. Generally, this means that data associated with only one fragment should use a ViewModel associated with just that one fragment.
As I have only one activity and view Model resides till activity is destroyed. Do all viewModel that I will create for each screen will contain data until activity is destroyed. If this is the case will it make my app heavy.
ViewModels live only as long as the ViewModelStore they're attached to is around. Therefore if you have a ViewModel associated with a fragment, it'll survive only as long as that fragment exists. For example, if that fragment gets popped off the back or you call remove(), then the ViewModel is destroyed. ViewModels only live as long as your activity if you specifically create them using the activity as the ViewModelStoreOwner (for example, by using ViewModelProvider(activity)).
should I use only one viewmodel for each tabs or should I use one view
model having different screens?
In single activity architecture, you can use ViewModel with either Activity Scope or with Fragment scope. As #ianhanniballake suggested in his answer, use ViewModel with Fragment which means that each tab in your case will have its own ViewModel attached to fragment. This will provide separation of concerns for functionality in each tab.
As I have only one activity and view Model resides till activity is
destroyed. Do all viewModel that I will create for each screen will
contain data until activity is destroyed. If this is the case will it
make my app heavy.
Again answer to this question is connected to your first question and explanation provided to it.
While working with single activity architecture narrow down scope as much as possible. Use ViewModel associated with activity (lets call it Global ViewModel) only to keep data which is used across multiple fragments. This way viewmodel will contain data till activity is in backstack and fragments can use it when required.
This will provide you 2 advantages
ViewModel will not contain additional data which you mentioned in your 2nd question
And most importantly there will not be any data discrepancies while accessing fragment multiple times. For e.g. if you open any fragment, fetch data from api and keep it in Global ViewModel and fail to delete it when remove fragment from backstack then your fragment will show old/obsolete data when you will open fragment next time. To avoid this scenario it is better to keep this data in viewmodel with fragment scope.
I hope this will be useful.
Each Fragment usually should have a ViewModel itself but in some cases where you want to share the same ViewModel instance, you can achieve it with having a ViewModel scoped to an activity.
ViewModel objects are scoped to the Lifecycle passed to the ViewModelProvider when getting the ViewModel it is found on the docs and you might have to read other details there but technically you can scope a ViewModel to a Fragment or to an Activity.

Do fragments keep running even if not on screen?

I have a Android app that shows lots of real-time data jammed onto one large scrolling activity.
Now i want to split it up into two simpler screens using fragments, where only one fragment may be on the screen at any one time.
I read up a whole lot on fragments and watched several videos, but before i start ripping up my code to convert it to fragments i wanted to know the following.
If i create two fragments A and B, then while showing fragment B, data comes in for fragment A. Can the controlling activity still communicate with fragment A giving it data even though its off screen? OR do i have to save the data somewhere and then when the user switches to fragment A then I give fragment A the data to be shown, while saving incoming data for fragment B which will now be off screen?
The problem is that right now im not saving any data because everything is on one screen, so as data come in i just displayed it, but if i switch to using fragments i dont know if i can do the same thing by passing the data to the fragments even if they are not on screen at the same time.
Thanks.
If you retrieve your data with multiple asynchronous requests in your Activity, you may create a fragment for each of them and move related retrieval operation into that fragment (probably to oncreateView() method). Then, you can use ViewPager (probably with TabLayout) in the parent Activity to be able to use all those fragments. Therefore, your Activity only deals with setting the ViewPager and leave the rest to fragments.
ViewPager shows one page at a time but it can initialize other fragments as well, even before they are shown. You can use ViewPager's setOffscreenPageLimit() method to increase that range.
In case you need a communication channel between fragments and the activity, you may create callback mechanisms, as described here.

In MVP structure which class responsible for keep list items and how to notify data change in this

I trying to refactor one of my activity class to implement mvp(using mvp mosby library) . I have a RecyclerView and in this view there is some items that some changes apply to them during the run time. for example I do some I/O operation and change one row.
I think it's better to keep my items in presenter class; what is the best practice for this? keep this in 1)presenter or 2)activity or 3)only keep view related item in adapter and all other item in presenter.
the activity now keep items directly and change item row in activity and then notify adapter. isn't better to move all this line in adapter and notify adapter in the adapter class? for example i want change icon of some row.where and which class is responsible for that? adapter? activity? now I want to implement it like this in adapter:
changeItemIcon(int position, int iconRes){
mImages.get(position).setICon(iconRes);
notifyItemChanged(position);
}
I invoke this method on activity and invoke activity method from presenter.
is it good? what is the best practice to do this?
UPDATE
also I find this question ( Best way to update data with a RecyclerView adapter ) that using adapter method for changing items. but what about modify? Need I keep reference to items in my activity?
for example i want change icon of some row.where and which class is responsible for that? adapter? activity?
I know it sounds a little bit strange, but changing an element is always the responsibility of your "business logic", even just for "icons".
The workflow should be as follows (unidirectional data flow):
View appeares, tells presenter to load a list of items
Presenter loads items form "business logic" and registers himself as an
observer / listener / callback (whatever you want to call it)
Presenter receives result and tells the view to display the list of
items (through RecyclerView and corresponding adapter).
so far is what you have implemented I guess, now it comes to the point where you want to change an item.
User clicks on an item in your RecyclerView which then should trigger to change the icon of this item. Therefore View should call: presenter.changeItem()
Presenter is just the man in the middle in this case and will invoke the "business logic layer" to tell that the item should be changed to new state (icon has changed).
"Business logic layer" will change the models state (change the items icon) and then will notify its observer / listeners that the model has been changed.
Since Presenter is still observing / listening to the business logic layer (see point 2.) the Presenter will be notified (see point 6.) with a new (updated) list of items containing the updated item which icon has been changed.
Similar to point 3. Presenter will tell the view to display the new (updated) list of items (through RecyclerView and corresponding adapter).
Do you see the unidirectional data flow? That is very important. Immutability FTW.
MVP has two different variants: Passive View and Supervising Controller. Depending on your taste, you can stick to one or mix both of them in your app.
If you choose Passive View, you need to hide Model from View and let Presenter format data then set to the View. In this case, you need to keep Model reference in Presenter. View should only hold view-data (adapter) for its displaying purpose.
If you stick to Supervising Controller, you can allow View to directly bind data from Model and ask Model to perform some simple logic. Presenter should only care complex logic, i.e some operations which need to involve Services. In this case, you can give Model (your items) to View (activity) and let it interact with Model in some simple manner.
PS: Please also check out our new MVP framework: Robo MVP at http://robo-creative.github.io/mvp.
I've never used mosby, but I've just read their docs (good reading btw) and here's my understanding:
A recycler view usually consists of the view (android term) and an adapter. Both are connected inside a fragment or activity. In terms of MVP/mosby this is all view layer. The presenter should only retrieve and pass the to-be-shown data from your service (model layer in mosby, "service layer" or "business logic" in other concepts), which in turn gets it from a DAO or repository (model layer).
The docs say that the presenter only handles the view state, not the actual contents. Your state is "showing list".

Categories