I’m trying to setup a simple database and part of my code is throwing off this error, which im not really sure of how to fix, the line in particular is the following:
NotesDatabase.getDatabase(getDatabase(applicationContext).noteDao().insertNote(note))
Which yields: Type Mismatch, Required: Context, Found: unit!
What should I do to fix this?
Whole code:
package com.example.notas.activities import android.os.AsyncTask import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.ImageView import android.widget.TextView import android.widget.Toast import com.example.notas.R import com.example.notas.database.NotesDatabase import com.example.notas.database.NotesDatabase.getDatabase import com.example.notas.entities.Note import java.text.SimpleDateFormat import java.util.* class CreateNoteActivity : AppCompatActivity() { lateinit var inputNoteTitle: EditText lateinit var inputNoteSubtitle: EditText lateinit var inputNoteText: EditText lateinit var textDateTime: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_create_note) val imageBack: ImageView = findViewById(R.id.imageBack) imageBack.setOnClickListener(View.OnClickListener { onBackPressed() }) inputNoteTitle = findViewById(R.id.inputNoteTitle) inputNoteSubtitle = findViewById(R.id.inputNoteSubtitle) inputNoteText = findViewById(R.id.inputNote) textDateTime = findViewById(R.id.textDateTime) textDateTime.setText( SimpleDateFormat("EEEE, dd, MMMM yyyy HM:mm a", Locale.getDefault()).format(Date()) ); } fun saveNote() { if (inputNoteTitle.text.toString().trim().isEmpty()) { Toast.makeText(this, "Note title can't be empty!", Toast.LENGTH_SHORT).show() return } else if (inputNoteSubtitle.text.toString().trim().isEmpty() && inputNoteText.text.toString().trim().isEmpty() ) { Toast.makeText(this, "Note can't be empty!", Toast.LENGTH_SHORT).show() return } val note: Note = Note() note.title = inputNoteTitle.text.toString() note.subtitle = inputNoteSubtitle.text.toString() note.noteText = inputNoteText.text.toString() note.dateTime = textDateTime.text.toString() class SaveNoteTask : AsyncTask<Void?, Void?, Void?>() { override fun doInBackground(vararg voids: Void?): Void? { NotesDatabase.getDatabase(getDatabase(applicationContext).noteDao().insertNote(note)) return null } override fun onPostExecute(result: Void?) { super.onPostExecute(result) } }
Advertisement
Answer
As per your error, the method needs context and you are passing a method to it. Try to pass context as below –
NotesDatabase.getDatabase(applicationContext)