Comunicate from activity 2 to activity 1 and update a List

My scenario is I have a List<Object> and I have the detail Activity where I can edit / delete, I’m wondering if is there any other way that I’m doing.

I’m passing from the adapter an intent where I pass the position of that object, and the Object itself, on Activity2 I do stuff and when I press delete or edit I send an intent with that action and the object and the position of the array, can you tell to me another way to do that efficient?

I thought a static List but I do not like static stuff to be honest…

Without DB stuff

Answer

The good way will be to use some local database like Realm or ROOM. Then you won’t pass whole object via Intent.

In Acitivity1 you load list of objects from local database. When users clicks on item, you pass itemId to Activity2 via bundle.

Then in Activity2 you can find item in local databse by id, then edit what you want, and save changes in database.

After returning to Activity1 you can reload list from database.

UPDATE

If you don’t want to play with local databases, then read about MVVM pattern + Data Binding.

In MVVM you have ViewModel which keeps your data, like List<Object>.

Thanks to DataBinding you can bind your list with adapter. And then all changes made on list will be instant visible in UI.

This is how it looks in Kotlin:

Binding list of objects with adapter:

@BindingAdapter("contractorItems")
fun setContractors(recyclerView: RecyclerView, items: List<Contractor>) {
    with(recyclerView.adapter as ContractorAdapter) {
        replaceData(items)
    }
}

Binding setContractors method with RecyclerView

<android.support.v7.widget.RecyclerView
    android:id="@+id/contractors_recyclerView"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:layout_marginEnd="16dp"
    android:layout_marginStart="16dp"
    app:contractorItems="@{viewmodel.contractors}"
    tools:listitem="@layout/contractor_signature_item" />

ViewModel:

class ContractorsViewModel: ViewModel() {

    val contractors = ObservableArrayList<Contractor>()

}

Leave a Reply

Your email address will not be published. Required fields are marked *