0

I am trying to add a click listener for each cardview in a grid layout, but I get the following error.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.uspherejda/com.example.uspherejda.HomeScreen}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.cardview.widget.CardView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

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 code:

<?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>
a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
  • 1
    you use `setContentView(R.layout.home_screen);` and then you use `beginTransaction` to swap out fragments. findViewById will try to find the view on on the activity, not on the fragment. – a_local_nobody Nov 03 '21 at 07:31
  • should i just begin the transaction after the cardviews listeners? or should i just declare these cardviews inside the HomeFragment instead? – noobieCoder Nov 03 '21 at 08:20
  • 1
    `should i just begin the transaction after the cardviews listeners?` that would make no difference, the view you're trying to find _wont be found_ because you're not looking for it in the right place. if it's on the fragment, trying to find it on the activity won't work, regardless of order – a_local_nobody Nov 03 '21 at 08:22

2 Answers2

1

I just declared the cardviews in my 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;
        }
    }
-1

I am almost certain what error is in the reference of your xml:

tools:context=".HomeFragment"

Should to be:

tools:context=".HomeScreen"

Are you sure this xml belongs to your activity HomeScreen?

The java code belongs to an activity and its xml belongs to a Fragment.

  • actually switching between both does nothing but what i am doing here is calling the home fragment in my activty and controlling the other fragments through my homescreen activity, but i changed the context and i am still getting the same error, probably the fragments are causing this issue – noobieCoder Nov 03 '21 at 01:47
  • That's why, you should have a class specific for the fragment 'HomeFragment'. Currently you are calling fragment's elements ID inside of a Activity, and that's why you get NullPointerException. The findViewById should to be in the class HomeFragment. – Richard Joel Nov 03 '21 at 02:54
  • the tools namespace makes no difference to a running app, it's just there for debugging and while we develop - https://stackoverflow.com/questions/11078487/whats-toolscontext-in-android-layout-files – a_local_nobody Nov 03 '21 at 07:33