-1

So am actually trying to initiate a method from my Adapter to one of my Fragment I am passing a variable from the Adapter to that Fragment too with the method I have created an interface to the job but unfortunately, there's a null pointer exception am not sure where the problem is someone please look at my code and let me know where the mistake is

Adapter

public class UserAdapter extends RecyclerView.Adapter<UserAdapter.ViewHolder> {
private  Context mContext;
private  List<User> mUsers;
private boolean isChat;

private boolean isBlock;

private boolean isAdd;

private boolean isGroup;

private boolean checked;

private final boolean unreadbool = true;


private GroupMethods listener;

String currentgroup;



String theLastMessage;
String UnreadMessage;



public UserAdapter(Context mContext, List<User> mUsers, boolean isChat, boolean isAdd, boolean isBlock, boolean isGroup) {
    this.mUsers = mUsers;
    this.mContext = mContext;
    this.isChat = isChat;
    this.isAdd = isAdd;
    this.isBlock = isBlock;
    this.isGroup = isGroup;

}

public UserAdapter(GroupMethods listener){
    this.listener = listener;
}


@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    ViewGroup viewGroup = (ViewGroup) LayoutInflater.from(mContext).inflate(R.layout.user_item, parent, false);
    return new UserAdapter.ViewHolder(viewGroup);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    final User user = mUsers.get(position);


    holder.UsernameText.setText(user.getUsername());
    holder.dt.setText(user.getDt());

    if (user.getImageUrl().equals("default")) {
        holder.profile.setImageResource(R.drawable.user);
    } else {
        Glide.with(mContext).load(user.getImageUrl()).into(holder.profile);
    }
    if (unreadbool) {
        UnreadMessage(user.getId(), holder.unread);
    }

    if(isGroup){
        holder.addpart.setVisibility(View.VISIBLE);
        final String addpart = user.getId();

        holder.addpart.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    addPart_group(addpart); //This is initiating the interface and error comes here
                }else {
                    //Do Nothing
                }
            }
        });


    }
    if(!isGroup){
        holder.addpart.setVisibility(View.GONE);
    }

   
   
private void addPart_group(String id) {

    listener.AddParticipant(id); //And here's its passing and initiating 
}


@Override
public int getItemCount() {
    return mUsers.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {



    public TextView UsernameText = itemView.findViewById(R.id.username);

    public TextView dt = itemView.findViewById(R.id.dt);
    public ImageView profile;

    private final CheckBox addpart;

    private final ImageView img_on;
    private final ImageView img_off;
    private final ImageView unread;
    private final TextView last_msg;

    private final ImageView UnBlock_btn;

    public ViewHolder(View view) {
        super(view);
        profile = itemView.findViewById(R.id.profile_image);
        img_on = itemView.findViewById(R.id.img_on);
        img_off = itemView.findViewById(R.id.img_off);
        last_msg = itemView.findViewById(R.id.last_msg);
        unread = itemView.findViewById(R.id.unread);
        UnBlock_btn = itemView.findViewById(R.id.cancel_button);

        addpart = itemView.findViewById(R.id.addpart);


    }
}

Logcat

    java.lang.NullPointerException: Attempt to invoke interface method 'void 
    com.margsapp.messenger.groupclass.GroupMethods.AddParticipant(java.lang.String)' on a null object reference
    at com.margsapp.messenger.Adapter.UserAdapter.addPart_group(UserAdapter.java:234)
    at com.margsapp.messenger.Adapter.UserAdapter.access$200(UserAdapter.java:37)
    at com.margsapp.messenger.Adapter.UserAdapter$2.onCheckedChanged(UserAdapter.java:152)
    at android.widget.CompoundButton.setChecked(CompoundButton.java:180)
    at android.widget.CompoundButton.toggle(CompoundButton.java:135)
    at android.widget.CompoundButton.performClick(CompoundButton.java:140)
    at android.view.View.performClickInternal(View.java:7102)
    at android.view.View.access$3500(View.java:801)
    at android.view.View$PerformClick.run(View.java:27336)
    at android.os.Handler.handleCallback(Handler.java:883)
    at android.os.Handler.dispatchMessage(Handler.java:100)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7356)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

For further details here's the fragment where the method exists

public class AddParticipantsFragment extends Fragment implements GroupMethods {

private RecyclerView recyclerView;
private List<User> mUsers;

DatabaseReference databaseReference;
FirebaseUser firebaseUser;

private List<Chatlist>usersList;
private UserAdapter userAdapter;

public String groupId;





@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_add_participants, container, false);
    recyclerView = view.findViewById(R.id.recycler_view);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

    usersList = new ArrayList<>();

    
    UserAdapter userAdapter = new UserAdapter(this);//Initializing here



    firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    databaseReference = FirebaseDatabase.getInstance().getReference("Chatlist").child(firebaseUser.getUid());
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            usersList.clear();
            for(DataSnapshot snapshot1 : snapshot.getChildren()){
                Chatlist chatlist = snapshot1.getValue(Chatlist.class);
                usersList.add(chatlist);
            }



            chatList();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

    AddParticipants activity = (AddParticipants) getActivity();
    assert activity != null;
    groupId = activity.getMyData();


    return view;
}



private void chatList() {

    mUsers = new ArrayList<>();
    databaseReference = FirebaseDatabase.getInstance().getReference("Users");
    databaseReference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            mUsers.clear();
            for (DataSnapshot snapshot1 : snapshot.getChildren()){
                User user = snapshot1.getValue(User.class);
                for (Chatlist chatlist : usersList){
                    assert user != null;
                    if(user.getId().equals(chatlist.getId())){
                        if(chatlist.getFriends().equals("Messaged")){
                            mUsers.add(user);

                        }if (chatlist.getFriends().equals("Requested")){
                            //DoNothing
                        }
                        if(chatlist.getFriends().equals("Blocked")){
                            //Dont do anything
                        }

                    }


                }

            }



            userAdapter = new UserAdapter(getContext(), mUsers, false, false, false, true);
            recyclerView.setAdapter(userAdapter);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}



@Override
public void AddParticipant(String id) {
    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Grouplist").child(groupId);
    HashMap<String, String> hashMap1 = new HashMap<>();
    hashMap1.put("id", id);
    hashMap1.put("admin","false");
    databaseReference.setValue(hashMap1);
}

}

And here's the interface

public interface GroupMethods {

public void AddParticipant(String id);
}

1 Answers1

2

How are you creating this Adapter? You have two different constructor methods for the Adapter, one contains a number of arguments and the other just the listener.

You should include the listener as another argument in the first constructor if you need to have access to it for all uses of this Adapter and delete the second constructor, otherwise using either of the constructors will leave the Adapter in an incomplete state.

If not all uses of the Adapter will need to include the listener, then create a separate method instead of a separate constructor to assign the listener to the Adapter class.

public setAdapter(GroupMethods listener){
    this.listener = listener;
}

Also, your RecyclerView is not extending from RecyclerView.Adapter as it probably should, check the examples available in the RecyclerView documentation

Daniel
  • 777
  • 9
  • 21