I'm getting two errors in my code. One is at the private val sharedView model, I keep getting an "Classifier 'SharedViewModel' does not have a companion object, and thus must be initialized here". Lastly, in both the lines of question.text = sharedViewmodel.question and question.text = sharedViewModel.answer I'm getting an "Type mismatch.
Required:
Editable!
Found:
String?" but when I try to change it to editable I then get an error below my button click listener for question/answer.text.toString(). Does anyone have any idea how to fix these? Here's my code:
package com.example.quest
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.preference.PreferenceManager
import com.google.android.material.floatingactionbutton.FloatingActionButton
class SecondActivity : AppCompatActivity() {
private val sharedViewModel: SharedViewModel by viewModels(SharedViewModel)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
val question = findViewById<EditText>(R.id.question)
val answer = findViewById<EditText>(R.id.answer)
if(sharedViewModel.question != null) {
question.text = sharedViewModel.question
}
if(sharedViewModel.answer != null) {
answer.text = sharedViewModel.answer
}
findViewById<FloatingActionButton>(R.id.btn3).setOnClickListener {
sharedViewModel.question = question.text.toString()
sharedViewModel.answer = answer.text.toString()
val questiontext = question.text.toString()
val answertext = answer.text.toString()
val returnIntent = Intent()
returnIntent.putExtra("test", questiontext)
returnIntent.putExtra("test2", answertext)
setResult(Activity.RESULT_OK, returnIntent)
finish()
}
}
}
Viewmodel:
package com.example.quest
import androidx.lifecycle.ViewModel
class SharedViewModel : ViewModel() {
var question: String ?= null
var answer: String ?= null
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…