I'm working on an Android app, it's a turn-based game. I have two types of turns (let's say TypeA and TypeB) and UI for TypeA is completely different from UI for TypeB. Also, there are sub-types for TypeB, each of them having their own UI. Every UI is implemented with a Fragment, but for a single game I need to create about 30 fragments, each of them used just a single time.
Currently I create the Fragment, save the data I need, destroy the fragment with
fragmentTransaction.remove(myFragment).commit()
and then I create the next Fragment and so on. Is there a better way to handle this situation?
I think that this is the right way, add fragments only when you need it and remove whose do not need.
Anyway I can suggest you to try Navigation Component to check visually all your fragments flow.
Ref. https://developer.android.com/guide/navigation/navigation-getting-started
Related
I created a class "Car" and I have a list of instantiated Cars created in my MainActivity.
I have a master/detail flow with an ItemListActivity as well, which should be able to receive a specific car from MainActivity.
This master/detail flow works as a Settings Menu, where there are multiple fragments acting as different types of settings (Build, engine, etc.)
The master/detail flow needs to then get all the changes made to the edit text, and update the fields of the Car that it received, and than send it back to MainActivity.
I'm not sure if this is 1) possible or 2) the best way to approach this problem. Should I be keeping the list of objects in MainActivity? Is there a better way to keep an object that will be used globally?
I would recommend having a ViewModel in your activity and get the ViewModel instance from your fragments as follows.
carViewModel = ViewModelProviders.of(getActivity()).get(CarViewModel.class);
The CarViewModel might have the necessary elements to build a car and from each fragments, you can just update that ViewModel that resides in your activity.
The CarViewModel might have a function call buildCar that you can trigger when you are done building your car from different fragments. The ViewModel will be bound to the lifecycle of the activity and hence if you close the activity, the information will be lost.
I'm really new to Android.
I have a fitness app where the user can change it's gym. There are several activities where the content depends on the user's gym.
One activity will show the workouts of the gym, another the athletes of the gym, etc...
What I would like, is to update all of these activities when the user
change it's gym.
I know how to do that in iOS, I just need to add an observer NotificationCenter.default.addObserver(), but I really don't know how to do that for android.
Is it possible? If yes, how?
First of all, according to Google your app should contain only one entry point, in other words one Activity, and have Fragments to represent contents of application.
Second of all, for solution to your problem you could use SharedPreferences. It has onSharedPreferencesChangeListener(); which could be used to listen for updates of information (e.g. GYM name, your custom user permissions, user role, etc.). When something changes in SharedPreferences you notify all dependent objects of application to change their information accordingly by using Observer pattern (P.S. can use RxJava for that). You could also implement SharedPreferences change listener in all the Fragments and updated their data there.
If, for whatever reason, you want to stick with using multiple Activities in your application, you could still use SharedPreferences, but instead of listening to changes, you just read preference values in Activity onCreate(); method and create content accordingly (change item visibility, color, etc.).
That's one of the approaches. Hope this puts you in the right direction. Good luck :)
I think that Android Architecture Components might help you with this, specifically LiveData which is an Observable.
Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.
LiveData will notify any of your activities that are coming to foreground.
I am working on an application in which there are some fragment classes, which can be open by two ways in the application. The first way is Main Flow , the second way is through the Navigation Drawer.
So when the fragment is called from the Navigation Drawer than it will perform some task, and if it's call from the Main Flow than it will perform another task.
How can I check the context? Is there possibility through the use of Enum class.
Note:
I don't want to send the hardcoded value through the Intent.
Firstly, you should avoid using enums in Android environment. Prefer to use #IntDef, #StringDef. The main reasoning behind this is the waste of resources. Enums take much more memory.
As Colt McAnlis shows in this perfmatters episode enums take 13x more space on rather trivial example.
Secondly, what you want to achieve may be done via Intents or Bundles, passing a boolean value from one component to another.
What advantages could be gained from divesting the role of presenter from an activity?
What are the roles/concerns that could be separated in order to dissect an activity from being a presenter?
Why would you want to separate them into two distinct concerns?
Under what circumstances would it make sense not to unify them?
Give examples, pros or cons.
I can see two main reasons to separate presenters from activities: reusability and testability.
Real use case for reusability: we have an illustration entity with properties like the photographer, copyright and date of shooting, which can be linked to documents. The legend of is on the relationship between the document and the illustration. You can edit both the illustration and the legend on their own screen, but we also wanted that the illustration could be edited from the legend screen. So we made a presenter for the illustration screen. The illustration activity is a really thin wrapper around that presenter, and the legend activity is a bit more complex, but reuses the presenter and view. The activities' responsibility is to provide the RequestContexts and do the fire() (the save/cancel buttons are on another activity, similar to the actions on Google Groups).
Hypothetical use cases for reusability:
for different form-factors, you want to aggregate things on the same screen or separate them on their own screen (e.g. master/detail), and when you aggregate them, having two activities might not be ideal. Using thin activities in the phone form-factor allows you to reuse the components (presenter/view) within a single activity in the tablet or desktop form factors.
reusing the same presenter on different platforms: you could possibly use the same presenter on an Android app and a web app (and even possibly an iOS app through java2objc), the view would be a native Android view or a GWT-based view, and the navigation would be handled by Android activities and/or fragments vs. GWT activities and places.
About testability (this is theoretical), you could then test your presenter without the hassle of the activity lifecycle (mocking the view), and then separately test the lifecycle (whether it correctly initializes and cleans up the presenter, fetches/caches the data, etc. mocking the presenter).
See also the commit message of https://code.google.com/p/google-web-toolkit/source/detail?r=10185
Ray's idea was to make MVP an implementation detail of widgets, just like cell widgets use internal presenters today. From the outside they're just widgets that you can compose tha way you want; on the inside they use MVP so you can test them without the need for a GWTTestCase.
First of all two Thanks for question which pushes me in to the longest research ever . :)
According to Thomos Broyer here.
Activity cannot talk with widgets,which presenter can do.
Two main areas of concern:
1- getting the data into the widgets:
how can this design be improved ?
Server (RequestFactory) ---> Activity ---> WidgetPresenter ---> Widget
here, RequestFactory hands in data to Activity, which then gives it to
the Presenter
which subsequently hands it to the widget.
2- getting the data from the widgets to the server
widget ---> WidgetPresenter ---> Activity ---> Server(RequestFactory)
I've spent some hours reading various questions and answers regarding implementing the various MVC-type patterns in Android. I've seen a few code examples posted in various blogs. I would, however, still appreciate some ideas and opinions on what I am trying to achieve. Specifically, I'd like to work out the best code mechanism to inform a single View, or a group of Views, that a particular item of data has been changed.
My application is quite simply one which obtains measurement data from a hardware device via Bluetooth, and displays and logs that data. At present, I have a Service which takes care of Bluetooth communications and background logging. I have a 'global' data store class that is an extension of Application.
As measurement data is polled from the external device, the measurement data (which is in reality about thirty bytes of data) is updated in the data store object (which, in MVC terms, I'm guessing is the 'model').
At any time, only a small subset of that data will be displayed by UI Views. Typically, a given View will only be interested in representing one particular byte of measurement data. As the user moves to different Activity classes, other Views will be displayed which would display a different subset of that data.
So to get to the point, I'm trying to choose the best way to cause invalidate() to be invoked on interested Views when a given data item is changed.
The options seem to be:
Make use of the existing Observer class, and related classes.
Kind of 'roll my own' observer pattern, by creating my own register() and unregister() functions in the data model. Observer Views would be held in an ArrayList (or perhaps a more complex arrangement of one observer List per data item). I'd loop through this ArrayList each time data are updated and call invalidate() (or postInvalidate() of course, depending on my threading arrangement).
Are there any reasons why I should use one of the above over the other? And is there any other 'observer' mechanism I should consider?
Many views in Android are backed by some subclass of BaseAdapter which has a method notifyDataSetChanged() which instructs the view to refresh itself. If you are using a view (such as ListView or GridView or any descendent of AdapterView) then it is backed by a BaseAdapter and you can simply update that Adapter and the view will refresh itself.
I guess this means, I vote that you use the built-in observer pattern. If you are using a custom view then obviously this won't work and you would have to use a custom method of refreshing anyway.
Another Option would be to use the Android Intent framework. When new data is received in the service set the data to the universal model and broadcast an intent that the data has been updated using the Context.broadcastIntent(Intent) method. Any view that is interested in that data would register and unregister receivers using the Context.RegisterReceiver(Receiver) and Context.unregisterReceiver(Receiver) methods. From there the view would retrieve the data from the universal model and update the view accordingly.
I think this might be what the observer pattern in Android.Lifecycle.Observer package is doing behind the scenes.