Android 使用列值-Room从文件室检索数据

Android 使用列值-Room从文件室检索数据,android,android-room,viewmodel,Android,Android Room,Viewmodel,我的房间里有两张桌子——事件和笔记。对于我在RecycleView中显示的每个事件,我都有一个链接,可以为该事件启动一个注释。第一次单击-创建注释。在第二次单击注释时,我希望检索上一个注释,然后进行编辑。此外,我正在使用相同的活动通过传递适当的值来编辑/创建新的注释,该值有效,但使用了已打包的注释 对于编辑现有事件注释,我使用putExtra方法发送事件ID(也存储在注释表中,而不是作为外键)。下面的DB结构(assocId指eventId) 视图模型 fun setNotesByAss

我的房间里有两张桌子——事件和笔记。对于我在RecycleView中显示的每个事件,我都有一个链接,可以为该事件启动一个注释。第一次单击-创建注释。在第二次单击注释时,我希望检索上一个注释,然后进行编辑。此外,我正在使用相同的活动通过传递适当的值来编辑/创建新的注释,该值有效,但使用了已打包的注释

对于编辑现有事件注释,我使用putExtra方法发送事件ID(也存储在注释表中,而不是作为外键)。下面的DB结构(assocId指eventId)

视图模型

    fun setNotesByAssocEventId(assocEventId: String): Note {
    return dao.getByAssocEventId(assocEventId)
}
    class NotesViewModel(application: Application) : AndroidViewModel(application) {
    private val context = getApplication<Application>().applicationContext
    private val listNotes = MutableLiveData<ArrayList<Note>>()
    private var dao: NoteDao

    init {
        val database = AppDatabase.getDatabase(context)
        dao = database.getNoteDao()
    }

    fun setNotes() {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getAll())
        listNotes.postValue(listItems)
    }

    fun setNotesByType(label: String) {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getByLabel(label))
        listNotes.postValue(listItems)
    }

    fun setNotesByTitle(title: String) {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getByTitle(title))
        listNotes.postValue(listItems)
    }

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

    fun insertNote(note: Note) {
        dao.insert(note)
    }

    fun updateNote(note: Note) {
        dao.update(note)
    }

    fun deleteNote(note: Note) {
        dao.delete(note)
    }

    fun getNotes(): LiveData<ArrayList<Note>> {
        return listNotes
    }

}

票据实体

@Entity(tableName = "notes")
        @Parcelize
data class Note(
    //PrimaryKey annotation to declare primary key with auto increment value
    //ColumnInfo annotation to specify the column's name
    @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 = ""
) : Parcelable
我正在使用以下代码编辑/创建新注释。而我能够创建/编辑注释。我无法使用eventId检索特定事件的节点。我得到的一个错误是,在分配从ViewModel返回的Note对象时,Note对象尚未初始化。可能是什么问题

assocID是使用putExtra获得的事件ID,将检索相应的事件注释

private lateinit var binding: ActivityEditNoteBinding
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

    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)
        ) {

        }

}
私有lateinit变量绑定:ActivityEditNoteBinding
私有lateinit变量notesViewModel:notesViewModel
私有lateinit变量注释:注释
私有变量关联:字符串?=""
私有变量isUpdate=false
private val dateChange=dateChange()
var拒绝:数据库引用?=无效的
var firebaseUser:firebaseUser?=无效的
重写创建时的乐趣(savedInstanceState:Bundle?){
super.onCreate(savedInstanceState)
绑定=ActivityEditNoteBinding.充气(LayoutFlater)
setContentView(binding.root)
assocId=intent.getStringExtra(“eventId”).toString()
initView()
initListener()
}
私有视图(){
firebaseUser=FirebaseAuth.getInstance().currentUser
initViewModel()
if(assocId!=null){
findViewById(R.id.editNote).text=“编辑事件注释”
Toast.makeText(这个“EvetnId received”,Toast.LENGTH\u SHORT.show()
isUpdate=true
binding.editNoteDelete.visibility=View.VISIBLE
notesViewModel.getNotes()
note=notesViewModel.setnotesbyasoceventId(“%${assocId}%”)
binding.editTextTitle.setText(note.title)
binding.editTextBody.setText(note.body)
binding.editTextTitle.setSelection(note.title.length)
//设置微调器位置
val compareValue=note.label
val adapter=ArrayAdapter.createFromResource(
这个,R.array.NoteSpinnerVals,
android.R.layout.simple\u微调器\u项目
)
adapter.setDropDownViewResource(android.R.layout.simple\u微调器\u下拉菜单\u项)
binding.spLabel.adapter=适配器
val喷丝头位置=适配器.getPosition(比较值)
装订.标签.设置选择(喷丝头位置)
}
}
私有视图模型(){
notesViewModel=ViewModelProvider(this.get)(notesViewModel::class.java)
}
private fun initListener(){
//binding.editNoteBack.setOnClickListener(此)
binding.editNoteSave.setOnClickListener(此)
binding.editNoteDelete.setOnClickListener(此)
}
私人注(注:注){
notesViewModel.deleteNote(注)
Toast.makeText(this@EditNote,“删除注释”,Toast.LENGTH\u SHORT.show()
}
私人娱乐节目对话(){
AwesomeDialog.build(此)
.position(AwesomeDialog.POSITIONS.CENTER)
.title(“删除注释?”)
.图标(R.drawable.ic\u delete\u黑色)
.background(R.drawable.background\u对话框)
.正(
“是,删除”,
buttonBackgroundColor=R.drawable.button_bg,
textColor=ContextCompat.getColor(this,R.color.white)
) {
删除注释(注释)
val intent=intent(这是MainActivity::class.java)
星触觉(意图)
完成()
}
非负性(
“取消”,
buttonBackgroundColor=R.drawable.button_bg,
textColor=ContextCompat.getColor(this,R.color.white)
) {
}
}
ViewModel的代码

    class NotesViewModel(application: Application) : AndroidViewModel(application) {
    private val context = getApplication<Application>().applicationContext
    private val listNotes = MutableLiveData<ArrayList<Note>>()
    private var dao: NoteDao

    init {
        val database = AppDatabase.getDatabase(context)
        dao = database.getNoteDao()
    }

    fun setNotes() {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getAll())
        listNotes.postValue(listItems)
    }

    fun setNotesByType(label: String) {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getByLabel(label))
        listNotes.postValue(listItems)
    }

    fun setNotesByTitle(title: String) {
        val listItems = arrayListOf<Note>()

        listItems.addAll(dao.getByTitle(title))
        listNotes.postValue(listItems)
    }

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

    fun insertNote(note: Note) {
        dao.insert(note)
    }

    fun updateNote(note: Note) {
        dao.update(note)
    }

    fun deleteNote(note: Note) {
        dao.delete(note)
    }

    fun getNotes(): LiveData<ArrayList<Note>> {
        return listNotes
    }

}
class NotesViewModel(应用程序:应用程序):AndroidViewModel(应用程序){
private val context=getApplication().applicationContext
private val listNotes=MutableLiveData()
私有var-dao:NoteDao
初始化{
val database=AppDatabase.getDatabase(上下文)
dao=database.getNoteDao()
}
趣味笔记(){
val listItems=arrayListOf()
listItems.addAll(dao.getAll())
listNotes.postValue(listItems)
}
fun setNotesByType(标签:字符串){
val listItems=arrayListOf()
listItems.addAll(dao.getByLabel(标签))
listNotes.postValue(listItems)
}
趣味setNotesByTitle(标题:字符串){
val listItems=arrayListOf()
listItems.addAll(dao.getByTitle(title))
listNotes.postValue(listItems)
}
fun setNotesByAsocEventId(associvented:String):注意{
return dao.getbyassociventid(associventid)
}
趣味插页(注:注){
dao.插入(注)
}
fun updateNote(注:注){
dao.update(注)
}
注意事项(注意事项:注意事项){
删除(注)
}
fun getNotes():LiveData{
返回列表注释
}
}

DAO中的方法需要稍微更改

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

@Query("SELECT * FROM notes WHERE assocEventId LIKE :assocEventId")
    fun getByAssocEventId(assocEventId: String): LiveData<List<Note>>
视图模型

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

你能添加你的ViewModel代码吗Hi Rahat,我已经添加了ViewModel代码…这里你得到null
note=notesViewModel.setnotesbyasoceventId(“%${assocId}%”)
?是的,这就是我得到null的地方为什么你在
“%${assocId}%”中使用
%
fun setNotesByAssocEventId(assocEventId: String): LiveData<Note>{
     return dao.getByAssocEventId(assocEventId)
   }
notesViewModel.setNotesByAssocEventId("%${assocId}%").observe(this, {
   if(it!=null){
     //if you using for single note only
   }

   //if(it.isNotEmpty()){
     //if you using for list
   //}
})