CardView NullPointerException onClickListener - PullRequest
0 голосов
/ 02 июня 2018

Я пытаюсь реализовать метод setOnClickListener в CardView, но получаю пустое исключение, когда меняю ориентацию устройства (работает нормально, если я запускаю либо в портретном, либо в ландшафтном режиме):

java.lang.RuntimeException: Невозможно начать действие. ComponentInfo(android.view.View $ OnClickListener) 'для ссылки на пустой объект

Мой класс Java:

public class feedBackCardView extends FragmentActivity {
    CardView neutralCustomer;
    CardView happyCustomer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_feed_back_card_view);

        neutralCustomer =  findViewById(R.id.neutralCustomer);
        happyCustomer =  findViewById(R.id.happyCard);

        neutralCustomer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    
                Intent intent = new Intent(feedBackCardView.this, thank_you_positive.class);
                startActivity(intent);
            }
        });

        happyCustomer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {    
                Intent intent = new Intent(feedBackCardView.this, thank_you_positive.class);
                startActivity(intent);
            }
        });    
    }

    public void unsatisfiedCutomerSelectionMethod(View v){
        singleChoiceClass unsatisfied_customer_dialog = new singleChoiceClass();    
        unsatisfied_customer_dialog.show(getFragmentManager(), "unsatisfied_customer_dialog");
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the main_menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {    
        switch(item.getItemId()) {
            case R.id.contactus:    
                Intent callIntent = new Intent(Intent.ACTION_DIAL);
                callIntent.setData(Uri.parse("tel:800.525.5097"));
                startActivity(callIntent);    
                break;
            case R.id.visitsite:
                Intent siteIntent = new Intent(Intent.ACTION_VIEW);
                siteIntent.setData(Uri.parse("http://navajoinc.com"));
                startActivity(siteIntent);   
                break;
            default:
                return super.onOptionsItemSelected(item);
        }   
        return true;
    }
}

XML деятельности:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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=".feedBackCardView"
    android:padding="10dp"
    android:background="@color/colorWhiteSmoke"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:fillViewport="true"
        android:layout_height="match_parent" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textSize="14dp"
                android:layout_gravity="center"
                android:text="Please tap a response :"
                android:textColor="@color/colorLightGrey" />

            <LinearLayout

                android:clipToPadding="false"
                android:gravity="center"
                android:clickable="false"
                android:layout_gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView
                    android:id="@+id/happyCard"
                    android:foreground="?android:selectableItemBackground"
                    android:clickable="true"
                    android:layout_width="160dp"
                    android:layout_height="190dp"
                    android:layout_margin="10dp"
                    app:cardElevation="3dp"
                   app:cardBackgroundColor="@color/cardview_light_background"
                    app:cardCornerRadius="3dp"
                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="vertical"
                        android:background="@color/colorWhite"
                        android:gravity="center">
                        <ImageView
                            android:layout_width="64dp"
                            android:layout_height="64dp"
                            android:background="@drawable/happy_face"
                            android:padding="10dp"/>

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textStyle="bold"
                            android:layout_marginTop="10dp"
                            android:textColor="@color/colorLightGrey"
                            android:text="Happy Customer"/>
                        <View
                            android:layout_width="match_parent"
                            android:layout_height="1dp"
                        android:background="@color/cardview_light_background"
                            android:layout_margin="2dp"/>
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:textSize="11dp"
                            android:textColor="@color/colorTextGrey"
                            android:text="I have had a happy experience"/>


                    </LinearLayout>

                </android.support.v7.widget.CardView>

            </LinearLayout>

            <LinearLayout
                android:id="@+id/neutralLayout"
                android:clipToPadding="false"
                android:gravity="center"
                android:orientation="horizontal"
                android:clickable="false"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView
                    android:id="@+id/neutralCustomer"
                    android:foreground="?android:selectableItemBackground"
                    android:clickable="true"
                    android:layout_width="160dp"
                    android:layout_height="190dp"
                    android:layout_margin="10dp"
                    app:cardElevation="3dp"
                    app:cardBackgroundColor="@color/cardview_light_background"
                    app:cardCornerRadius="3dp"
                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="vertical"
                        android:background="@color/colorWhite"
                        android:gravity="center">
                        <ImageView
                            android:layout_width="64dp"
                            android:layout_height="64dp"
                            android:background="@drawable/neutral_face"
                            android:padding="10dp"/>

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textStyle="bold"
                            android:layout_marginTop="10dp"
                            android:textColor="@color/colorLightGrey"
                            android:text="Neutral Customer"/>
                        <View
                            android:layout_width="match_parent"
                            android:layout_height="1dp"

    android:background="@color/cardview_light_background"
                            android:layout_margin="2dp"/>
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:textSize="11dp"
                            android:textColor="@color/colorTextGrey"
                            android:text="My experience was neutral"/>


                    </LinearLayout>

                </android.support.v7.widget.CardView>

            </LinearLayout>

            <LinearLayout
                android:clipToPadding="false"
                android:gravity="center"
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">
                <android.support.v7.widget.CardView

                    android:foreground="?android:selectableItemBackground"
                    android:clickable="true"
                    android:onClick="unsatisfiedCutomerSelectionMethod"
                    android:layout_width="160dp"
                    android:layout_height="190dp"
                    android:layout_margin="10dp"
                    app:cardElevation="3dp"
                    app:cardBackgroundColor="@color/cardview_light_background"
                    app:cardCornerRadius="3dp"
                    >

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:orientation="vertical"
                        android:background="@color/colorWhite"
                        android:gravity="center">
                        <ImageView
                            android:layout_width="64dp"
                            android:layout_height="64dp"
                            android:background="@drawable/angry_face"
                            android:padding="10dp"/>

                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:textStyle="bold"
                            android:layout_marginTop="10dp"
                            android:textColor="@color/colorLightGrey"
                            android:text="Unsatisfied Customer"/>
                        <View
                            android:layout_width="match_parent"
                            android:layout_height="1dp"
                            android:background="@color/cardview_light_background"
                            android:layout_margin="2dp"/>
                        <TextView
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:gravity="center"
                            android:textSize="11dp"
                            android:textColor="@color/colorTextGrey"
                            android:text="My experience was unpleasant"/>

                    </LinearLayout>    
                </android.support.v7.widget.CardView>    
            </LinearLayout>
        </LinearLayout>
    </ScrollView>
</LinearLayout>

Я пробовал много решений на Stackoverflow и других сайтах, но ни один из них не сработал?Не могли бы вы помочь с этим вопросом?

1 Ответ

0 голосов
/ 02 июня 2018

Я попробовал код, и он работает.Даже после вращения.Однако я изменил реализацию методов onclick, чтобы просто показывать тост, а не запускать намерение, поскольку вы не предоставили классы.Я также опустил весь код, связанный с меню.

Кроме того, почему вы устанавливаете свойство clickable=true в представлении вашей карты, если вы устанавливаете onClickListener в своем коде?Это избыточно.Кроме того, я не вижу никакой причины утверждать clickable=false в ваших <LinearLayout> тегах.

Я не думаю, что вы предоставляете достаточно информации, чтобы найти ошибку, или это связано с классами, которые имеютне было предоставлено.Приложение просто зависает при вращении или после того, как вы пытаетесь что-то нажать?Вы уверены, что сбой связан с ротацией, а не попыткой запуска нового действия?

...