JoeHz
JoeHz

Reputation: 2196

Using an ArrayAdapter with LiveData.

I'm familiar with MVVM in WPF, but am in the process of porting an existing Android app to make use of a ViewModel class and LiveData for the first time.

The app "as/was" has a custom ArrayAdapter that is used to correctly display the items contained in a List in a gridview. The code that does that looks essentially like this ("essentially" because there are actually 4 such grids in the activity that all do it like this):

ArrayAdapter<String> playerAdapter = new MyAdapter<String>(this, R.layout.grid_item, playerList);

gridView.setAdapter(playerAdapter)

and when the playerList contents changed, there was an explicit call to

playerAdapter.notifyDataSetChanged()

Since my goal is to have the grid respond automatically when the playerList changes, and never have to notify anything, it seems now that the "playerList" needs to become a MutableLiveData<List<String>>.

I suspect I am going to have a problem though-

The MyAdapter class extends ArrayAdapter<T>

So in practice it's going to become an

ArrayAdapter<MutableLiveData<List<String>>>

But a MutableLiveData isn't going to work there, right?

I could unwrap it and make the call to create it look like this:

ArrayAdapter<String> playerAdapter = 
new MyAdapter<String>(this, R.layout.grid_item, playerList.getValue());

Is this correct? It seems the way of madness.

Ultimately my goal is to just assign the gridView's android:adapter property to this thing in xml and never have to think about it anymore (beyond the required calls to setvalue() and postValue() when I modify the underlying list...which I'm not even sure how would work here.

I would hope there's already a MutableLiveData Collection that's ready to go somewhere and I'd use that.

What the standard way to do this?

Upvotes: 4

Views: 4588

Answers (1)

Prashanth Verma
Prashanth Verma

Reputation: 588

I believe the way you are thinking is wrong. Don't worry about this:

ArrayAdapter<MutableLiveData<List<String>>>

You will get a list thats all. MutableLiveData is to set a livedata object like setValue() or postValue() manually. Just set your below code whenever liveData gets triggered and gives you the new playerList, something like this:

viewModel.getPlayListObservable().observe(this, new Observer<List<String>>() {
        @Override
        public void onChanged(List<String> playerList) {
            ArrayAdapter<String> playerAdapter = new MyAdapter<String>(this, R.layout.grid_item, playerList);
            gridView.setAdapter(playerAdapter);
            playerAdapter.notifydataChanged();
        }
    });

Upvotes: 4

Related Questions