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

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.

Related

How can I store and update a common (temporary) data between activities and fragments in Android?

i have an application with multiple fragments and activities. I'm wondering if I can create a container class between fragments. (I want to save with set and pull with get)
For example, I will save the gender information of the user in the FragmentA class, and then I will use this information when I switch to FragmentB. In the same way; I will get the user's age, height, weight in FragmentC class. and then I will access this information in the FragmentE (Final) class and save it to the Room database. How can I do this? Could you please give an example in Java?
Note: I'm using Shared Preferencens but I want to look for a different method as I don't know if it works asynchronously or synchronously. For example, can we create such a container with ViewModel LiveData, store the data and access it from anywhere?
Shared ViewModel in Android to communicate with other fragments. You can save your all data in this SharedViewModel and acsess it in all the fragments.
Please follow this link https://www.geeksforgeeks.org/shared-viewmodel-in-android/
Here they have used two fragment which act as sender and receiver similarly you can create for your multiple fragments
//Java Implementation of SharedViewModel
Sharing data between fragments using new architecture component ViewModel

Best way for frequent view change in android?

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

ViewModel Data Lost When BackPress

firstly I want to say I am sorry. I am newbie in MVVM. I want to know how to retain the data in viewmodel ??
For example I have followed this codelab tutorial https://codelabs.developers.google.com/codelabs/android-lifecycles/#0.
I try to kill the apps then go back into the apps but the data is not saved .Why?
I tried to make new activity by intent it. I ln new activity I implement the same code as statelifecyle. But why when I backpressed and try to enter back the newactivity the data is not saved ?
To answer your questions:
Data in ViewModel is only persisted throughout the lifecycle of your activity. So if your app dies, your data is not saved. If you want it to persist, consider integrating an off-line data persistence library like Room or you can also use SharedPreferences depending on your use case.
According to this post: Android LiveData - how to reuse the same ViewModel on different activities?
When you call ViewModelProviders.of(this), you actually create/retain
a ViewModelStore which is bound to this, so different Activities have
different ViewModelStore and each ViewModelStore creates a different
instance of a ViewModel using a given factory, so you can not have the
same instance of a ViewModel in different ViewModelStores
In other words, different activities cannot share a single ViewModel. So if you want to switch pages while retaining data in your ViewModel, consider using fragments inside your activity instead.

Android - Launch multiple methods in others Activities

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.

Notifying view/activity when the data/model changes

I have an Activity A, Activity B and an Object C. I need to start Activity B from Activity A and while starting i need object C to find user location and once it is available Activity B must be notified with the location object.
I am not sure how Object C can notify Activity B since android dosent allow to get hold of Activity References.
Look into implementing a Bound Service. Your location info could be fetched within this service (on another thread, of course), and retrieved within Activity B when it binds to the service.
Create an AsyncTask that will find the user location in the background.
Once completed, you can update the UI or maybe create a notification to the user.
Use Java Observer and Observable classes.
By extending the Observable class on your data object (model), you are able to assign Observers which listen for changes in said data model. When the data changes, the Observer is notified automatically and fires its update() method.
The update() method is an obvious place to put your code which refreshes the views impacted by the changes in data, this is where the linkage between the views and the data model occurs (usually in the Android Activity). The beauty of using the Observer and Observable classes is that the data model, views and controller (the Activity that updates the views) are all separated. That is, you can use the data model for whatever you want, if you change the views it won’t break the data model and vice versa. This makes your app much simpler to understand and easier to update later down the road.
Here's simple code example: http://www.ootpapps.com/eclipse_projects/ObserverExample.zip

Categories

Resources