Корневой случай для NoSuchElementException: коллекция пуста - PullRequest
0 голосов
/ 06 ноября 2019

Я столкнулся с Сбой в Firebase Crashlytics на методе связывания, но не могу найти основную причину. Я добавил проверку Null, но проблема не устранена.

Отчет о сбое Firebase

Fatal Exception: java.util.NoSuchElementException: Collection is empty.
       at kotlin.collections.CollectionsKt___CollectionsKt.first(_Collections.kt:184)
       at com.transferhome.contacts.ContactsAdapter.bind(ContactsAdapter.kt:25)
       at com.transferhome.contacts.ContactsBaseAdapter.onBindViewHolder(ContactsBaseAdapter.kt:38)
       at com.transferhome.contacts.ContactsBaseAdapter.onBindViewHolder(ContactsBaseAdapter.kt:19)
       at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6781)
       at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6823)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5752)
       at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6019)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5858)
       at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:5854)
       at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2230)
       at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1557)
       at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1517)
       at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:612)
       at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:3924)
       at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3336)
       at android.view.View.measure(View.java:22216)
       at androidx.constraintlayout.widget.ConstraintLayout.internalMeasureChildren(ConstraintLayout.java:1227)
       at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1572)
       at android.view.View.measure(View.java:22216)
       at androidx.viewpager.widget.ViewPager.onMeasure(ViewPager.java:1638)
       at android.view.View.measure(View.java:22216)
       at androidx.constraintlayout.widget.ConstraintLayout.onMeasure(ConstraintLayout.java:1676)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:733)
       at com.google.android.material.appbar.HeaderScrollingViewBehavior.onMeasureChild(HeaderScrollingViewBehavior.java:95)
       at com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior.onMeasureChild(AppBarLayout.java:1556)
       at androidx.coordinatorlayout.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:803)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
       at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1539)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:823)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:702)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1539)
       at android.widget.LinearLayout.measureVertical(LinearLayout.java:823)
       at android.widget.LinearLayout.onMeasure(LinearLayout.java:702)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6671)
       at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
       at com.android.internal.policy.DecorView.onMeasure(DecorView.java:831)
       at android.view.View.measure(View.java:22216)
       at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2589)
       at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1631)
       at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1885)
       at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1515)
       at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7266)
       at android.view.Choreographer$CallbackRecord.run(Choreographer.java:981)
       at android.view.Choreographer.doCallbacks(Choreographer.java:790)
       at android.view.Choreographer.doFrame(Choreographer.java:721)
       at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:967)
       at android.os.Handler.handleCallback(Handler.java:808)
       at android.os.Handler.dispatchMessage(Handler.java:101)
       at android.os.Looper.loop(Looper.java:166)
       at android.app.ActivityThread.main(ActivityThread.java:7529)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)

ContactsAdapter.kt

class ContactsAdapter ( private val onItemSelect: (contact: Contact) -> Unit )
    : ContactsBaseAdapter<ItemContactFavListBinding>()  {

    var contactFavSignal = MutableLiveData<Contact>().apply {  }


    override fun bind(contact: Contact, holder: ContactVH<ItemContactFavListBinding>) {
        val binding = holder.binding
        binding.contactName.text = contact.name
        binding.contactNumber.text = contact.numbers.first().phone

        binding.imgContactHeart.setOnClickListener(View.OnClickListener {
            val backgroundImageName = (binding.imgContactHeart.getTag()).toString()
            if(backgroundImageName.equals("2")) {
                binding.imgContactHeart.setImageResource(R.drawable.heart_selected_yellow)
                EventBus.getDefault().post(CustomEvent(contact,true));
                binding.imgContactHeart.setTag("1")
                binding.imgContactHeart.setImageResource(R.drawable.heart_selected_yellow)

            }else  if(backgroundImageName.equals("1")) {
                binding.imgContactHeart.setImageResource(R.drawable.heart_selected_yellow)
                EventBus.getDefault().post(CustomEvent(contact,false));

                binding.imgContactHeart.setTag("2")
                binding.imgContactHeart.setImageResource(R.drawable.heart)

            }
        })

        var num = contact.numbers.first().phone
        if(num.contains(" "))
            num = num.replace(" ","")

        if(num.startsWith("0"))
            num = num.removePrefix("0")

        if(num.startsWith("+"))
            num = num.removePrefix("+")

        var isFav:Boolean=false

        for (x in 0..FavoritesFragment.listFavNumbers.size-1)
        {
            var num2 = FavoritesFragment.listFavNumbers[x]
            if(num2.endsWith(num))
                isFav=true
        }

        if(isFav)
        {
            binding.imgContactHeart.setTag("1")
            binding.imgContactHeart.setImageResource(R.drawable.heart_selected_yellow)
        }
        else
        {
            binding.imgContactHeart.setTag("2")

            binding.imgContactHeart.setImageResource(R.drawable.heart)
        }

        showContactProfileImage(contact, binding.contactImage)

        holder.binding.root.setOnClickListener {
            onItemSelect.invoke(contact)
        }
    }

    override fun provideBinding(inflater: LayoutInflater, parent: ViewGroup): ItemContactFavListBinding {
        return ItemContactFavListBinding.inflate(inflater, parent, false)
    }
}

ContactBaseAdater.kt

abstract class ContactsBaseAdapter<T : ViewDataBinding> :
    PagedListAdapter<Contact, ContactsBaseAdapter.ContactVH<T>>(object : DiffUtil.ItemCallback<Contact>() {
        override fun areItemsTheSame(oldItem: Contact, newItem: Contact): Boolean {
            return oldItem.name == newItem.name || oldItem.id == newItem.id
        }

        override fun areContentsTheSame(oldItem: Contact, newItem: Contact): Boolean {
            return oldItem.name == newItem.name

        }

    } ) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ContactVH<T> {
        return ContactVH(provideBinding(LayoutInflater.from(parent.context), parent))
    }

    override fun onBindViewHolder(holder: ContactVH<T>, position: Int) {
        val contact = getItem(position)
        if (contact != null) {
            bind(contact, holder)
        }
    }

    abstract fun bind(contact: Contact, holder: ContactVH<T>)

    abstract fun provideBinding(inflater: LayoutInflater, parent: ViewGroup): T

    class ContactVH<T : ViewDataBinding>(val binding: T) : RecyclerView.ViewHolder(binding.root)

    fun showContactProfileImage(contact: Contact, imageHolder: ImageView?) {
        UiUtils.showContactProfileImage(contact, imageHolder)
    }
}

item_contact_fav_list.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools">


    <RelativeLayout android:layout_width="match_parent"
                  android:layout_marginLeft="16dp"
                  android:layout_marginRight="16dp"
                  android:layout_marginStart="16dp"
                  android:layout_marginEnd="16dp"
                  android:layout_marginTop="8dp"
                  android:layout_marginBottom="8dp"
                  android:layout_height="wrap_content"
                  android:orientation="horizontal"
                  tools:ignore="UseCompoundDrawables">

        <ImageView
                android:id="@+id/contact_image"
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:layout_marginTop="8dp"
                android:layout_marginBottom="8dp"
                android:layout_alignParentLeft="true"
                android:contentDescription="@null"/>

        <LinearLayout android:layout_width="match_parent"
                      android:layout_height="50dp"
                      android:orientation="vertical"
                      android:weightSum="2"
                      android:layout_toLeftOf="@+id/img_contact_heart"
                      android:layout_toRightOf="@+id/contact_image"
                      android:layout_marginLeft="5dp">

        <TextView
                android:id="@+id/contact_name"
                android:textSize="16sp"
                android:layout_width="match_parent"
                android:layout_height="0dp"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:singleLine="true"
                android:ellipsize="middle"
                android:focusable="false"
                android:textColor="@color/colorBlack"
                android:layout_marginTop="3dp"
                tools:text="Contact Name"/>
            <TextView
                    android:id="@+id/contact_number"
                    android:textSize="15sp"
                    android:layout_width="match_parent"
                    android:layout_height="0dp"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:singleLine="true"
                    android:textColor="@android:color/darker_gray"
                    tools:text="Contact Name"
                    android:layout_marginLeft="5dp"

            />
        </LinearLayout>

        <ImageView
                android:layout_alignParentRight="true"
                android:id="@+id/img_contact_heart"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/heart"
                android:layout_centerVertical="true"
        />

    </RelativeLayout>
</layout>

1 Ответ

1 голос
/ 06 ноября 2019

Давайте посмотрим на трассировку стека:

Fatal Exception: java.util.NoSuchElementException: Collection is empty.
       at kotlin.collections.CollectionsKt___CollectionsKt.first(_Collections.kt:184)
       at com.transferhome.contacts.ContactsAdapter.bind(ContactsAdapter.kt:25)

Скорее всего, упоминается следующая строка:

binding.contactNumber.text = contact.numbers.first().phone

вызов first() в частности. Если contact.numbers пусто, first() выдаст NoSuchElementException. Ваш код не обрабатывает этот случай.

Самое простое решение - установить для текста значение null, если нет чисел:

binding.contactNumber.text = contact.numbers.firstOrNull()?.phone

Зачем добавлять проверку нуля, если исключение былоне NullPointerException?

...