尝试在空对象引用上调用接口方法“____”[重复]
Posted
技术标签:
【中文标题】尝试在空对象引用上调用接口方法“____”[重复]【英文标题】:Attempt to invoke interface method '____' on a null object reference [duplicate] 【发布时间】:2021-06-12 23:09:28 【问题描述】:所以实际上我正在尝试从我的适配器启动一个方法到我的一个片段我也将一个变量从适配器传递到该片段,方法是我创建了一个作业接口,但不幸的是,有一个空指针异常不确定问题出在哪里,请查看我的代码并让我知道错误在哪里
适配器
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)
有关更多详细信息,这里是该方法所在的片段
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);
这是界面
public interface GroupMethods
public void AddParticipant(String id);
【问题讨论】:
listener
是null
不,这没有回答我的问题@a_local_nobody
@GabrieleMariotti 我应该如何解决它我的意思是我已经在我的片段中提到它但它显示为空?
是的,我正在使用那个构造函数
我已经添加了其他文件我是否正确初始化?
【参考方案1】:
您是如何创建此适配器的?适配器有两种不同的构造方法,一种包含许多参数,另一种只包含侦听器。
如果您需要对该适配器的所有使用访问它并删除第二个构造函数,则应在第一个构造函数中包含侦听器作为另一个参数,否则使用任何一个构造函数都会使适配器处于不完整状态。
如果不是所有适配器的使用都需要包含监听器,那么创建一个单独的方法而不是一个单独的构造函数来将监听器分配给适配器类。
public setAdapter(GroupMethods listener)
this.listener = listener;
此外,您的 RecyclerView 没有从 RecyclerView.Adapter 扩展,因为它可能应该,请查看 RecyclerView documentation 中提供的示例
【讨论】:
非常感谢您的回答,我创建了两个构造函数,因为它们都有不同的用例 我已经添加了我的 Fragment 和 Interface 现在有什么问题以及如何解决它?以上是关于尝试在空对象引用上调用接口方法“____”[重复]的主要内容,如果未能解决你的问题,请参考以下文章
致命异常: main ,尝试在空对象引用上调用虚拟方法 [重复]
AsyncTask +数据库尝试在空对象引用上调用虚拟方法[重复]
数据库错误:尝试在空对象引用上调用虚拟方法“Cursor .getScene()”[重复]
数据库错误:“NullPointerException:尝试在空对象引用上调用虚拟方法 getApplicationInfo()...”[重复]