Android - Launch multiple methods in others Activities - java

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.

Related

How to keep objects throughout multiple activities and fragments in Android?

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.

Storing Application context in SharedPreferences when app crashes

Currently im storing all of my users information and there friends information inside a class i have created called userInfoCore that extends Application so i can store the values in the Context. When my app crashes it gets rid of al those values and my users are forced to relogin, so i would like to store them in SharedPreferences to be grabbed again in the onCreate of my MainActivity.
I know how to store them, thats not the issue. The issue is i dont want to overcrowd my code with repetitive code and put the storing methods in all the onDestroy's of all my Activities, and i cant #Override onDestroy in my userInfoCore class because its not an Activity i imagine?
Some insite would be great. Thank!
EDIT:
Ive found out that this line in the android manifest is causing my Application Context data to be destroyed even when the user presses the home screen. android:launchMode="singleInstance"
My thoughts are YES i could store them in the onPause or do what #CommonsWare suggested. However like i said, i dont want to have to do all of that. If i can find the root of the cause of the issue... which i have. (The singleInstance in manifest) then i would be much happier.
Some insite would be great.
Update your persistent store when the data changes. A custom Application subclass, like any singleton, should only be treated as a cache or other transient spot for data. If you care about the values, persist them, at the point when the data is changed.
This is a good argument for using the Model-View-Presenter (or Model-View-Controller) pattern. By separating your Model (domain data and procedures) from your View and Presenter (Layout and Activity respectively) you only have to write the Store logic once.
Then you have two choices: either do as #CommonsWare suggests, have the model write itself whenever it changes, or add a simple call in each Application's onPause (onDestroy is too late! It may never get called.) to the model to tell it to save itself.
Note: the model can accept a context as a construction parameter for use in finding a shared preferences, or it can create it's own named preferences using the PreferenceManager

GWT - Separating role of presenter from activity

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)

Get an object "FragmentManager" in "Service"

Is it possible to get an object "FragmentManager" in "Service"? Is it possible to pass an object "FragmentManager" from "Activity" in the "Service".
PS: Includes not officially supported features.
Is it possible to get an object "FragmentManager" in "Service"?
No, sorry.
Is it possible to pass an object "FragmentManager" from "Activity" in the "Service".
That would be an exceptionally bad idea.
If you wish for your service to update your UI, bear in mind that there might not be a UI. The user is welcome to press their BACK or HOME button to exit your UI, even while your service is running.
Also bear in mind that it might be a different UI. For example, when the user rotates the device from portrait to landscape, your activity (and fragments, by default) will be destroyed and recreated. Or, the user may tap on something that brings a different activity to the foreground, and that activity has its own fragments and manager.
Therefore, to have your service update your UI, you need to use a communications path that supports this sort of decoupled operation, such as:
send a broadcast
send a broadcast using LocalBroadcastManager
update content via a ContentProvider, with activities using CursorLoader or ContentObserver to be notified about data changes
etc.

Android: Using observer pattern with Views (possibly MVC, MVVM related)

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.

Categories

Resources