java.lang.IllegalStateException: cardProductItem не должно быть нулевым - PullRequest
0 голосов
/ 05 июля 2019

У меня есть приложение для Android с Kotlin. Это приложение содержит интерфейс, который содержит обзор переработчика, чтобы получить весь список продуктов.Чтобы заполнить этот список продуктов, я создаю адаптер, этот адаптер представляет собой просмотр карты: просмотр изображений и два просмотра текста.В этом интерфейсе я добавил две кнопки: одну, когда я нажимаю на весь дисплей продукта со списком, а другую - с расположением сетки. Значение по умолчанию для расположения сетки.Я хочу изменить ширину и высоту просмотра карты, чтобы отобразить все продукты в списке.Следующий код является элементом anadapter:

<?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/cardProductItem"
        android:layout_width="180dp"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:layout_marginTop="@dimen/spacing_medium"
        android:layout_marginBottom="@dimen/spacing_medium"
        android:layout_marginRight="@dimen/spacing_middle"
        android:layout_marginLeft="@dimen/spacing_middle"
        android:background="@color/grey">
    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <ImageView
                    android:id="@+id/productImage"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent"
                    android:scaleType="fitXY"
                    android:adjustViewBounds="true"
                    android:layout_centerInParent="true"
                    android:layout_gravity="center"/>

        <LinearLayout android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:orientation="horizontal"
                      android:layout_marginTop="@dimen/spacing_middle">
            <LinearLayout android:layout_width="wrap_content"
                          android:layout_height="wrap_content"
                          android:orientation="vertical">
                <TextView
                        android:id="@+id/productName"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginLeft="@dimen/spacing_medium"
                        android:fontFamily="@font/lato_regular"
                        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                        android:textColor="@color/black"/>
                <TextView
                        android:id="@+id/productPrice"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="left"
                        android:layout_marginLeft="@dimen/spacing_medium"

                        android:textStyle="bold"
                        android:fontFamily="@font/lato_regular"
                        android:textAppearance="@style/TextAppearance.AppCompat.Medium"
                        android:textColor="@color/black"/>
            </LinearLayout>
            <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content">
                <ImageView
                        android:id="@+id/arrowDetailProduct"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:scaleType="fitXY"
                        android:layout_margin="8dp"
                        android:visibility="gone"
                        android:layout_gravity="center|center_horizontal"
                        android:src="@drawable/ic_right_arrow"/>

            </LinearLayout>


        </LinearLayout>

    </LinearLayout>
</androidx.cardview.widget.CardView>

следующий код является извлечением из xml-файла, содержащего представление переработчика:

<ImageView
               android:id="@+id/gridProducts"
               android:layout_width="@dimen/spacing_mlarge"
               android:layout_height="@dimen/spacing_mlarge"
               android:scaleType="fitXY"
               android:layout_toLeftOf="@+id/productNumber"
               android:layout_margin="8dp"
               android:src="@drawable/ic_divided_squares"/>
       <ImageView
               android:id="@+id/listProducts"
               android:layout_width="@dimen/spacing_mlarge"
               android:layout_height="@dimen/spacing_mlarge"
               android:scaleType="fitXY"
               android:layout_margin="8dp"
               android:src="@drawable/ic_rounded_black_square_shape"/>

   </androidx.appcompat.widget.LinearLayoutCompat>


   <androidx.recyclerview.widget.RecyclerView
           android:id="@+id/recyclerViewProductByCategory"
           android:layout_below="@+id/recyclerViewCategories"
           android:layout_marginTop="66dp"
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_marginStart="@dimen/spacing_middle"
           android:layout_marginEnd="@dimen/spacing_middle"
           android:orientation="horizontal"/>

следующий код содержит действие onclick в дваbuttom (Imageview):

gridProducts.setOnClickListener {
            recyclerViewProductByCategory.layoutManager =
                StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
            recyclerViewProductByCategory.adapter = products?.let { it -> ProductAdapter(it) }
            gridProducts.visibility = View.INVISIBLE
            listProducts.visibility = View.VISIBLE

        }
        listProducts.setOnClickListener {
            recyclerViewProductByCategory.layoutManager =
                LinearLayoutManager(this@CategoryByProduct, RecyclerView.VERTICAL, false)

            recyclerViewProductByCategory.adapter = products?.let { it -> ProductAdapter(it) }
    val layoutParams = LayoutParams(
        LayoutParams.MATCH_PARENT, // CardView width
        LayoutParams.WRAP_CONTENT // CardView height
    )
    cardProductItem.layoutParams = layoutParams
            listProducts.visibility = View.INVISIBLE
            gridProducts.visibility = View.VISIBLE

        }

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

java.lang.IllegalStateException: cardProductItem не должен быть нулевым

Подскажите, пожалуйста, где ошибка и как я могу ее исправить

1 Ответ

0 голосов
/ 06 июля 2019

На основании доступного кода вы устанавливаете значение cardProductItem вне setOnClickListener.Ошибка говорит о том, что cardProductItem не может быть установлен при нажатии listProduct.Убедитесь, что вы устанавливаете cardProductItem в значение, прежде чем пользовательский интерфейс будет представлен пользователю.

Для более подробного ответа мне нужно взглянуть на другие места, где используется cardProductItem.

...