Skip to content
Advertisement

In my chat app i have this error java.lang.NullPointerException

I making chat app .. and I have this problem when i click in any user to start chat with him. but for first time when i get into chat and i send first message it has been sent “in my firebase i see it”but when i am trying to get chat again this error occur ..

    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
    at com.example.learno.SocialApp.ChatActivity$4.onDataChange(ChatActivity.java:157)

So, this is my code ..

public class ChatActivity extends AppCompatActivity {
Toolbar toolbar;
RecyclerView recyclerView;
ImageView profileTv;
TextView nameTv, userStatusTv;
EditText messageEt;
ImageButton sendBtn;
FirebaseAuth firebaseAuth;
FirebaseDatabase firebaseDatabase;
DatabaseReference usersDbRef;

ValueEventListener seenListener;
DatabaseReference userRefForSeen;

List<Modelchat> chatList;
AdapterChat adapterChat;

String hisUid;
String myUid;
String hisImage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_chat);
    toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    toolbar.setTitle("");
    recyclerView = findViewById(R.id.chat_RecylerView);
    profileTv = findViewById(R.id.profileTv);
    nameTv = findViewById(R.id.nameTv);
    userStatusTv = findViewById(R.id.userStatusTv);
    messageEt = findViewById(R.id.massageEt);
    sendBtn = findViewById(R.id.sendBtn);

    LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
    linearLayoutManager.setStackFromEnd(true);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(linearLayoutManager);

    Intent intent = getIntent();
    hisUid = intent.getStringExtra("hisUid");

    firebaseAuth = FirebaseAuth.getInstance();

    firebaseDatabase = FirebaseDatabase.getInstance();

    usersDbRef = firebaseDatabase.getReference("Users");

    Query userQuery = usersDbRef.orderByChild("uid").equalTo(hisUid);

    userQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                String name = "" + ds.child("name").getValue();
                hisImage = "" + ds.child("image").getValue();

                nameTv.setText(name);
                try {
                    Picasso.get().load(hisImage).placeholder(R.drawable.ic_defult_img_face).into(profileTv);
                } catch (Exception e) {
                    Picasso.get().load(R.drawable.ic_defult_img_face).into(profileTv);
                }
            }
        }

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

        }
    });

    sendBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String message = messageEt.getText().toString().trim();
            if (TextUtils.isEmpty(message)) {
                Toast.makeText(ChatActivity.this, "Cannot send empty message...", Toast.LENGTH_SHORT).show();
            } else {
                sendMessage(message);
            }
        }
    });
    readMessages();
    seenMessages();
}

private void seenMessages() {
    userRefForSeen = FirebaseDatabase.getInstance().getReference("Chats");
    seenListener = userRefForSeen.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot ds: dataSnapshot.getChildren()) {
                Modelchat chat = ds.getValue(Modelchat.class);
                if (chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid)) {
                    HashMap<String, Object> hasSeenHashMap = new HashMap<>();
                    hasSeenHashMap.put("isSeen", true);
                    ds.getRef().updateChildren(hasSeenHashMap);
                }
            }
        }

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

        }
    });
}

private void readMessages() {
    chatList = new ArrayList<>();
    DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
    dbRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            chatList.clear();
            for (DataSnapshot ds : dataSnapshot.getChildren()) {
                Modelchat chat = ds.getValue(Modelchat.class);
                if (chat.getReceiver().equals(myUid) && chat.getSender().equals(hisUid) ||
                        chat.getReceiver().equals(hisUid) && chat.getSender().equals(myUid)) {
                    chatList.add(chat);
                }
                adapterChat = new

                        AdapterChat(ChatActivity.this, chatList, hisImage);
                adapterChat.notifyDataSetChanged();
                recyclerView.setAdapter(adapterChat);
            }
        }


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

        }
    });
}


private void sendMessage(String message) {


    DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

    String timeStamp = String.valueOf(System.currentTimeMillis());

    HashMap<String, Object> hashMap = new HashMap<>();
    hashMap.put("Sender", myUid);
    hashMap.put("receiver", hisUid);
    hashMap.put("message", message);
    hashMap.put("timeStamp", timeStamp);
    hashMap.put("isSeen", false);

    databaseReference.child("Chats").push().setValue(hashMap);

    messageEt.setText("");
}

private void checkuserstatus() {
    FirebaseUser user = firebaseAuth.getCurrentUser();
    if (user != null) {
        myUid = user.getUid();
    } else {
        startActivity(new Intent(this, Register.class));
        finish();
    }
}

@Override
protected void onStart() {
    checkuserstatus();
    super.onStart();
}

@Override
protected void onPause() {
    super.onPause();
    userRefForSeen.removeEventListener(seenListener);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_logout, menu);
    menu.findItem(R.id.actiob_search).setVisible(false);
    return super.onCreateOptionsMenu(menu);
}

@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.logout) ;
    {
        firebaseAuth.signOut();
        checkuserstatus();
    }

    return super.onOptionsItemSelected(item);
}

and this is my Model ..

public class Modelchat {
String message,receiver,sender,timestamp;
boolean isSeen;

public Modelchat(){}

public Modelchat(String message, String receiver, String sender, String timestamp, boolean isSeen) {
    this.message = message;
    this.receiver = receiver;
    this.sender = sender;
    this.timestamp = timestamp;
    this.isSeen = isSeen;
}

public String getMessage() {
    return message;
}

public void setMessage(String message) {
    this.message = message;
}

public String getReceiver() {
    return receiver;
}

public void setReceiver(String receiver) {
    this.receiver = receiver;
}

public String getSender() {
    return sender;
}

public void setSender(String sender) {
    this.sender = sender;
}

public String getTimestamp() {
    return timestamp;
}

public void setTimestamp(String timestamp) {
    this.timestamp = timestamp;
}

public boolean isSeen() {
    return isSeen;
}

public void setSeen(boolean seen) {
    isSeen = seen;
}

so this error occur when i get into my users fragment and click into any user to start chat with him .. any one can help me with that ?

Advertisement

Answer

in your code chat.getReceiver() & chat.getSender() are returning null values and you have many calls like chat.getReceiver().equals(myUid) & chat.getSender().equals(hisUid) and all of them can product NullPointerException.

So correct getReceiver() and getSender() codes and make sure they do not return null values or check for null before calling equals on them.

Or change chat.getSender().equals(hisUid) to hisUid.equals(chat.getSender()) and chat.getReceiver().equals(myUid) to myUid.equals(chat.getReceiver()) if hisUid and myUid always are not null.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement