简体   繁体   English

RecyclerView Kotlin 不显示内容

[英]RecyclerView Kotlin not displaying content

I am reading contacts stored in the Room database and displaying it in a recyclerView.我正在读取存储在 Room 数据库中的联系人并将其显示在 recyclerView 中。 Also, using nbested recyclerView.此外,使用 nbested recyclerView。 But having spent a lot of time on this I do not understand why the recyclerview does not load... nor do any Toast messages are displayed (which are present in the activity).但是在这上面花了很多时间我不明白为什么 recyclerview 没有加载......也没有显示任何 Toast 消息(这些消息存在于活动中)。 I have shared below the Activity/Adapter and layout code... any thoughts would be helpful...我在活动/适配器和布局代码下面分享了...任何想法都会有所帮助...

Activity活动

 private lateinit var progressBar: ProgressDialog
var firebaseUser: FirebaseUser? = null //the used id of the user using the app
var managecontactsadapter: ManageContactsAdapter? = null
var reference: DatabaseReference? = null
var rvCRM: RecyclerView? = null
private val _contsCRMLiveData = MutableLiveData<ArrayList<Contact>>()
private val crmContactsLiveData: LiveData<ArrayList<Contact>> = _contsCRMLiveData

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_manage_contacts)
    setSupportActionBar(toolbar_contacts)
    supportActionBar!!.title = ""
    supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    //Progress Bar
    progressBar = ProgressDialog(this)
    progressBar.setCancelable(false)
    progressBar.setMessage("Loading...")

    rvCRM = findViewById(R.id.rvCRM)
    rvCRM!!.setHasFixedSize(true)
    rvCRM!!.layoutManager = LinearLayoutManager(this)
    displayContacts()
    crmContactsLiveData.observe(this, Observer {
       rvCRM!!.adapter = managecontactsadapter
    })
    Toast.makeText(this, "Adapter Called.", Toast.LENGTH_SHORT).show()
    contact_fab.setOnClickListener {
        val intent = Intent(this, EditContact::class.java)
        intent.putExtra("Edit", false)
        this.startActivity(intent)
    }

    contSort.setOnClickListener {

    }

    contFilter.setOnClickListener {

    }
}

//Top Right Menu
override fun onCreateOptionsMenu(menu: Menu): Boolean {
    // Inflate the menu; this adds items to the action bar if it is present.
    menuInflater.inflate(R.menu.menu_main, menu)
    return true
}

//Top Right Menu Options Selected Actions
override fun onOptionsItemSelected(item: MenuItem): Boolean {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    when (item.itemId) {
        R.id.action_settings -> {
            val intent = Intent(this@ManageContacts, SettingsActivity::class.java)
            startActivity(intent)
            return true
        }
        R.id.Logout -> {

            //Google Sign Out
            progressBar.show()
            val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build()
            val mGoogleSignInClient = GoogleSignIn.getClient(this, gso)

            mGoogleSignInClient.revokeAccess()
                .addOnCompleteListener(this) {
                    mGoogleSignInClient.signOut()
                        .addOnCompleteListener(this) { progressBar.dismiss();finish() }
                }

            //Firebase sign Out
            FirebaseAuth.getInstance().signOut()
            val intent = Intent(this@ManageContacts, IntroScreensHome::class.java)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
            startActivity(intent)
            finish()
            return true
        }
    }
    return false
}

private fun displayContacts() {

    val mupdateList = ArrayList<Contact>()
    lateinit var contact : List<Contact>
    val db = AppDatabase.getDatabase(this)
    db.contactsDao().getcrmContacts().observe(this, Observer {
        contact = it
    

    mupdateList.clear()
            for (i in contact) {
                mupdateList.add(i)
            }
        })
        val size = mupdateList.size
        Toast.makeText(this, "Display Called.", Toast.LENGTH_SHORT).show()
        managecontactsadapter = ManageContactsAdapter(this, mupdateList)
        rvCRM!!.adapter = managecontactsadapter
    }

}

Adapter适配器

class ManageContactsAdapter(
mContext: Context,
mupdateList: ArrayList<Contact>
) : RecyclerView.Adapter<ManageContactsAdapter.MyViewHolder?>() {
    private val layoutInflater = mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    private val mContext: Context
    private val mupdateList: List<Contact>

init {
    this.mContext = mContext
    this.mupdateList = mupdateList
}

class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var contLabel: TextView? = null
    var ContactName: TextView? = null
    var ContactDetails: LinearLayout? = null
    private var ContactProfileImage: ShapeableImageView

    init {
        contLabel = itemView.findViewById(R.id.contLabel)
        ContactProfileImage = itemView.findViewById(R.id.ContactProfileImage)
        ContactName = itemView.findViewById(R.id.ContactName)
        ContactDetails = itemView.findViewById(R.id.ContactDetails)
    }
}

override fun onCreateViewHolder(parent: ViewGroup,viewType: Int): MyViewHolder {
    return MyViewHolder(layoutInflater.inflate(R.layout.contacts_row, parent, false))
}

override fun getItemCount(): Int {
    return mupdateList.size
}


override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
    val contact = mupdateList[position]

    with(holder.itemView) {
        ContactName.text = contact.name
        if(contact.label != null){
            contLabel.text = contact.label
            if (contact.label == "LEAD"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorPurple))
            } else if (contact.label == "Qualified"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorBlueNote))
            } else if (contact.label == "Proposal"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorMaroon))
            } else if (contact.label == "Client"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorGreen))
            } else if (contact.label == "Invoiced"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorYellow))
            } else if (contact.label == "Unpaid"){
                contLabel.setBackgroundColor(resources.getColor(R.color.ColorRed))
            } else if (contact.label == ""){
                contLabel.setBackgroundColor(Color.TRANSPARENT)
            }
        }

        Picasso.get().load(contact.photoUri)
            .placeholder(R.drawable.ic_baseline_whatshot_24).fit().centerCrop().into(
                ContactProfileImage
            )
        ContactDetails.removeAllViews()
        contact.numbers.forEach {
            val detail = layoutInflater.inflate(
                R.layout.row_contact_data,
                ContactDetails,
                false
            )
            detail.imgIcon.setImageResource(R.drawable.ic_local_phone_black_24dp)
            detail.ContactData.text = it
            ContactDetails.addView(detail)
        }
        contact.emails.forEach {
            val detail = layoutInflater.inflate(
                R.layout.row_contact_data,
                ContactDetails,
                false
            )
            detail.imgIcon.setImageResource(R.drawable.ic_mail_black_24dp)
            detail.ContactData.text = it
            ContactDetails.addView(detail)
        }
    }
    holder.itemView.setOnClickListener {
        val intent = Intent(mContext, ContactDetailsHome::class.java)
        intent.putExtra("contact", contact as Serializable)
        intent.putExtra("Edit", true)
        mContext.startActivity(intent)
    }

    holder.itemView.setOnLongClickListener {

        val options = arrayOf<CharSequence>(
            "Lead",
            "Qualified",
            "Proposal",
            "Client",
            "Invoiced",
            "Unpaid",
            "Clear"
        )
        var salesTag = ""
        val builder: AlertDialog.Builder = AlertDialog.Builder(mContext)
        builder.setTitle("Contact is a?")
        builder.setItems(options, DialogInterface.OnClickListener { _, which ->
            if (which == 0) {
                salesTag = "Lead"
                updateDB(contact, salesTag)
            }
            if (which == 1) {
                salesTag = "Qualified"
                updateDB(contact, salesTag)
            }
            if (which == 2) {
                salesTag = "Proposal"
                updateDB(contact, salesTag)
            }
            if (which == 3) {
                salesTag = "Client"
                updateDB(contact, salesTag)
            }
            if (which == 4) {
                salesTag = "Invoiced"
                updateDB(contact, salesTag)
            }
            if (which == 5) {
                salesTag = "Unpaid"
                updateDB(contact, salesTag)
            }
            if (which == 6) {
                salesTag = ""
                updateDB(contact, salesTag)
            }
        })
        builder.show()
        true
    }

}

private fun updateDB(contactL: Contact, salesTag: String) {
    val db = AppDatabase.getDatabase(mContext)
    val ev = Contact(
        contactL.id,
        contactL.name,
        contactL.lookupKey,
        contactL.photoUri,
        salesTag,
        null
    )
    db.contactsDao().updateContact(ev)
}

inner class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)

} }

Layout file布局文件

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Contacts.ui.ManageContacts">

<com.google.android.material.appbar.AppBarLayout
    android:id="@+id/barlayout_contacts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar_contacts"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:popupTheme="@style/AppTheme.PopupOverlay">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <TextView
                android:id="@+id/actconttitle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerVertical="true"
                android:layout_marginStart="8dp"
                android:clickable="true"
                android:focusable="true"
                android:text="CRM"
                android:textAllCaps="true"
                android:textColor="@color/white"
                android:textSize="16sp" />

            <TextView
                android:id="@+id/contSort"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Sort"
                android:textAllCaps="true"
                android:textSize="16sp"
                android:clickable="true"
                android:focusable="true"
                android:textColor="@color/white"
                android:layout_toStartOf="@+id/contFilter"
                android:layout_marginEnd="14dp">
            </TextView>
            <TextView
                android:id="@+id/contFilter"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Filter"
                android:textAllCaps="true"
                android:textSize="16sp"
                android:clickable="true"
                android:focusable="true"
                android:layout_alignParentEnd="true"
                android:textColor="@color/white"
                android:layout_marginEnd="12dp">
            </TextView>
        </RelativeLayout>

    </androidx.appcompat.widget.Toolbar>

</com.google.android.material.appbar.AppBarLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/barlayout_contacts"
    android:background="@color/colorPrimaryDark" />

<EditText
    android:id="@+id/user_search_contacts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/barlayout_contacts"
    android:layout_marginStart="15dp"
    android:layout_marginTop="15dp"
    android:layout_marginEnd="15dp"
    android:layout_marginBottom="15dp"
    android:background="@drawable/textentrybg"
    android:hint="Search"
    android:padding="9dp"
    android:paddingStart="10dp"
    android:paddingEnd="10dp"
    android:textSize="19sp">

</EditText>

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvCRM"
    android:layout_below="@+id/user_search_contacts"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    />

<com.google.android.material.floatingactionbutton.FloatingActionButton
    android:id="@+id/contact_fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentEnd="true"
    android:layout_margin="20dp"
    android:backgroundTint="#2EBCD9"
    android:clickable="true"
    android:contentDescription="contact_fab"
    android:focusable="true"
    android:src="@drawable/ic_baseline_fab_24"
    app:backgroundTint="#FFFFFF" />


</RelativeLayout>

LiveData query is not working and not returning any value, got pointed out thanks to Soumik! LiveData 查询不工作且不返回任何值,感谢 Soumik 指出! Tested by doing a standard query without LiveData and it works!通过在没有 LiveData 的情况下进行标准查询进行测试,它可以工作!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM