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.
Related
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
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.
My app initially makes a request for a list of objects from a server. These objects are currently kept in memory as an ArrayList<MyObject>. However, I want these objects to be passed through multiple activities before the user terminates the flow by pressing a button. I could make the ArrayList serializable and pass it through Intent extras. But I could also store MyObject(s) in a SQLite database and access/modify them in any Activity without having to go though intents. I was wondering what the norm is to accomplish this.
EDIT: forgot to mention that all the values would be deleted once the user terminates the flow.
SQLite is not the best way to go in your case since you don't need the data to be persistent after you close the app. It will just slow your app having to store and retrieve all entries on every activity transition. You can do one of the following instead:
Pass Serializable the way you described. Might be slower than the other alternatives though
Make MyObject implement Parcelable and use [intent.putParcelableArrayListExtra()](https://developer.android.com/reference/android/content/Intent.html#putParcelableArrayListExtra(java.lang.String, java.util.ArrayList))
Extend Application and load the list from the network in your Application.onCreate() and call getList() from activities that need it. That way you load it once and you don't need to pass it between different activities.
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