I'm creating a clone of WhatsApp and on the MainActivity there are 4 fragments side-by-side: Chats, Groups, Contacts and Requests. The last one developed was the ChatsFragment.
On it's onCreateView it gives the error on currentUserId = mAuth.getCurrentUser().getUid()
with the error of java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
This is the code:
public class ChatsFragment extends Fragment {
private View privateChatsView;
private RecyclerView chatsList;
private DatabaseReference chatsRef, usersRef;
private FirebaseAuth mAuth;
private String currentUserId;
public ChatsFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
privateChatsView = inflater.inflate(R.layout.fragment_chats, container, false);
mAuth = FirebaseAuth.getInstance();
currentUserId = mAuth.getCurrentUser().getUid();
usersRef = FirebaseDatabase.getInstance().getReference().child("Users");
chatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(currentUserId);
chatsList = privateChatsView.findViewById(R.id.chats_list);
chatsList.setLayoutManager(new LinearLayoutManager(getContext()));
return privateChatsView;
}
...
}
The ContactsFragment use the same logic to display the contacts of the user, but it doesn't crash when clicking on it, so it makes me wonder if as the ChatsFragment is the first one that opens automatically when the MainActivity is opening, is it possible that the ChatsFragment calls first for the mAuth before the MainActivity? Or am I missing something?
If it is this problem with synchronization, how could it be delayed?
Let me tell more, this error started on the first mobile phone (API 23), the second mobile (API 21 ) was ok but now it's crashing too. Now, the app only works on a virtual device (API 27). Hope it helps
Edit/Solution: as I as verifying the currentUser as davehenry said, one of the cellphones just blocked the screen and the app worked fine. Idk what happened, but when opening the app with the cellphone blocked, after unblocking it, the app was on the login page and it worked fine after that. I tryed it with the other cellphone and worked again... it's possible that the app had time to verify the currentUser on the MainActivity and then change to the LoginActivity, because since it's not logged in, the ChatsFragment would receive the User, but there was none and then the app crashed... the problem here is why the app opened first the fragment before verifying which activity should be opened first