You are placing ContactAdapter.Companion.insertContactAsyncTask(this)
on a class level. On a class level, you can only declare the class's fields or methods, you can't execute code there. So you have to declare it, not create an object:
class ContactAdapter() :
RecyclerView.Adapter<ContactAdapter.ViewHolder>() {
private val getContacts = ContactAdapter.Companion.insertContactAsyncTask(this)
......
}
Then you have to execute your async task in places you want it to be executed from. Here for example it executes in a constructor:
constructor {
getContacts.execute()
}
As for the context of Room.databaseBuilder()
, it is not ContactAdapter
. It is the class Context
from android.content
package. Given your code one way to pass it to insertContactAsyncTask
is to add an argument of type Context
to your ContactAdapter
, then pass this argument to insertContactAsyncTask
. Here is an example:
class ContactAdapter(val context: Context) :
RecyclerView.Adapter<ContactAdapter.ViewHolder>() {
private val getContacts = ContactAdapter.Companion.insertContactAsyncTask(context)
......
companion object {
class insertContactAsyncTask internal constructor(context: Context) : AsyncTask<Int, String, String?>() {
var res:Long = 0;
var context=context
private val activityReference: WeakReference<ContactAdapter> = WeakReference(context)
override fun doInBackground(vararg params: Int?): String? {
try{
val db = Room.databaseBuilder(
context,
contactDatabase::class.java, "quest_contacts"
).build()
val contacts:List<Contact> = db.contactDao().getAllContacts()
Log.d("Results","$contacts")
return contacts.toString()
}
catch(e: Exception)
{
Log.e("Exception","$e")
}
return ""
}
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…