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
1.3k views
in Technique[技术] by (71.8m points)

kotlin - Retrieving object from Room Database

I have two tables in my Room DB - Events and Notes. I an trying to retrieve the Note object using the EventId associated with that event. I am using a ViewModel as well but I am unable to get the already created Note object to edit/Delete/Update it for that event.

One of the errors I am getting is Note object has not been initialized when I am assigning the note object the object returned from the ViewModel. What am I doing wrong here?

  private lateinit var binding: ActivityEditNoteBinding
val editNoteExtra = "edit_note_extra"
private lateinit var notesViewModel: NotesViewModel
private lateinit var note: Note
private var assocId: String? = ""
private var isUpdate = false
private val dateChange = DateChange()

var refUsers: DatabaseReference? = null
var firebaseUser: FirebaseUser? = null

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    binding = ActivityEditNoteBinding.inflate(layoutInflater)
    setContentView(binding.root)
    assocId = intent.getStringExtra("eventId").toString()

    initView()
    initListener()
}

private fun initView() {

    firebaseUser = FirebaseAuth.getInstance().currentUser

    if (intent.getParcelableExtra<Note>(editNoteExtra) != null) {

        isUpdate = true
        binding.editNoteDelete.visibility = View.VISIBLE
        note = intent.getParcelableExtra(editNoteExtra)!!
        binding.editTextTitle.setText(note.title)
        binding.editTextBody.setText(note.body)
        binding.editTextTitle.setSelection(note.title.length)

        //set spinner position
        val compareValue = note.label
        val adapter = ArrayAdapter.createFromResource(
            this, R.array.NoteSpinnerVals,
            android.R.layout.simple_spinner_item
        )

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spLabel.adapter = adapter
        val spinnerPosition = adapter.getPosition(compareValue)
        binding.spLabel.setSelection(spinnerPosition)
    }

    initViewModel()

    if (assocId != null) {
        findViewById<TextView>(R.id.editNote).text = "Edit Event Note"
        Toast.makeText(this, "EvetnId received", Toast.LENGTH_SHORT).show()
        isUpdate = true
        binding.editNoteDelete.visibility = View.VISIBLE
        notesViewModel.getNotes()
        note = notesViewModel.setNotesByAssocEventId("%${assocId}%")
        binding.editTextTitle.setText(note.title)
        binding.editTextBody.setText(note.body)
        binding.editTextTitle.setSelection(note.title.length)

        //set spinner position
        val compareValue = note.label
        val adapter = ArrayAdapter.createFromResource(
            this, R.array.NoteSpinnerVals,
            android.R.layout.simple_spinner_item
        )

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        binding.spLabel.adapter = adapter
        val spinnerPosition = adapter.getPosition(compareValue)
        binding.spLabel.setSelection(spinnerPosition)

    }

}

private fun initViewModel() {
    notesViewModel = ViewModelProvider(this).get(NotesViewModel::class.java)
}


private fun initListener() {
  //  binding.editNoteBack.setOnClickListener(this)
    binding.editNoteSave.setOnClickListener(this)
    binding.editNoteDelete.setOnClickListener(this)
}

private fun deleteNote(note: Note) {
    notesViewModel.deleteNote(note)
    Toast.makeText(this@EditNote, "Note removed", Toast.LENGTH_SHORT).show()
}

private fun showDialog() {

    AwesomeDialog.build(this)
        .position(AwesomeDialog.POSITIONS.CENTER)
        .title("Delete the note?")
        .icon(R.drawable.ic_delete_black)
        .background(R.drawable.background_dialog)
        .onPositive(
            "Yes, delete",
            buttonBackgroundColor = R.drawable.button_bg,
            textColor = ContextCompat.getColor(this, R.color.white)
        ) {
            deleteNote(note)
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
            finish()
        }
        .onNegative(
            "Cancel",
            buttonBackgroundColor = R.drawable.button_bg,
            textColor = ContextCompat.getColor(this, R.color.white)
        ) {

        }

}

ViewModel

    fun setNotesByAssocEventId(assocEventId: String): Note {
    return dao.getByAssocEventId(assocEventId)
}

DAO

    @Query("SELECT * FROM notes WHERE assocEventId = :assocEventId")
    fun getByAssocEventId(assocEventId: String): Note

NoteEntity

    @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0,
    @ColumnInfo(name = "assocEventId") var assocEventId: String = "",
    @ColumnInfo(name = "title") var title: String = "",
    @ColumnInfo(name = "label") var label: String = "",
    @ColumnInfo(name = "date") var date: String = "",
    @ColumnInfo(name = "time") var time: String = "",
    @ColumnInfo(name = "updatedDate") var updatedDate: String = "",
    @ColumnInfo(name = "updatedTime") var updatedTime: String = "",
    @ColumnInfo(name = "body") var body: String = ""
question from:https://stackoverflow.com/questions/65862428/retrieving-object-from-room-database

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

1 Answer

0 votes
by (71.8m points)
Waitting for answers

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

...