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

android - How to Load Sqlite data in recycler view using kotlin with Room?

Iam working on a project where I have to load Sqlite data in recycler view and I'm using ROOM for this.Following is my adapter code :-

package com.example.demorecyclerview.adapter
import android.os.AsyncTask
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import androidx.room.Room
import com.example.demorecyclerview.MainActivity
import com.example.demorecyclerview.R
import com.example.demorecyclerview.database.contactDatabase
import com.example.demorecyclerview.entity.Contact
import java.lang.Exception
import java.lang.ref.WeakReference


class ContactAdapter() :
        RecyclerView.Adapter<ContactAdapter.ViewHolder>() {

    /**
     * Provide a reference to the type of views that you are using
     * (custom ViewHolder).
     */
         ContactAdapter.Companion.insertContactAsyncTask(this)

    private val name= arrayOf("abc","xyz","pqr")
    private val numbers= arrayOf("123","456","789")

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        var nameTextView:TextView=view.findViewById(R.id.textViewName)
        var mobTextView:TextView=view.findViewById(R.id.textViewMobile)
//        val textView: TextView
//
//        init {
//            // Define click listener for the ViewHolder's View.
//            textView = view.findViewById(R.id.textView)
//        }
    }

    // Create new views (invoked by the layout manager)
    override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): ViewHolder {

        val view = LayoutInflater.from(viewGroup.context)
                .inflate(R.layout.card_contacts, viewGroup, false)

        return ViewHolder(view)
    }

    // Replace the contents of a view (invoked by the layout manager)
    override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

        // Get element from your dataset at this position and replace the
        // contents of the view with that element
      viewHolder.nameTextView.text=name[position]
        viewHolder.mobTextView.text=numbers[position]
    }

    // Return the size of your dataset (invoked by the layout manager)
    override fun getItemCount() = name.size


    companion object {
        class insertContactAsyncTask internal constructor(context: ContactAdapter) : 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 ""
            }

//            override fun onPostExecute(result: String?) {
//               return result
//
//            }
        }

    }

}

As it is a normal class, so what should I pass as context in Room.databaseBuilder().When I'm calling ContactAdapter.Companion.insertContactAsyncTask(this) it shows error "Expecting Member Declaration".Please help me resolving this.Thanks in advance....

question from:https://stackoverflow.com/questions/65643178/how-to-load-sqlite-data-in-recycler-view-using-kotlin-with-room

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

1 Answer

0 votes
by (71.8m points)

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 ""
        }
    }
}

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

...