I pass the data through the Bundle to the `vm, I look at everything clearly in the log, but when I try to turn arguments in the fragment where I should have received it, null comes.
I can't enter at what point I could have lost them.
Here is my first vm:
fun sendData(it: ConfigurationDto?) {
Log.d("some", "sendData : $it")
if (it != null) {
OnboardingViewModel.newBundle(it)
}
}
Here is code of my OnboardingViewModel:
companion object {
val Bundle.configuration: ConfigurationDto?
get() = getSerializable("configuration") as? ConfigurationDto
fun newBundle(configuration: ConfigurationDto): Bundle {
Log.d("some", "new Bundle: configuration $configuration")
return Bundle().apply {
putSerializable("configuration", configuration)
}
}
}
Here I see that the configuration is coming.
And when i trying to get my arguments in fragment:
class OnboardingFragment : Fragment(), ViewPager.OnPageChangeListener, View.OnClickListener {
private fun setupViewModel() {
viewModel = ViewModelProvider(this, viewModelFactory).get(OnboardingViewModel::class.java)
lifecycle.addObserver(viewModel)
Log.d("some", "arguments in vm: $arguments")
viewModel.setInitialData(arguments)
I see that arguments is null.
I see that arguments is null.
arguments is the Bundle that is set on a Fragment, usually when you create it. Something like:
val fragment = OnboardingFrament().apply {
arguments = Bundle().apply {
// Set values on bundle
}
}
Since you have only shown two random pieces of code related to some random ViewModels and not where you create OnBoardingFragment, I can only assume that wherever you create it, you are not setting the arguments, hence it's null.
Your sendData function does nothing. It creates a Bundle object and then immediately releases it to the garbage collector because you aren't doing anything with it. Incidentally, it's weird that it takes a nullable parameter when it can't do anything useful with null. If a function is useless when its parameter(s) is null, it should not accept a nullable parameter. Otherwise, the calling code looks like it's doing something useful when it isn't, which just makes debugging more difficult and bugs more likely.
Also, it is highly unusual that your ViewModels are aware of your Fragments. It is part of the contract of ViewModel that you're not supposed to leak your Activities or Fragments to them. LiveData is special because it can automatically drop its references to its observers at the appropriate time to prevent a leak.
So whatever you're doing by having your ViewModel observe your Fragment lifecycle is probably a design error. You should not be trying to send data to another Fragment by using a ViewModel function.
If you want to send data from one Fragment to another Fragment, then you should set its arguments property right after instantiating the Fragment instance and before making the fragment transaction. Then, as the framework automatically recreates the Fragment as needed for configuration changes, when it automatically creates new instances of that Fragment, it will also pass it that same argument data.
Related
I know this is a very documented topic, but I couldn't find a way to implement it in my project, even after spending hours trying to figure it out.
My root problem is that I have a RecyclerView with an Adapter whose content isn't updating as I'd like. I'm a beginner in Android, so I didn't implement any MVVM or such architecture, and my project only contains a repository, fetching data from Firebase Database, and passing it to a list of ShowModel, a copy of said list being used in my Adapter to display my shows (In order to filter/sort them without modifying the list with all shows).
However, when adding a show to the database from another Activity, my Adapter isn't displaying the newly added show (as detailed here)
I was told to use LiveData and ViewModel, but even though I started understanding how it works after spending time researching it, I don't fully get how I should use it in order to implement it in my project.
Currently I have the following classes:
The Adapter:
class ShowAdapter(private val context: MainActivity, private val layoutId: Int, private val textNoResult: TextView?) : RecyclerView.Adapter<ShowAdapter.ViewHolder>(), Filterable {
var displayList = ArrayList(showList)
class ViewHolder(view : View) : RecyclerView.ViewHolder(view){
val showName: TextView = view.findViewById(R.id.show_name)
val showMenuIcon: ImageView = view.findViewById(R.id.menu_icon)
}
#SuppressLint("NewApi")
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false)
return ViewHolder(view)
}
#SuppressLint("NewApi", "WeekBasedYear")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val currentShow = displayList[position]
val index = holder.adapterPosition
holder.showName.text = currentShow.name
holder.itemView.setOnClickListener{ // Display show content
val intent = Intent(context, DetailsActivity::class.java)
intent.putExtra("position", index)
startActivity(context, intent, null)
}
holder.showMenuIcon.setOnClickListener{
val popupMenu = PopupMenu(context, it)
popupMenu.menuInflater.inflate(R.menu.show_management_menu, popupMenu.menu)
popupMenu.show()
popupMenu.setOnMenuItemClickListener {
when(it.itemId){
R.id.edit -> { // Edit show
val intent = Intent(context, AddShowActivity::class.java)
intent.putExtra("position", index)
startActivity(context, intent, null)
return#setOnMenuItemClickListener true
}
R.id.delete -> { // Delete show
val repo = ShowRepository()
repo.deleteShow(currentShow)
displayList.remove(currentShow)
notifyItemRemoved(index)
return#setOnMenuItemClickListener true
}
else -> false
}
}
}
}
override fun getItemCount(): Int = displayList.size
// Sorting/Filtering methods
}
The fragment displaying the adapter:
class HomeFragment : Fragment() {
private lateinit var context: MainActivity
private lateinit var verticalRecyclerView: RecyclerView
private lateinit var buttonAddShow: Button
private lateinit var showsAdapter: ShowAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_home, container, false)
context = getContext() as MainActivity
buttonAddShow = view.findViewById(R.id.home_button_add_show)
buttonAddShow.setOnClickListener{ // Starts activity to add a show
startActivity(Intent(context, AddShowActivity::class.java))
}
verticalRecyclerView = view.findViewById(R.id.home_recycler_view)
showsAdapter = ShowAdapter(context, R.layout.item_show, null)
verticalRecyclerView.adapter = showsAdapter
return view
}
}
The MainActivity:
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
loadFragment(HomeFragment())
}
private fun loadFragment(fragment: Fragment){
val repo = ShowRepository()
if(showsListener != null) databaseRef.removeEventListener(showsListener!!)
repo.updateData{
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.fragment_container, fragment)
transaction.addToBackStack(null)
if(supportFragmentManager.isStateSaved)transaction.commitAllowingStateLoss()
else transaction.commit()
}
}
}
The repository:
class ShowRepository {
object Singleton{
val databaseRef = FirebaseDatabase.getInstance().getReference("shows")
val showList = arrayListOf<ShowModel>()
var showsListener: ValueEventListener? = null
}
fun updateData(callback: () -> Unit){
showsListener = databaseRef.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
showList.clear()
for(ds in snapshot.children){
val show = ds.getValue(ShowModel::class.java)
if(show != null) showList.add(show)
}
callback()
}
override fun onCancelled(p0: DatabaseError) { }
})
}
fun insertShow(show: ShowModel){
databaseRef.child(show.id).setValue(show)
}
fun deleteShow(show: ShowModel){
databaseRef.child(show.id).removeValue()
}
}
From what I understand of LiveData and ViewModel, what I should do is creating a ShowViewModel containing a MutableLiveData<List<ShowModel>> containing the shows, and then observe it in my HomeFragment and update the adapter depending on the changes happening. However, everytime I start something to implement it, I encounter a situation where I'm lost and don't know what I should do, which leads me back to square one once again. I've been trying this for more than a week without progressing even a little bit, and that's why I'm here, hoping for some insight.
Sorry for the silly question and the absurd amount of informations, and hoping someone will be able to help me understand what I do wrong/should do.
(this ended up longer than I meant it to be - hope it's not too much! There's a lot to learn, but you don't have to make it super complicated at first)
Broadly, working backwards, it should go like this:
Adapter
displays whatever the Fragment tells it to (some kind of setData function that updates its internal list and refreshes)
passes events to the Fragment (deleteItem(item), showDetails(item) etc.) - don't have the Adapter doing things like starting Activites, that's not its responsibility
Fragment
grabs a reference to any ViewModels (only certain components like Fragments and Activities can actually "own" them)
observes any LiveData (or collects Flows if you're doing it that way) on the VM, and updates stuff in the UI in response
e.g. model.shows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }
handles UI events and calls methods on the VM in response, e.g. click listeners, events from the Adapter
ViewModel
acts as a go-between for the UI (the Fragment) and the data layer (the repository)
exposes methods for handling events like deleting items, interacts with the data layer as required (e.g. calling the appropriate delete function)
exposes data state for the UI to observe, so it can react to changes/updates (e.g. a LiveData containing the current list of shows that the data layer has provided)
That's the basic setup - the VM exposes data which the UI layer observes and reacts to, by displaying it. The UI layer also produces events (usually down to user interaction) which are passed to the VM. You can read more about this general approach in this guide about app architecture - it's worth reading because not only is it recommended as a way to build apps, a lot of the components you use in modern Android are designed with this kind of approach in mind (like the reactive model of wiring stuff up).
You could handle the Adapter events like this:
// in your Adapter
var itemDeletedListener: ((Item) -> Unit)? = null
// when the delete event happens for an item
itemDeletedListener?.invoke(item)
// in your Fragment
adapter.itemDeletedListener = { viewModel.deleteItem(it) }
which is easier than implementing an interface, and lets you wire up your Adapter similar to doing setOnClickListener on a button. Notice we're passing the actual Item object here instead of a list index - generally this is easier to work with, you don't need to maintain multiple copies of a list just so you can look up an index given to you by something else. Passing a unique ID can make sense though, especially if you're working with a database! But usually the object itself is more useful and consistent
The data layer is the tricky bit - the ViewModel needs to communicate with that to get the current state. Say you delete an item - you then need to get the current, updated list of shows. You have three approaches:
Call the delete function, immediately after fetch the current data, and set it on the appropriate LiveData
This can work, but it's not very reactive - you're doing one action, then immediately doing another because you know your data is stale. It would be better if the new data just arrived automatically and you could react to that by pushing it out. The other issue is that calling the delete function might not have an immediate effect - if you fetch the current data, nothing might have changed yet. It's better if the data layer is responsible for announcing updates.
This is the simplest approach though, and probably a good start! You could run this task in a coroutine (viewModelScope.launch { // delete and fetch and update LiveData }) so any slowness doesn't block the current thread.
Have the data layer's functions return the current, updated data that results
Similar to above, you're just sort of pushing the fetching into the data layer. This requires all those functions to be written to return the current state, which could take a while! And depending on what data you want, this might be impossible - if you have an active query on some data, how does the function know what specific data to return?
Make the ViewModel observe the data it wants, so when the data layer updates, you get the results automatically
This is the recommended reactive approach - again it's that two-way idea. The VM calling a function on the data layer is completely separate from the VM receiving new data. One thing just happens as a natural consequence of the other, they don't need to be tied together. You just need to wire them up right!
How do you actually do that though? If you're working with something like Room, that's already baked in. Queries can return async data providers like LiveData or Flows - your VM just needs to observe those and expose the results, or just expose them directly. That way, when a table is updated, any queries (like the current shows) push a new value, and the observers receive it and do whatever they need to do, like telling the Adapter to display the data. It all Just Works once it's wired up.
Since you have your own repo, you need to expose your own data sources. You could have a currentShows LiveData or (probably preferably) the flow equivalent, StateFlow. When the repo initialises, and when any data is changed, it updates that currentShows data. Anything observing that (e.g. the VM, the Fragment through a LiveData/Flow that the VM exposes) will automatically get the new values. So broadly:
// Repo
// this setup is exactly the same as your typical LiveData, except you need an initial value
private val _currentShows = MutableStateFlow<List<Show>>(emptyList()) // or whatever default
val currentShows: StateFlow<List<Show>> = _currentShows
fun deleteItem(item: Item) {
// do the deletion
// get the updated show list
_currentShows.value = updatedShowList
}
// ViewModel
// one way of doing things - you have a lot of options! This literally just exposes
// the state from the data layer, and turns it into a LiveData (if you want that)
val currentShows = repo.currentShows.asLiveData()
// Fragment
// wire things up so you handle new data as it arrives
viewModel.currentShows.observe(viewLifecycleOwner) { shows -> adapter.setData(shows) }
That's basically it. I've skimmed over a lot because honestly, there's a lot to learn with this - especially about Flows and coroutines if you're not already familiar with those. But hopefully that gives you an overview of the general idea, and don't be afraid to take shortcuts (like just updating your data in the ViewModel by setting its LiveData values) while you're learning and getting the hang of it. Definitely give that app architecture guide a read, and also the guides for ViewModels and LiveData. It'll start to click when you get the general idea!
It seems like recommended pattern for fields in viewmodel is:
val selected = MutableLiveData<Item>()
fun select(item: Item) {
selected.value = item
}
(btw, is it correct that the selected field isn't private?)
But what if I don't need to subscribe to the changes in the ViewModel's field. I just need passively pull that value in another fragment.
My project details:
one activity and a bunch of simple fragments replacing each other with the navigation component
ViewModel does the business logic and carries some values from one fragment to another
there is one ViewModel for the activity and the fragments, don't see the point to have more than one ViewModel, as it's the same business flow
I'd prefer to store a value in one fragment and access it in the next one which replaces the current one instead of pass it into a bundle and retrieve again and again manually in each fragment
ViewModel:
private var amount = 0
fun setAmount(value: Int) { amount = value}
fun getAmount() = amount
Fragment1:
bnd.button10.setOnClickListener { viewModel.setAmount(10) }
Fragment2:
if(viewModel.getAmount() < 20) { bnd.textView.text = "less than 20" }
Is this would be a valid approach? Or there is a better one? Or should I just use LiveData or Flow?
Maybe I should use SavedStateHandle? Is it injectable in ViewModel?
To answer your question,
No, It is not mandatory to use LiveData always inside ViewModel, it is just an observable pattern to inform the caller about updates in data.
If you have something which won't be changed frequently and can be accessed by its instance. You can completely ignore wrapping it inside LiveData.
And anyways ViewModel instance will be preserved and so are values inside it.
And regarding private field, MutableLiveData should never be exposed outside the class, as the data flow is always from VM -> View which is beauty of MVVM pattern
private val selected = MutableLiveData<Item>()
val selectedLiveData : LiveData<Item>
get() = selected
fun select(item: Item) {
selected.value = item
}
Hi what is the best way of passing data from a callback function defined in a different class to your activity back to your activity. I am new to android development so sorry if some of this is obvious. I am using an SDK provided by Xsens and a bit of background basically they provide sensors which connect to your device via bluetooth and then stream data back to your device such as acceleration, orientation etc...
The way my code is written is I scan for the sensors, they are then listed on my app and I can press connect on each sensor. When the connected button is clicked the callback class is defined (mine is called ConnectScannedDevice())
Inside this ConnectScannedDevice Class I have overridden the following function and written the below code
override fun onXsensDotDataChanged(address: String, XsensDotData: XsensDotData) {
XsensDotData.acc.forEachIndexed() { index, value ->
Log.d("Sensor Data Acceleration $index", value.toString())
}
XsensDotData.dq.forEachIndexed { index, value ->
Log.d("Sensor Data Orientation $index", value.toString())
}
}
This callback function is hit when I start measuring on the device by using the following code connectedDevice.startMeasuring() this is when the callback function is hit.
I have a setOnClickListener in my activity which then runs the above code to make the device start measuring.
What I now need to do is pass the data the callback function is logging to logcat back to the activity. What is the best way of passing the data the callback function is logging to my activity where the button was pressed.
In the SDK documentation it mentions The XsensDotData object has implemented the Parcelable object from Java, so this object can be passed to another class by Broadcast event.
When the device starts measuring it is a constant stream of data until I stop it from measuring, I need to pass all this data back to the activity. I am trying to display this data onto a graph.
The following is not tested but it outlines the logic of creating a LiveData stream.
In your ConnectScannedDevice class add a private MutableLiveData<XsensDotData> property (that you will update as data changes) and a LiveData<XsensDotData> that you will expose to the ViewModel.
// This is changed internally (never expose a MutableLiveData)
private var xSensorDataMutableLiveData = MutableLiveData<XsensDotData>()
// Changed switchMap() to map()
var xSensorDataLiveData: LiveData<XsensDotData> =
Transformations.map(xSensorDataMutableLiveData) { data ->
data
}
When the data changes you want to update your xSensorMutableDataLiveData in the onXsensDotDataChanged function
override fun onXsensDotDataChanged(address: String, xSensDotData: XsensDotData) {
xSensorDataMutableLiveData.value = XsensDotData
}
Now implement you ViewModel class as follows
// Uncomment if you want to use savedState
//class DeviceDataViewModel(private val savedState: SavedStateHandle): ViewModel() {
class DeviceDataViewModel(): ViewModel() {
// define and initialize a ConnectScannedDevice property
val connectScannedDevice = ConnecScannedDevice() // or however you initialize it
// get a reference to its LiveData
var xSensorDataLiveData = connectScannedDevice.xSensorDataLiveData
}
In your activity get hold of the ViewModel like this
private val deviceDataViewModel by lazy {
ViewModelProvider(this).get(DeviceDataViewModel::class.java)
}
Register your activity to observe the LiveData coming from the ViewModel in the onCreate(Bundle?) function and define how to respond
deviceDataViewModel.xSensorDataLiveData.observe(
this,
Observer { xSensDotData ->
xSensDotData.acc.forEachIndexed() { index, value ->
Log.d("Sensor Data Acceleration $index", value.toString())
}
xSensDotData.dq.forEachIndexed { index, value ->
Log.d("Sensor Data Orientation $index", value.toString())
}
}
)
Note
Google recommends the use of a repository pattern, which means you should add a singleton repository class that does what your ViewModel is currently doing. Your ViewModel should then get hold of the repository instance and simply get its LiveData and pass it on to the activity.
The repository's job is to gather all data from all sources and pass them on to various ViewModels. The ViewModel encapsulates the data needed by activities/fragments and helps make the data survive configuration changes. Activities and fragments get their data from ViewModels and display them on screen.
I have 3 LiveData objects in my ViewModel, I'm applying transformations to these, the problem is 2 LiveData are getting observed while the other one is not, I've tried different solutions like changing the way ViewModel is initialized or the way LiveData is initialized but nothing has worked for me.
class MyClass : ViewModel() {
init {
_originallist.value = Instance.getOrignalList()
}
// observed in Fragment A
val a: LiveData<List<A>> = Transformations.map(_searchText, ::extractA)
// observed in Fragment B
val b: LiveData<List<B>> = Transformations.map(_originallist, ::extractB)
// observed in Fragment C
val c: LiveData<List<C>> = Transformations.map(_originalList, ::extractC)
// Called from Fragment D to change the _searchText liveData
fun setSearchText(text: String) {
_searchText.value = text
}
fun extractA(text: String): List<A> {
val temp = ArrayList<A>()
list.foreach {
if (it.contains(text, false) temp . add (it)
}
return temp
}
fun extractB(list: List<B>): List<B> {
// do something
}
fun extractC(list: List<C>): List<C> {
// do something
}
}
If you have noticed that the LiveData b and c are getting initialized just once hence I'm able to see the data in my RecyclerView, but for the LiveData A, the search text can change based on user input, this is where my fragment is not observing this live data.
Things to note: This is a common ViewModel for my 3 viewPager fragments, LiveData a is observed in one fragment, B in another and C in another.
Eventually, I have to apply the search for other 2 fragments as well.
When I was debugging the observer lines in my fragment was getting skipped, another thing I would like to point out is that the code in all 3 fragments is same except that they are observing different LiveData
EDIT: What i have noticed now is that, since i'm calling the setSearchText() from Fragment D i'm able to observe the changes of LiveData A in Fragment D but i want to observe that in Fragment A but not able to.
I have a search bar in fragment D and bottom of that i have a view pager with 3 fragments, all 4 fragments have a common viewModel, Am i doing something wrong here or is this not the way to implement this?
TIA
Finally found the root cause, the problem was that the viewModel was getting its own lifecycle owner in each of fragment, the solution to this was to declare and initialize the viewModel object in the parent activity of the fragments and use its instace in the fragment to observe the LiveData
The problem is:
Your function extractA in
val a: LiveData<List<A>> = Transformations.map(_searchText, ::extractA)
will only be executed when the value of _searchText will change.
That's how Transformations work, they apply the given function whenever the value changes.
I have a ViewModel which has a property of type LiveData<UserData>, being read from a Room database.
Its code is as follows:
class UserDataViewModel(application: Application) : AndroidViewModel(application) {
private val userDataDao: UserDataDao = AppDatabase.getInstance(application).dao()
val userData: LiveData<UserData?> = userDataDao.getUserData()
}
In the associated activity, I get a reference to the view model:
private val viewModel: UserDataViewModel by viewModels()
In that activity, I need to get the value of the UserData on a button click:
private fun handleClick(view: View) {
viewModel.userData.value?.let {
// do stuff if the userData is present
}
}
Now in theory, unless the user presses the button before the data has been loaded, this should never be null.
However, as the code stands, the call to viewModel.userData.value is always null and the let block never executes.
But, if I add this statement in onCreate, the let block in the click handler executes as desired:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.userData.observe(this, Observer {
// do nothing
})
}
My question is: why do I need to call the observe function, even if I'm doing nothing with a change event, to get valid responses from LiveData::getValue?
My question is: why do I need to call the observe function, even if I'm doing nothing with a change event, to get valid responses from LiveData::getValue?
Because the ComputableLiveData returned from the Room DAO only executes the query if the LiveData has at least one active observer (inside LiveData.onActive()). Then it runs asynchronously on a different thread, and at some point in the future it will be posted into the LiveData.
You do not need to call observe() in order to get a LiveData to give up a value other than null. LiveData always contains and yields null initially until something sets its value. If you don't want this initial null value, then you should immediately set it to something else instead, before making the LiveData available to any other components. If you want to know when it first contains a non-null value, you will need to use an observer.