may I get an explain as to why one of the parameters i'm passing to my RecyclerViewAdapter
is null when I try to access it in the Adapter
? I've been looking at the fragments lifecycle but I cant seem to wrap my head around what's causing it to be null. In onCreateView()
I have:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_message, container, false);
mFirestore = FirebaseFirestore.getInstance();
String user_id = mAuth.getCurrentUser().getUid();;
mUsersListView = view.findViewById(R.id.users_list);
usersList = new ArrayList<>();
usersRecyclerAdapter = new UsersRecyclerAdapter(container.getContext(), usersList, me);
mUsersListView.setHasFixedSize(true);
mUsersListView.setLayoutManager(new LinearLayoutManager(container.getContext()));
mUsersListView.setAdapter(usersRecyclerAdapter);
return view;
}
And in onStart()
:
@Override
public void onStart() {
super.onStart();
usersList.clear();
mFirestore.collection("Users").addSnapshotListener(getActivity(), (documentSnapshots, e) -> {
for (DocumentChange documentChange : documentSnapshots.getDocumentChanges()) {
if (documentChange.getType() == DocumentChange.Type.ADDED) {
String user_id = documentChange.getDocument().getId();
if (mAuth.getCurrentUser().getUid().matches(user_id)) {
me = documentChange.getDocument().toObject(Users.class).withId(user_id);
System.out.println(me.getName()); //prints out a name
usersRecyclerAdapter.notifyDataSetChanged();
} else {
Users users = documentChange.getDocument().toObject(Users.class).withId(user_id);
usersList.add(users);
usersRecyclerAdapter.notifyDataSetChanged();
}
}
}
});
}
My Adapter class looks like this
public class UsersRecyclerAdapter extends RecyclerView.Adapter<UsersRecyclerAdapter.ViewHolder> {
private List<Users> usersList;
private Context context;
private Users me;
public UsersRecyclerAdapter(Context context, List<Users> usersList, Users me) {
this.usersList = usersList;
this.context = context;
this.me = me;
System.out.println(me.getName()); //this outputs null
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
//
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
//
}
}
I want to keep a reference of the me
object and pass it on to my adapter. However, when I try to access it there, it triggers a NullPointerException
. The List is fine and can be accessed though. How come?
So after discussing in comments, what helped was making a method to update me
variable in the adapter:
updateMe(Users me){ this.me = me; }
And calling it from fragment whenever me
changes.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.