0

Working on an android project just for the fun of it. I am getting back the error after a user tries to log in. I did a try-catch around the line where the error is and the RecyclerView object itself is null. So now that I know that, I am trying to figure out why it isn't getting set when I do findViewById(). I will paste the relevant code down below.

java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference

MainActivity.java

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.SearchView;

import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    MyProductAdapter myProductAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications).build();
        NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);

        RecyclerView recyclerView;
        recyclerView = findViewById(R.id.listId);
        System.out.println("This is recyclverView" + recyclerView);
        try {
            recyclerView.setHasFixedSize(true);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));
            recyclerView.setHasFixedSize(true);

        } catch (NullPointerException e) {
            System.out.println("null here" + e.getCause());
        }

        ArrayList<MyProduct> myProductData = new ArrayList<>();
        myProductData.add(new MyProduct("Panadol", "Pill  for headAche", "Price : $2.99", R.drawable.logo2));
        myProductData.add(new MyProduct("Nyquill", "Pill  for headAche", "Price : $2.99", R.drawable.logo2));
        myProductData.add(new MyProduct("ZAck", "Pill  for headAche", "Price : $2.99", R.drawable.logo2));
        myProductData.add(new MyProduct("Codeine", "Pill  for headAche", "Price : $2.99", R.drawable.logo2));


        myProductAdapter = new MyProductAdapter(myProductData, MainActivity.this);
        recyclerView.setAdapter(myProductAdapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        getMenuInflater().inflate(R.menu.menu_bar, menu);
        MenuItem menuItem = menu.findItem(R.id.search);
        SearchView searchView = (SearchView) menuItem.getActionView();
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String s) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String s) {

                myProductAdapter.getFilter().filter(s);
                return false;
            }
        });
        return super.onCreateOptionsMenu(menu);
    }

}

fragment_dashboard.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=".ui.dashboard.DashboardFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listId"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="2dp"

         />




</LinearLayout>

DashBoardFragment.java

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import com.example.medistak.R;

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        
        dashboardViewModel =
                new ViewModelProvider(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {

            }
        });
        return root;
    }
}
Joy Bits
  • 33
  • 3
Mohamed Ali
  • 702
  • 8
  • 29

1 Answers1

1

Edit (after OP adds the DashboardFragment class)

Move your MyProductAdapter and recyclerView code from MainActivity to DashboardFragment onCreateView() method as follows:

RecyclerView recyclerView = findViewById(R.id.listId);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myProductAdapter);

Your RecyclerView listId resides in your DashboardFragment whereas you are initializing and setting it up in your MainActivity class. The reason why Null Object Reference error is showing up is because of the order in which Activities and their underlying Fragments are added to the Backstack.

First your MainActivity is setup. Then follows the Fragments lying in MainActivity, in your case its the DashboardFragment. So if you will setup a recyclerView of the DashboardFragment which is not even in existence from MainActivity's point of view and yet to be created , of course it will lead to a NPE.

The solution to your problem will be to pluck out all the recyclerView setup code from MainActivity class and transfer it over to DashboardFragment.

Karan Dhillon
  • 1,186
  • 1
  • 6
  • 14