Нулевая ошибка TextView несмотря на уже объявленный текст - PullRequest
0 голосов
/ 16 декабря 2018

Я пытаюсь показать массив Strings в моем RecyclerView, но я получаю ошибку, связанную с нулем, даже несмотря на это.Я просмотрел код, но не вижу, что делаю не так.Во время развертывания logcat возвращает эту ошибку:

txtTitle не должен быть нулевым

class MyFragment : androidx.fragment.app.Fragment() {
    private val ITEMTYPE = 100
    private val HEADERTYPE = 101
    private val INFOTYPE = 102

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_rv, container, false)
    }

    private lateinit var mRecyclerView: RecyclerView
    private lateinit var dataTitle: ArrayList<CharSequence>
    private lateinit var dataRating: ArrayList<String>
    private lateinit var dataDescription: ArrayList<String>
    private lateinit var mAdapter: RecyclerView.Adapter<com.companyname.appname.MyFragment.ViewHolder>

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        val v = view

        mRecyclerView = v!!.findViewById(R.id.my_recyclerview)

        // set the linear layout manager
        mRecyclerView.layoutManager = LinearLayoutManager(activity, RecyclerView.VERTICAL, false)

        // SpannableStrings
        // dynamically change SpannableString colour using defined attribute
        val attrS = intArrayOf(R.attr.spannablestringtextColor)
        val ta = activity!!.theme.obtainStyledAttributes(attrS)
        val colorSS = ta.getColor(0, Color.BLACK) //Color.BLACK - default value (colour will change automatically depending on chosen theme)
        ta.recycle()


        // SpannableString (start)
        val ssb1 = SpannableStringBuilder()

        val str1a = SpannableString(getString(R.string.placeholder1_placeholder2_placeholder3,
                " ", getString(R.string.product_a), " "))
        str1a.setSpan(BackgroundColorSpan(Color.BLACK), 0, str1a.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        str1a.setSpan(ForegroundColorSpan(ContextCompat.getColor(context!!, R.color.green)), 0, str1a.length, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
        ssb1.append(str1a)

        val str1b = SpannableString(" " + getString(R.string.producta_feature))
        str1b.setSpan(ForegroundColorSpan(colorSS), 0, str1b.length, 0)
        ssb1.append(str1b)
        // SpannableString (end)


        // init data
        dataTitle = ArrayList()
        dataTitle.add(ssbA)
        dataTitle.add(getString(R.string.title_b))

        dataRating = ArrayList()
        dataRating.add(getString(R.string.rating_a))
        dataRating.add(getString(R.string.rating_b))

        dataDescription = ArrayList()
        dataDescription.add(getString(R.string.description_a))
        dataDescription.add(getString(R.string.description_b))


        // create the adapter
        mAdapter = createAdapter()

        // set the adapter
        mRecyclerView.adapter = mAdapter

        super.onActivityCreated(savedInstanceState)
    }

    private fun createAdapter(): RecyclerView.Adapter<com.companyname.appname.MyFragment.ViewHolder> {
        return object : RecyclerView.Adapter<com.companyname.appname.MyFragment.ViewHolder>() {
            override fun onCreateViewHolder(parent: ViewGroup, type: Int): com.companyname.appname.MyFragment.ViewHolder {
                return when (type) {
                    HEADERTYPE -> com.companyname.appname.MyFragment.ViewHolder(inflateHelper(R.layout.rv_header, parent))

                    INFOTYPE -> com.companyname.appname.MyFragment.ViewHolder(inflateHelper(R.layout.rv_info, parent))

                    ITEMTYPE -> com.companyname.appname.MyFragment.ViewHolder(inflateHelper(R.layout.rv_item, parent))

                    else -> com.companyname.appname.MyFragment.ViewHolder(inflateHelper(R.layout.rv_item, parent))
                }
            }

            override fun onBindViewHolder(viewHolder: com.companyname.appname.MyFragment.ViewHolder, position: Int) {
                val rlProductInformation = viewHolder.itemView.findViewById<RelativeLayout>(R.id.rl_product_information)

                when (getItemViewType(position)) {
                    HEADERTYPE -> {
                        val buyButton = viewHolder.itemView.findViewById<Button>(R.id.buy_product)
                        buyButton.setText(R.string.buy)
                    }
                    INTROTYPE -> {
                        val tvIntroA = viewHolder.itemView.findViewById<TextView>(R.id.tv_product_intro_A)

                        val tvIntroB = viewHolder.itemView.findViewById<TextView>(R.id.tv_product_intro_B)
                    }
                    ITEMTYPE -> {
                        val itemA = dataTitle[position]
                        val itemB = dataRating[position]
                        val itemC = dataDescription[position]

                        viewHolder.tvTitle.text = itemA
                        viewHolder.tvSubtitle.text = itemB
                        viewHolder.tvDescription.text = itemC
                    }
                }
            }

            override fun getItemCount(): Int {
                return dataTitle.size + 2
            }

            override fun getItemViewType(position: Int): Int {
                return when (position) {
                    0 -> HEADERTYPE
                    else -> ITEMTYPE
                }
            }
        }
    }

    private fun inflateHelper(resId: Int, parent: ViewGroup): View {
        return LayoutInflater.from(activity).inflate(resId, parent, false)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
    internal class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        var tvTitle: TextView = itemView.findViewById(R.id.tv_product_title) as TextView
        var tvSubtitle: TextView = itemView.findViewById(R.id.tv_product_rating) as TextView
        var tvDescription: TextView = itemView.findViewById(R.id.tv_product_description) as TextView

        init {
            tvTitle; tvSubtitle; tvDescription
        }
    }
}

RecyclerView XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearLayout_recyclerView"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/my_recyclerview"
        android:clipToPadding="false"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical"
        android:scrollbarSize="3dp">
    </androidx.recyclerview.widget.RecyclerView>
</LinearLayout>

RecyclerПросмотреть элемент XML

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cv_product"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:contentPadding="16dp"
    android:layout_marginBottom="30dp">

    <LinearLayout
        android:id="@+id/ll_cv_product"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">


        <LinearLayout
            android:id="@+id/cv_product_title"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal"
            android:layout_marginBottom="2dp">

            <TextView
                android:id="@+id/tv_product_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                style="@android:style/TextAppearance.Large" />
        </LinearLayout>

        <RelativeLayout
            android:id="@+id/rl_product_information"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <TextView
                android:id="@+id/tv_product_new"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/board"
                android:textColor="?android:attr/textColorPrimary"
                style="@android:style/TextAppearance.Large"
                android:layout_below="@+id/cv_product_title"/>

            <TextView
                android:id="@+id/tv_product_rating"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginStart="10dp"
                android:textColor="?android:attr/textColorPrimary"
                style="@android:style/TextAppearance.Large"
                android:layout_below="@+id/cv_product_title"
                android:layout_toEndOf="@+id/tv_product_new" />

            <TextView
                android:id="@+id/tv_product_description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="?android:attr/textColorPrimary"
                style="@android:style/TextAppearance.Medium"
                android:layout_below="@+id/tv_product_rating" />
        </RelativeLayout>
    </LinearLayout>
</androidx.cardview.widget.CardView>

1 Ответ

0 голосов
/ 16 декабря 2018

Вы должны поместить код инициализации RecyclerView в onViewCreated.Код трудно читать, но ошибка говорит о том, что tv_product_title не определен в соответствующем XML-формате макета для элемента.

...