【问题标题】:CardView onClick java.lang.NullPointerException [duplicate]CardView onClick java.lang.NullPointerException [重复]
【发布时间】:2021-12-17 10:42:18
【问题描述】:

我正在尝试为网格布局中的每个卡片视图添加点击侦听器,但出现以下错误。

java.lang.RuntimeException:无法启动活动 组件信息{com.example.uspherejda/com.example.uspherejda.HomeScreen}: java.lang.NullPointerException:尝试调用虚拟方法'void androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' 在空对象引用上

原因:java.lang.NullPointerException:尝试调用虚拟 方法'无效 androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' 在空对象引用上

public class HomeScreen extends AppCompatActivity implements View.OnClickListener{
    //SQL
    private SatFromHelper dbHelper;
    private SQLiteDatabase db;

    private CardView satList, addSat, satType, satCountries, aboutMe, goCrazy;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_screen);

        dbHelper = new SatFromHelper(this);
        db = dbHelper.getWritableDatabase();
        //call the Home fragment
        getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, new HomeFragment()).commit();
        //Set up a custom bar using a custom
        ActionBar actionBar = getSupportActionBar();
        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.start_dark_blue)));
        actionBar.setDisplayShowCustomEnabled(true);
        LayoutInflater layoutInflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = layoutInflater.inflate(R.layout.custom_bar_image, null);
        actionBar.setCustomView(view);
        //Card views.
        satList = (CardView) findViewById(R.id.crdList);
        addSat = (CardView) findViewById(R.id.crdForm);
        satType = (CardView) findViewById(R.id.crdSatTypes);
        satCountries = (CardView) findViewById(R.id.crdCountries);
        aboutMe = (CardView) findViewById(R.id.crdAboutMe);
        goCrazy = (CardView) findViewById(R.id.crdGoCrayCraaaaay);

         satList.setOnClickListener(this);
         addSat.setOnClickListener(this);
         satType.setOnClickListener(this);
         satCountries.setOnClickListener(this);
         aboutMe.setOnClickListener(this);
         goCrazy.setOnClickListener(this);

        //Bottom Navigation
        BottomNavigationView bottomNav = findViewById(R.id.nav_menu);
        //Item listener when one of hte items below from the nav_bar is selected
        bottomNav.setOnItemSelectedListener(item -> {
            Fragment selectedFragment = null;
            switch(item.getItemId()){
                case R.id.nav_home:
                    selectedFragment = new HomeFragment();
                    break;
                case R.id.nav_list:
                    selectedFragment = new ListFragment(dbHelper, db);
                    break;
                case R.id.nav_add:
                    selectedFragment = new AddFragment(dbHelper, db);
                    break;
            }
            getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, selectedFragment).commit();
            return true;
        });
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.crdList: startActivity(new Intent(getApplicationContext(), ListFragment.class));
            break;
        }

    }
    //Close the db when the activity onDestroy
    @Override
    public void onDestroy() {
        super.onDestroy();
        dbHelper.close();
        db.close();
    }
}

XML 代码:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:id="@+id/frameLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".HomeFragment">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">
                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="My Dashboard"
                    android:textSize="40sp"
                    android:textStyle="bold"
                    android:textColor="@color/white"
                    android:layout_margin="20dp" />
                <GridLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:rowCount="4"
                    android:columnCount="2"
                    android:layout_margin="5dp"
                    android:alignmentMode="alignMargins"
                    android:layout_gravity="center_horizontal"
                    android:columnOrderPreserved="false">
                        <androidx.cardview.widget.CardView
                                android:id="@+id/crdList"
                                android:layout_width="170dp"
                                android:layout_height="170dp"
                                app:cardCornerRadius="12dp"
                                app:cardElevation="5dp"
                                app:cardBackgroundColor="@color/center_light_blue"
                                android:layout_margin="10dp">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:orientation="vertical"
                            android:gravity="center">
                                <ImageView
                                    android:layout_width="84dp"
                                    android:layout_height="84dp"
                                    android:src="@drawable/satdashboard"/>

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="Satellite List"
                                    android:textSize="16sp"
                                    android:layout_marginTop="20dp"
                                    android:textColor="@color/white"/>
                        </LinearLayout>
                        </androidx.cardview.widget.CardView>

                        <androidx.cardview.widget.CardView
                            android:id="@+id/crdForm"
                            android:layout_width="170dp"
                            android:layout_height="170dp"
                            app:cardCornerRadius="12dp"
                            app:cardElevation="5dp"
                            app:cardBackgroundColor="@color/center_light_blue"
                            android:layout_margin="10dp">
                                <LinearLayout
                                    android:layout_width="match_parent"
                                    android:layout_height="match_parent"
                                    android:orientation="vertical"
                                    android:gravity="center">
                                        <ImageView
                                            android:layout_marginLeft="10dp"
                                            android:layout_width="84dp"
                                            android:layout_height="84dp"
                                            android:src="@drawable/formdashboard"/>

                                        <TextView
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:text="Add a Satellite"
                                            android:textSize="16sp"
                                            android:layout_marginTop="20dp"
                                            android:textColor="@color/white"/>
                                </LinearLayout>
                        </androidx.cardview.widget.CardView>

                        <androidx.cardview.widget.CardView
                            android:id="@+id/crdSatTypes"
                            android:layout_width="170dp"
                            android:layout_height="170dp"
                            app:cardCornerRadius="12dp"
                            app:cardElevation="5dp"
                            app:cardBackgroundColor="@color/center_light_blue"
                            android:layout_margin="10dp">
                        <LinearLayout
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:orientation="vertical"
                            android:gravity="center">
                                <ImageView
                                    android:layout_width="84dp"
                                    android:layout_height="84dp"
                                    android:src="@drawable/sattypes"/>

                                <TextView
                                    android:layout_width="wrap_content"
                                    android:layout_height="wrap_content"
                                    android:text="Types of Satellites"
                                    android:textSize="16sp"
                                    android:layout_marginTop="20dp"
                                    android:textColor="@color/white"/>
                        </LinearLayout>

                </androidx.cardview.widget.CardView>

                        <androidx.cardview.widget.CardView
                            android:id="@+id/crdCountries"
                            android:layout_width="170dp"
                            android:layout_height="170dp"
                            android:layout_margin="10dp"
                            app:cardBackgroundColor="@color/center_light_blue"
                            app:cardCornerRadius="12dp"
                            app:cardElevation="5dp">

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

                                        <ImageView
                                            android:layout_width="84dp"
                                            android:layout_height="84dp"
                                            android:src="@drawable/countrysats" />

                                        <TextView
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginTop="20dp"
                                            android:text="Satellite Countries"
                                            android:textColor="@color/white"
                                            android:textSize="16sp" />
                                </LinearLayout>

                        </androidx.cardview.widget.CardView>

                        <androidx.cardview.widget.CardView
                            android:id="@+id/crdAboutMe"
                            android:layout_width="170dp"
                            android:layout_height="170dp"
                            android:layout_margin="10dp"
                            app:cardBackgroundColor="@color/center_light_blue"
                            app:cardCornerRadius="12dp"
                            app:cardElevation="5dp">

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

                                        <ImageView
                                            android:layout_width="84dp"
                                            android:layout_height="84dp"
                                            android:src="@drawable/aboutme" />

                                        <TextView
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginTop="20dp"
                                            android:text="About Me"
                                            android:textColor="@color/white"
                                            android:textSize="16sp" />
                                </LinearLayout>

                        </androidx.cardview.widget.CardView>

                        <androidx.cardview.widget.CardView
                            android:id="@+id/crdGoCrayCraaaaay"
                            android:layout_width="170dp"
                            android:layout_height="170dp"
                            android:layout_margin="10dp"
                            app:cardBackgroundColor="@color/center_light_blue"
                            app:cardCornerRadius="12dp"
                            app:cardElevation="5dp">

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

                                        <ImageView
                                            android:layout_width="84dp"
                                            android:layout_height="84dp"
                                            android:src="@drawable/gocrazy" />

                                        <TextView
                                            android:layout_width="wrap_content"
                                            android:layout_height="wrap_content"
                                            android:layout_marginTop="20dp"
                                            android:text="Go Crazy!"
                                            android:textColor="@color/white"
                                            android:textSize="16sp" />
                                </LinearLayout>

                        </androidx.cardview.widget.CardView>

                </GridLayout>

        </LinearLayout>

</ScrollView>

【问题讨论】:

  • 您使用setContentView(R.layout.home_screen);,然后使用beginTransaction 交换片段。 findViewById 将尝试在活动上查找视图,而不是在片段上。
  • 我应该在cardviews听众之后才开始交易吗?还是我应该在 HomeFragment 中声明这些卡片视图?
  • should i just begin the transaction after the cardviews listeners? 这没什么区别,您试图找到的视图不会被找到,因为您没有在正确的位置寻找它。如果它在片段上,无论顺序如何,试图在 Activity 上找到它都行不通

标签: java android xml


【解决方案1】:

我刚刚在我的 HomeFragment 中声明了卡片视图。

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        //Card views.
        satList = (CardView) view.findViewById(R.id.crdList);
        addSat = (CardView) view.findViewById(R.id.crdForm);
        satType = (CardView) view.findViewById(R.id.crdSatTypes);
        satCountries = (CardView) view.findViewById(R.id.crdCountries);
        aboutMe = (CardView) view.findViewById(R.id.crdAboutMe);
        goCrazy = (CardView) view.findViewById(R.id.crdGoCrayCraaaaay);
        //listeners
        satList.setOnClickListener(this::onClick);
        //addSat.setOnClickListener(this);
        //satType.setOnClickListener(this);
        //satCountries.setOnClickListener(this);
        //aboutMe.setOnClickListener(this);
        //goCrazy.setOnClickListener(this);
        return view;
    }
    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.crdList: getParentFragmentManager().beginTransaction().replace(R.id.homeFragment, new ListFragment(dbHelper, db)).commit();
                break;
        }
    }

【讨论】:

    【解决方案2】:

    我几乎可以确定您的 xml 参考中有什么错误:

    tools:context=".HomeFragment"
    

    应该是:

    tools:context=".HomeScreen"
    

    您确定此 xml 属于您的活动 HomeScreen 吗?

    java代码属于一个activity,它的xml属于一个Fragment。

    【讨论】:

    • 实际上在两者之间切换什么都不做,但我在这里做的是在我的活动中调用主片段并通过我的主屏幕活动控制其他片段,但我改变了上下文,我仍然得到相同错误,可能是碎片导致了这个问题
    • 这就是为什么,你应该有一个特定于片段'HomeFragment'的类。目前,您在 Activity 中调用片段的元素 ID,这就是您得到 NullPointerException 的原因。 findViewById 应该在 HomeFragment 类中。
    • tools 命名空间对正在运行的应用程序没有影响,它只是用于调试和开发时 - stackoverflow.com/questions/11078487/…
    猜你喜欢
    • 2021-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多