0

I have a bug in my app and I don't know how to resolve it. When I try to run my app, it just says, unfortunately app has stopped and in the logcat it says this:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.isEmpty()' on a null object reference' on a null object reference

t is suppose to take the user to the login activity since the user is not logged in. This is the code of the fragment where the error is being pointed to.

package com.app.whatsupafrica;


import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;

import de.hdodenhof.circleimageview.CircleImageView;


/**
* A simple {@link Fragment} subclass.
*/
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.getUid();
    if (mAuth.getUid() == null)
    {
     SendUserToLoginActivity();
    }
    if (! mAuth.getUid().isEmpty())
    {
        ChatsRef = FirebaseDatabase.getInstance().getReference().child("Contacts").child(mAuth.getUid());
    }
    UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");


    chatsList = (RecyclerView) PrivateChatsView.findViewById(R.id.chats_list);
    chatsList.setLayoutManager(new LinearLayoutManager(getContext()));


    return PrivateChatsView;
}


@Override
public void onStart()
{
    super.onStart();


    FirebaseRecyclerOptions<Contacts> options =
            new FirebaseRecyclerOptions.Builder<Contacts>()
            .setQuery(ChatsRef, Contacts.class)
            .build();


    FirebaseRecyclerAdapter<Contacts, ChatsViewHolder> adapter =
            new FirebaseRecyclerAdapter<Contacts, ChatsViewHolder>(options) {
                @Override
                protected void onBindViewHolder(@NonNull final ChatsViewHolder holder, int position, @NonNull Contacts model)
                {
                    final String usersIDs = getRef(position).getKey();
                    final String[] retImage = {"default_image"};

                    UsersRef.child(usersIDs).addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(@NonNull DataSnapshot dataSnapshot)
                        {
                            if (dataSnapshot.exists())
                            {
                                if (dataSnapshot.hasChild("image"))
                                {
                                    retImage[0] = dataSnapshot.child("image").getValue().toString();
                                    Picasso.get().load(retImage[0]).into(holder.profileImage);
                                }

                                final String retName = dataSnapshot.child("name").getValue().toString();
                                final String retStatus = dataSnapshot.child("status").getValue().toString();

                                holder.userName.setText(retName);
                                // holder.userStatus.setText("Last Seen: " + "\n" + "Date " + " Time");

                                holder.itemView.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v)
                                    {
                                        Intent chatIntent = new Intent(getContext(), ChatActivity.class);
                                        chatIntent.putExtra("visit_user_id", usersIDs);
                                        chatIntent.putExtra("visit_user_name", retName);
                                        chatIntent.putExtra("visit_image", retImage[0]);
                                        startActivity(chatIntent);
                                    }
                                });
                            }
                        }

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

                        }
                    });
                }

                @NonNull
                @Override
                public ChatsViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i)
                {
                    View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.users_display_layout, viewGroup, false);
                    return new ChatsViewHolder(view);
                }
            };

    chatsList.setAdapter(adapter);
    adapter.startListening();
}




public static class ChatsViewHolder extends RecyclerView.ViewHolder
{
    CircleImageView profileImage;
    TextView userStatus, userName;


    public ChatsViewHolder(@NonNull View itemView)
    {
        super(itemView);

        profileImage = itemView.findViewById(R.id.users_profile_image);
        userStatus = itemView.findViewById(R.id.user_status);
        userName = itemView.findViewById(R.id.user_profile_name);
    }
}
private void SendUserToLoginActivity()
{
    Intent loginIntent = new Intent(getContext(), LoginActivity.class);
    startActivity(loginIntent);
}
}
halfer
  • 19,824
  • 17
  • 99
  • 186
Tomi Tokko
  • 11
  • 3
  • Have you tried to place a breakpoint and inspect the reason why it is happening? – bichito Mar 27 '20 at 15:10
  • Maybe you should be checking mAuth.getCurrentUser(). If the user is logged out, the user is null and you can't call getUid() on something that is null. Have you tried checking this? – Norik Mar 27 '20 at 15:14
  • @Norik i will try that now. Thank you – Tomi Tokko Mar 27 '20 at 15:21

2 Answers2

0

Check if the user has signed in or not

 if(! Objects.requireNonNull( mAuth.getUid() ).isEmpty())
     currentUserID = mAuth.getUid();
 else
     //sign in the user 
0

Add this code:

mAuth.getUid();

instead of

mAuth.getCurrentUser().getUid();

Apparently current user is null

Kasım Özdemir
  • 5,414
  • 3
  • 18
  • 35