Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
723 views
in Technique[技术] by (71.8m points)

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

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
    }
}
question from:https://stackoverflow.com/questions/50923273/livedata-cannot-assign-to-value-the-setter-is-protected-protected-and-packa

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...