android – LiveData. Cannot assign to ‘value’: the setter is protected/*protected and package*/ for synthetic extension-ThrowExceptions

Exception or error:

I’m trying to implement a DB Observer with LiveData as described in the android documentation.

As long as I’m programming in Kotlin I’m adapting the functions (originally written in Java) to it.

When trying to save the data I find this problem.

Cannot assign to ‘value’: the setter is protected/*protected and package*/ for synthetic extension in ‘<library Grade: android.arch.livecycle:livedata-core-1.1.1>’

Did anyone have this problem already?

This is my code:

ViewModel:

class ProfileViewModel: ViewModel() {

    object FirstName: MutableLiveData<String>()

    fun getCurrentName(): LiveData<String> {
        return FirstName
    }
}

Fragment

class ProfileFragment{

    private lateinit var model: ProfileViewModel

    // this is called onViewCreated. inputFirstName is an Edittext.
    override fun setUp() {
        model = ViewModelProviders.of(this).get(ProfileViewModel::class.java)

        val nameObserver = Observer<String> { firstName ->
            inputFirstName.text = SpannableStringBuilder(firstName)
        }

        model.getCurrentName().observe(this, nameObserver)
    }

    fun saveProfileData() {
        val firstName = inputFirstName.text.toString()
        model.getCurrentName().value = firstName
    }
}
How to solve:

As @spkink suggested:

replace

fun getCurrentName(): LiveData<String>

with

fun getCurrentName(): MutableLiveData<String>

The error is caused because setValue(T value) is protected in LiveData (so you cannot call it) while it is public in MutableLiveData.

Leave a Reply

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