从 Adapter 调用一个方法到 Fragment 并传递一个变量 Android Studio

Call a method from Adapter to Fragment and pass a variable with it Android Studio

所以我想要的是在我的回收站视图中单击一个按钮,我的片段中的 method/function 应该被调用,同时它也应该发送一个变量。我知道我可以使用 Listener 或 Interface,但我已经查看并实施了几种解决方案,但其中 none 通常工作正常空指针异常我不知道我在做什么错误所以如果有人让我知道这会很有帮助如何通过查看我的代码准确地做到这一点我也从我的适配器中删除了一些不必要的部分..

适配器

public class AddPartAdapter extends RecyclerView.Adapter<AddPartAdapter.ViewHolder> {

private  Context mContext;
private  List<User> mUsers;

EventListener listener;



public interface EventListener {
    void AddParticipant(String id);
}

public void addEventListener(EventListener listener){
    this.listener = listener;
}

public void removeEventListener(){
    listener = null;
}


public AddPartAdapter(Context mContext, List<User> mUsers) {
    this.mContext = mContext;
    this.mUsers = mUsers;

}



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

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

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

    if (user.getImageUrl().equals("default")) {
        holder.dp.setImageResource(R.drawable.user);
    } else {
        Glide.with(mContext).load(user.getImageUrl()).into(holder.dp);
    }

    holder.addpart_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String Variable = user.getId();//This is the variable that should pass
            //Send call that method and send the variablethat variable to Fragment
            listener.AddParticipant(Variable);
        }
    });

}

碎片

public class AddParticipantsFragment extends Fragment implements AddPartAdapter.EventListener {

private RecyclerView recyclerView;
private List<User> mUsers;

DatabaseReference databaseReference;
FirebaseUser firebaseUser;

private List<Chatlist>usersList;

private AddPartAdapter addPartAdapter;

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<>();
    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
                        }

                    }


                }

            }



            AddPartAdapter addPartAdapter = new AddPartAdapter(getContext(), mUsers);
            addPartAdapter.addEventListener();//Here inside the bracket what to add.
            recyclerView.setAdapter(addPartAdapter);
        }

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

        }
    });
}




public void AddParticipant(String id) {
    //And it should initialize this method
    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);
}

public void onDestroy() {
    super.onDestroy();
    addPartAdapter.removeEventListener();
}
}

这是 logcat

java.lang.NullPointerException: 尝试在空对象引用上调用接口方法 'void com.margsapp.messenger.Adapter.AddPartAdapter$EventListener.AddParticipant(java.lang.String)' 在 com.margsapp.messenger.Adapter.AddPartAdapter$1.onClick(AddPartAdapter.java:70) 在 android.view.View.performClick(View.java:7125) 在 android.view.View.performClick 内部(View.java:7102) 在 android.view.View.access3500 美元(View.java:801) 在 android.view.View$PerformClick.run(View.java:27336) 在 android.os.Handler.handleCallback(Handler.java:883) 在 android.os.Handler.dispatchMessage(Handler.java:100) 在 android.os.Looper.loop(Looper.java:214) 在 android.app.ActivityThread.main(ActivityThread.java:7356) 在 java.lang.reflect.Method.invoke(本机方法) 在 com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 在 com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

试试这个方法,

在您的适配器中 class,创建 2 个方法。添加和删​​除侦听器。

public addEventListener(EventListener listener){
    this.listener = listener;
}

public removeEventListener(){
   listener = null;
}

片段class

public class AddParticipantsFragment extends Fragment implements AddPartAdapter.EventListener  {

private RecyclerView recyclerView;
private List<User> mUsers;

DatabaseReference databaseReference;
FirebaseUser firebaseUser;

private List<Chatlist>usersList;


public String groupId;
private AddPartAdapter addPartAdapter



@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<>();

    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
                        }

                    }


                }

            }



            addPartAdapter = new AddPartAdapter(getContext(), mUsers);
            adapter.addEventListener(this)
            recyclerView.setAdapter(addPartAdapter);
        }

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

        }
    });
}



 //This is the method that should be called and id is the variable I want
 public void AddParticipant(String id) {
    //And it should initialize this method
    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);
 }


 override fun onDestroy() {
        super.onDestroy()
        adapter.removeEventListener()
    }

}