Search code examples
androidnullpointerexceptiononclicklistener

NullPointerException error when using onClickListener on RecyclerView item


So I created a RecyclerView and then inflated a layout on to it, individual_user.xml.

In AllUsersActivity, I am connecting data to Firebase. I am trying to set an OnClickListener with individualUserContainerConstraintLayout on to the container of the individual user to set an Intent. However, I keep getting a NullPointerException error. Why is this?

The Activity I am trying to go to with the Intent(UserProfileActivity) has just a TextView.

On a side note: I am new to this forum so I hope my question is detailed enough. I did search for similar questions already existing on the forum but none of them helped with this particular problem.

AllUsersActivity:

public class AllUsersActivity extends AppCompatActivity {

    private Toolbar mAllUsersToolBar;
    private RecyclerView mAllUsersRecyclerView;
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseUsersAdapter = null;

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

        //To place ToolBar on the page
        mAllUsersToolBar = findViewById(R.id.allUsersToolBar);
        setSupportActionBar(mAllUsersToolBar);
        getSupportActionBar().setTitle("All Users");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mAllUsersRecyclerView = findViewById(R.id.allUsersRecyclerView);

        //When user clicks the container of the user on the All Users page, they get sent to that particular user's user profile.
        ConstraintLayout individualUserContainerConstraintLayout = (ConstraintLayout) findViewById(R.id.individualUserContainerConstraintLayout);

        individualUserContainerConstraintLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent goToUserProfile = new Intent(AllUsersActivity.this, UserProfileActivity.class);
                startActivity(goToUserProfile);
            }
        });


        //FirebaseAdapter

        //Query locates the file you want to access the data from.
        Query query = FirebaseDatabase.getInstance().getReference().child("Users");

        FirebaseRecyclerOptions<Users> options = new FirebaseRecyclerOptions.Builder<Users>()
                .setQuery(query, Users.class)
                .build();

        firebaseUsersAdapter = new FirebaseRecyclerAdapter<Users, UsersViewHolder>(
                options) {
            @Override
            protected void onBindViewHolder(UsersViewHolder holder, int position, Users model) {
                holder.mIndividualUserName.setText(model.getUsername());
                holder.mIndividualUserStatus.setText(model.getStatus());
                holder.mIndividualUserPicture.setImageDrawable(getDrawable(R.drawable.profile_pic));

                //This is use to retrieve the User ID from Firebase Database.
                String userId = getRef(position).getKey();

            }

            @Override
            public UsersViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.individual_user, parent, false);
                return new UsersViewHolder(view);
            }
        };

        mAllUsersRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAllUsersRecyclerView.setAdapter(firebaseUsersAdapter);
        firebaseUsersAdapter.startListening();


    }

    @Override
    protected void onResume() {
        super.onResume();
        if(firebaseUsersAdapter != null){
            firebaseUsersAdapter.startListening();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(firebaseUsersAdapter != null){
            firebaseUsersAdapter.stopListening();
        }
    }
}

Error:

09-10 21:16:38.593 2311-2311/? E/adbd: failed to connect to socket 'localabstract:com.example.android.whammychat': Connection refused
        09-10 21:16:39.475 1575-6243/? E/AudioFlinger: not enough memory for AudioTrack size=131296
        09-10 21:16:39.475 1575-6243/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
        09-10 21:16:39.477 2412-7979/? E/IAudioFlinger: createRecord returned error -12
        09-10 21:16:39.477 2412-7979/? E/AudioRecord: AudioFlinger could not create record track, status: -12
        09-10 21:16:39.478 2412-7979/? E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
        09-10 21:16:39.478 2412-7979/? E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
        09-10 21:16:39.479 2412-7979/? E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
        09-10 21:16:47.742 1663-1851/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
        09-10 21:16:47.858 1663-1695/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
        09-10 21:16:53.374 8098-8098/com.example.android.whammychat E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.example.android.whammychat, PID: 8098
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.whammychat/com.example.android.whammychat.AllUsersActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.constraint.ConstraintLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.constraint.ConstraintLayout.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
        at com.example.android.whammychat.AllUsersActivity.onCreate(AllUsersActivity.java:48)
        at android.app.Activity.performCreate(Activity.java:7136)
        at android.app.Activity.performCreate(Activity.java:7127)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1271)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2893)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1808) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6669) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
        09-10 21:16:53.490 1799-1886/? E/InputDispatcher: channel '1450866 PopupWindow:2083893 (server)' ~ Channel is unrecoverably broken and will be disposed!
        09-10 21:16:53.492 1799-1886/? E/InputDispatcher: channel '118f06 com.example.android.whammychat/com.example.android.whammychat.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
        09-10 21:16:54.429 1575-6243/? E/AudioFlinger: not enough memory for AudioTrack size=131296
        09-10 21:16:54.429 1575-6243/? E/AudioFlinger: createRecordTrack_l() initCheck failed -12; no control block?
        09-10 21:16:54.440 2412-8127/? E/IAudioFlinger: createRecord returned error -12
        09-10 21:16:54.440 2412-8127/? E/AudioRecord: AudioFlinger could not create record track, status: -12
        09-10 21:16:54.440 2412-8127/? E/AudioRecord-JNI: Error creating AudioRecord instance: initialization check failed with status -12.
        09-10 21:16:54.441 2412-8127/? E/android.media.AudioRecord: Error code -20 when initializing native AudioRecord object.
        09-10 21:16:54.441 2412-8127/? E/ActivityThread: Failed to find provider info for com.google.android.apps.gsa.testing.ui.audio.recorded
        09-10 21:16:54.480 1799-1819/? E/memtrack: Couldn't load memtrack module

Solution

  • Your problem probably is that individualUserContainerConstraintLayout is part of R.layout.individual_user and you are trying to find it in R.layout.activity_all_users.

    This is not how RecyclerView works. You need to set the click listener in the adapter of the RecyclerView. That's where you have access to the views inside R.layout.individual_user.

    One way to do it would be like this:

    1. First you would need to remove theses lines since they are not helpful:

      ConstraintLayout individualUserContainerConstraintLayout = (ConstraintLayout) findViewById(R.id.individualUserContainerConstraintLayout);
      
      individualUserContainerConstraintLayout.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              Intent goToUserProfile = new Intent(AllUsersActivity.this, UserProfileActivity.class);
              startActivity(goToUserProfile);
          }
      });
      
    2. Now, in the onBindViewHolder(UsersViewHolder, int, Users), you can add these lines at the end of the method:

      holder.itemView.setOnclickListener(new View.OnClickListener() {
          @Override
          public void onClick(View view) {
              Intent goToUserProfile = new Intent(AllUsersActivity.this, UserProfileActivity.class);
              startActivity(goToUserProfile);
          }
      });
      

    Try it out, see if it works. If it doesn't work, it's probably because you don't have the correct visibility for your Activity in this method. If that's the case, you should use an interface, a solution which I would recommend anyway.

    Let me know if you need help with this too.