简体   繁体   中英

How to use data from onActivityResult in MVVM architecture?

How to use data from onActivityResult in MVVM architecture? I need to add an item to the RecyclerView that is subscribed to receive data from the ViewModel. How can I send data from onActivityResult to the ViewModel class and then update my list? If I add data to the adapter immediately from the onactivityresult method, nothing happens. I need any help on this issue

Activity class:

class ContactsActivity : AppCompatActivity(), ContactsListener {
    private val TAG = "ContactsActivity"

    @Inject
    lateinit var factory: ViewModelProvider.Factory
    lateinit var contactsViewModel: ContactsViewModel


    companion object {
        const val ADD_CONTACT_REQUEST = 200
    }

    private lateinit var mAdapter: ContactsAdapter

    @SuppressLint("WrongConstant")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        toolbar_contacts.title = getString(R.string.contacts_toolbar_title)

        add_new_contact_btn.setOnClickListener {
            val intent = Intent(this@ContactsActivity, AddContactActivity::class.java)
            startActivityForResult(intent, ADD_CONTACT_REQUEST)
        }

        DaggerContactsActivity_ContactsComponent.create().inject(this@ContactsActivity)
        contactsViewModel = ViewModelProviders.of(this@ContactsActivity, factory).get(ContactsViewModel::class.java)
        contactsViewModel.getContactsList().observe(this@ContactsActivity, Observer {

            mAdapter = ContactsAdapter(this@ContactsActivity, it)
            recycler_contacts.layoutManager =
                LinearLayoutManager(applicationContext, OrientationHelper.VERTICAL, false)
            recycler_contacts.adapter = mAdapter
            recycler_contacts.setHasFixedSize(true)

            mAdapter.sortByName()

        })
    }

    // Dagger create
    @Component (modules = [ContactsModule::class])
    interface ContactsComponent {

        fun inject (activity: ContactsActivity)
    }

    @Module
    abstract class ContactsModule {

        @Binds
    abstract fun bindViewModelFactory(factory: ContactsViewModelFactory): ViewModelProvider.Factory
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
            if (resultCode == ADD_CONTACT_REQUEST && resultCode == RESULT_OK) {
                val firstName: String? = data?.getStringExtra(AddContactActivity.EXTRA_FIRST_NAME)
                val lastName: String? = data?.getStringExtra(AddContactActivity.EXTRA_LAST_NAME)
                val phone: String? = data?.getStringExtra(AddContactActivity.EXTRA_PHONE)
                val email: String? = data?.getStringExtra(AddContactActivity.EXTRA_EMAIL)
                val notes: String? = data?.getStringExtra(AddContactActivity.EXTRA_NOTES)

                val contacts = Contacts(firstName = firstName.toString(), lastName = lastName.toString(), phone = phone.toString(),
                    email = email.toString(), notes = notes.toString(), images = "")

                contactsViewModel.get(contacts = contacts)
            }
        }

    override fun setupContactsList(contactsList: ArrayList<Contacts>) {

        mAdapter.setupContacts(contactsList = contactsList)
    }
}

IN MVVM Architecture, you don't need to exchange data using Activity's onActivityResult. Instead, let target Activity's UI bind to ViewModel's LiveData which further points to same data source (eg sqLite) that is updated by another activity (via its own ViewModel).

MVVM enables two way binding. Just update the list when you are finishing or clearing the activity whose onActivity result you have overriden.

The data is already subscribed in your previous activity and it will get the update as soon as the other activity updates the list. The ViewModel would be shared between both the activities.

Take a look at the working of MVVM with shared instance : https://www.google.com/url?sa=t&source=web&rct=j&url=https://github.com/android/architecture-components-samples/issues/29&ved=2ahUKEwjn0ZWEzvPmAhUxzDgGHXhuBUsQFjAAegQICRAE&usg=AOvVaw36xQIOfJIp4abIODjXrz6S

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM