Null Pointer Exception as notification was added












0














I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message



package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{

private String messageReceiverId;
private String messageReceiverName;

// private Toolbar ChatToolBar;

private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;


private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;


FirebaseUser fuser;
DatabaseReference rootRef;

private FirebaseAuth mAuth;
private String messageSenderId;


private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();

private LinearLayoutManager linearLayoutManager;

private MessageAdapter messageAdapter;

private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;




Intent intent;

ValueEventListener seenListener;

String userid;

APIServiceFragment apiService;

boolean notify = false;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);


rootRef = FirebaseDatabase.getInstance().getReference();

mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();



messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");



apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);

// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);


loadingBar = new ProgressDialog(this);

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);

LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);

actionBar.setCustomView(action_bar_view);

userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);


SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);


messageAdapter = new MessageAdapter(messageList);

userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);

linearLayoutManager = new LinearLayoutManager(this);

userMessagesList.setHasFixedSize(true);

userMessagesList.setLayoutManager(linearLayoutManager);

userMessagesList.setAdapter(messageAdapter);




FetchMessages();


userNameTitle.setText(messageReceiverName);

rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();


Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
@Override
public void onSuccess()
{

}

@Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});


if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}

else
{
LastSeenTime getTime = new LastSeenTime();

long last_seen = Long.parseLong(online);

//problem with last seen time here

String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();


userLastSeen.setText(lastSeenDisplayTime);
}
}

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});



SendMessageButton.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View view)
{
SendMessage();
}
});



// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v)
// {

// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();


Uri ImageUri = data.getData();

final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

final String message_push_id = user_message_key.getKey();


final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");

final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {

downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();


Map messageTextBody = new HashMap();


messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}

InputMessageText.setText("");

loadingBar.dismiss();
}
});


Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}

private void FetchMessages()
{

rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{

if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);

messageList.add(messages);

messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});


// seenMessage(userid);

}



private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);

if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();

messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);

}
}
}

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

}
});
}





private void SendMessage()
{


notify = true;
String messageText = InputMessageText.getText().toString();

if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}

else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;

final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

String message_push_id = user_message_key.getKey();


Map messageTextBody = new HashMap();


messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);

messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}

else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}




}
});





**i tried sending chat notification with the code below


and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**



                    final String msg = messageText;

rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}

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

}
});


}

}

private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);

Sender sender = new Sender(data, token.getToken());

apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)

{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onFailure(Call<MyResponse> call, Throwable t)
{

}
});
}
}

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

}
});
}


}


this is the logcat below



 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)









share|improve this question




















  • 1




    I don't see any code setting fuser before calling fuser.getUid()
    – Michael Butscher
    Nov 20 at 22:40










  • you have declared 'fuser' but have not assigned before you use it.
    – Chamila Lakmal
    Nov 21 at 4:24
















0














I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message



package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{

private String messageReceiverId;
private String messageReceiverName;

// private Toolbar ChatToolBar;

private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;


private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;


FirebaseUser fuser;
DatabaseReference rootRef;

private FirebaseAuth mAuth;
private String messageSenderId;


private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();

private LinearLayoutManager linearLayoutManager;

private MessageAdapter messageAdapter;

private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;




Intent intent;

ValueEventListener seenListener;

String userid;

APIServiceFragment apiService;

boolean notify = false;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);


rootRef = FirebaseDatabase.getInstance().getReference();

mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();



messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");



apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);

// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);


loadingBar = new ProgressDialog(this);

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);

LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);

actionBar.setCustomView(action_bar_view);

userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);


SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);


messageAdapter = new MessageAdapter(messageList);

userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);

linearLayoutManager = new LinearLayoutManager(this);

userMessagesList.setHasFixedSize(true);

userMessagesList.setLayoutManager(linearLayoutManager);

userMessagesList.setAdapter(messageAdapter);




FetchMessages();


userNameTitle.setText(messageReceiverName);

rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();


Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
@Override
public void onSuccess()
{

}

@Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});


if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}

else
{
LastSeenTime getTime = new LastSeenTime();

long last_seen = Long.parseLong(online);

//problem with last seen time here

String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();


userLastSeen.setText(lastSeenDisplayTime);
}
}

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});



SendMessageButton.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View view)
{
SendMessage();
}
});



// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v)
// {

// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();


Uri ImageUri = data.getData();

final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

final String message_push_id = user_message_key.getKey();


final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");

final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {

downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();


Map messageTextBody = new HashMap();


messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}

InputMessageText.setText("");

loadingBar.dismiss();
}
});


Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}

private void FetchMessages()
{

rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{

if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);

messageList.add(messages);

messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});


// seenMessage(userid);

}



private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);

if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();

messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);

}
}
}

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

}
});
}





private void SendMessage()
{


notify = true;
String messageText = InputMessageText.getText().toString();

if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}

else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;

final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

String message_push_id = user_message_key.getKey();


Map messageTextBody = new HashMap();


messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);

messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}

else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}




}
});





**i tried sending chat notification with the code below


and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**



                    final String msg = messageText;

rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}

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

}
});


}

}

private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);

Sender sender = new Sender(data, token.getToken());

apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)

{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onFailure(Call<MyResponse> call, Throwable t)
{

}
});
}
}

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

}
});
}


}


this is the logcat below



 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)









share|improve this question




















  • 1




    I don't see any code setting fuser before calling fuser.getUid()
    – Michael Butscher
    Nov 20 at 22:40










  • you have declared 'fuser' but have not assigned before you use it.
    – Chamila Lakmal
    Nov 21 at 4:24














0












0








0







I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message



package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{

private String messageReceiverId;
private String messageReceiverName;

// private Toolbar ChatToolBar;

private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;


private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;


FirebaseUser fuser;
DatabaseReference rootRef;

private FirebaseAuth mAuth;
private String messageSenderId;


private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();

private LinearLayoutManager linearLayoutManager;

private MessageAdapter messageAdapter;

private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;




Intent intent;

ValueEventListener seenListener;

String userid;

APIServiceFragment apiService;

boolean notify = false;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);


rootRef = FirebaseDatabase.getInstance().getReference();

mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();



messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");



apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);

// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);


loadingBar = new ProgressDialog(this);

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);

LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);

actionBar.setCustomView(action_bar_view);

userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);


SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);


messageAdapter = new MessageAdapter(messageList);

userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);

linearLayoutManager = new LinearLayoutManager(this);

userMessagesList.setHasFixedSize(true);

userMessagesList.setLayoutManager(linearLayoutManager);

userMessagesList.setAdapter(messageAdapter);




FetchMessages();


userNameTitle.setText(messageReceiverName);

rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();


Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
@Override
public void onSuccess()
{

}

@Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});


if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}

else
{
LastSeenTime getTime = new LastSeenTime();

long last_seen = Long.parseLong(online);

//problem with last seen time here

String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();


userLastSeen.setText(lastSeenDisplayTime);
}
}

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});



SendMessageButton.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View view)
{
SendMessage();
}
});



// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v)
// {

// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();


Uri ImageUri = data.getData();

final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

final String message_push_id = user_message_key.getKey();


final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");

final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {

downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();


Map messageTextBody = new HashMap();


messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}

InputMessageText.setText("");

loadingBar.dismiss();
}
});


Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}

private void FetchMessages()
{

rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{

if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);

messageList.add(messages);

messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});


// seenMessage(userid);

}



private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);

if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();

messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);

}
}
}

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

}
});
}





private void SendMessage()
{


notify = true;
String messageText = InputMessageText.getText().toString();

if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}

else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;

final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

String message_push_id = user_message_key.getKey();


Map messageTextBody = new HashMap();


messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);

messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}

else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}




}
});





**i tried sending chat notification with the code below


and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**



                    final String msg = messageText;

rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}

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

}
});


}

}

private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);

Sender sender = new Sender(data, token.getToken());

apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)

{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onFailure(Call<MyResponse> call, Throwable t)
{

}
});
}
}

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

}
});
}


}


this is the logcat below



 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)









share|improve this question















I don't get the error when i run the app everything works fine, but when i click on the send message button the app crashes but the message still gets sent. below is my code for the chatActivity and logcat message



package com.paddi.paddi.paddi;
public class ChatActivity extends AppCompatActivity
{

private String messageReceiverId;
private String messageReceiverName;

// private Toolbar ChatToolBar;

private TextView userNameTitle;
private TextView userLastSeen;
private CircleImageView userChatProfileImage;


private ImageButton SendMessageButton;
// private ImageButton SelectImageButton;
private EditText InputMessageText;


FirebaseUser fuser;
DatabaseReference rootRef;

private FirebaseAuth mAuth;
private String messageSenderId;


private RecyclerView userMessagesList;
private final List<Messages> messageList = new ArrayList<>();

private LinearLayoutManager linearLayoutManager;

private MessageAdapter messageAdapter;

private static int Gallery_Pick = 1;
private StorageReference MessageImageStorageRef;
private ProgressDialog loadingBar;
private String downloadImageUrl;




Intent intent;

ValueEventListener seenListener;

String userid;

APIServiceFragment apiService;

boolean notify = false;


@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);


rootRef = FirebaseDatabase.getInstance().getReference();

mAuth = FirebaseAuth.getInstance();
messageSenderId = mAuth.getCurrentUser().getUid();



messageReceiverId = getIntent().getExtras().get("visit_user_id").toString();
messageReceiverName = getIntent().getExtras().get("user_name").toString();
MessageImageStorageRef = FirebaseStorage.getInstance().getReference().child("Messages_Pictures");



apiService = Client.getClient("https://fcm.googleapis.com/").create(APIServiceFragment.class);

// ChatToolBar = (Toolbar) findViewById(R.id.chat_bar_layout);
// setSupportActionBar(ChatToolBar);


loadingBar = new ProgressDialog(this);

ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);

LayoutInflater layoutInflater = (LayoutInflater)
this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View action_bar_view = layoutInflater.inflate(R.layout.chat_custom_bar, null);

actionBar.setCustomView(action_bar_view);

userNameTitle = (TextView) findViewById(R.id.custom_profile_name);
userLastSeen = (TextView) findViewById(R.id.custom_user_last_seen);
userChatProfileImage = (CircleImageView) findViewById(R.id.custom_profile_image_last_seen);


SendMessageButton = (ImageButton) findViewById(R.id.send_message_btn);
// SelectImageButton = (ImageButton) findViewById(R.id.select_image);
InputMessageText = (EditText) findViewById(R.id.input_message);


messageAdapter = new MessageAdapter(messageList);

userMessagesList = (RecyclerView) findViewById(R.id.messages_list_of_users);

linearLayoutManager = new LinearLayoutManager(this);

userMessagesList.setHasFixedSize(true);

userMessagesList.setLayoutManager(linearLayoutManager);

userMessagesList.setAdapter(messageAdapter);




FetchMessages();


userNameTitle.setText(messageReceiverName);

rootRef.child("Users").child(messageReceiverId).addValueEventListener(new ValueEventListener()
{
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
final String online = dataSnapshot.child("online").getValue().toString();
final String userThumb = dataSnapshot.child("user_thumb_image").getValue().toString();


Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().networkPolicy(NetworkPolicy.OFFLINE).placeholder(R.drawable.default_profile)
.into(userChatProfileImage, new Callback() {
@Override
public void onSuccess()
{

}

@Override
public void onError()
{
Picasso.with(ChatActivity.this).load(userThumb).fit().centerInside().placeholder(R.drawable.default_profile).into(userChatProfileImage);
}
});


if (online != null) {
if (online.equals("true"))
{
userLastSeen.setText("online");
}

else
{
LastSeenTime getTime = new LastSeenTime();

long last_seen = Long.parseLong(online);

//problem with last seen time here

String lastSeenDisplayTime = getTime.getTimeAgo(last_seen, getApplicationContext()).toString();


userLastSeen.setText(lastSeenDisplayTime);
}
}

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});



SendMessageButton.setOnClickListener(new View.OnClickListener()
{

@Override
public void onClick(View view)
{
SendMessage();
}
});



// SelectImageButton.setOnClickListener(new View.OnClickListener() {
// @Override
// public void onClick(View v)
// {

// Intent galleryIntent = new Intent();
// galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
// galleryIntent.setType("image/*");
// startActivityForResult(galleryIntent, Gallery_Pick);
//}
//});


}


@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);

if(requestCode==Gallery_Pick && resultCode==RESULT_OK &&data!=null)
{
loadingBar.setTitle("Sending Image");
loadingBar.setMessage("Please Wait");
loadingBar.show();


Uri ImageUri = data.getData();

final String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;
final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

final String message_push_id = user_message_key.getKey();


final StorageReference filePath = MessageImageStorageRef.child(message_push_id + ".jpg");

final StorageTask<UploadTask.TaskSnapshot> taskSnapshotStorageTask = filePath.putFile(ImageUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {

downloadImageUrl = filePath.getDownloadUrl().toString();
// return filePath.getDownloadUrl();


Map messageTextBody = new HashMap();


messageTextBody.put("message", downloadImageUrl);
messageTextBody.put("isseen", true);
messageTextBody.put("type", "image");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}

InputMessageText.setText("");

loadingBar.dismiss();
}
});


Toast.makeText(ChatActivity.this, "Picture Sent Successfully.", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
} else {
Toast.makeText(ChatActivity.this, "Picture not sent, Try again", Toast.LENGTH_SHORT).show();
loadingBar.dismiss();
}
}
});
}
}

private void FetchMessages()
{

rootRef.child("Messages").child(messageSenderId).child(messageReceiverId)
.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s)
{

if (dataSnapshot.exists())
{
Messages messages = dataSnapshot.getValue(Messages.class);

messageList.add(messages);

messageAdapter.notifyDataSetChanged();
userMessagesList.smoothScrollToPosition(userMessagesList.getAdapter().getItemCount());
}
}

@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onChildRemoved(DataSnapshot dataSnapshot)
{

}

@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s)
{

}

@Override
public void onCancelled(DatabaseError databaseError)
{

}
});


// seenMessage(userid);

}



private void seenMessage(final String userid) //add String and userid
{
rootRef = FirebaseDatabase.getInstance().getReference("Messages");
seenListener = rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot : dataSnapshot.getChildren())
{
Messages messages = snapshot.getValue(Messages.class);

if (messages.getTo().equals(fuser.getUid()) && messages.getFrom().equals(ChatActivity.this.userid))//change messages to userid
{
Map messageTextBody = new HashMap();

messageTextBody.put("isseen", true);
snapshot.getRef().updateChildren(messageTextBody);

}
}
}

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

}
});
}





private void SendMessage()
{


notify = true;
String messageText = InputMessageText.getText().toString();

if (TextUtils.isEmpty(messageText))
{
Toast.makeText(ChatActivity.this,
"Input message", Toast.LENGTH_SHORT).show();
}

else
{
String message_sender_ref = "Messages/" + messageSenderId + "/" + messageReceiverId;

final String message_receiver_ref = "Messages/" + messageReceiverId + "/" + messageSenderId;



DatabaseReference user_message_key = rootRef.child("Messages").child(messageSenderId)
.child(messageReceiverId).push();

String message_push_id = user_message_key.getKey();


Map messageTextBody = new HashMap();


messageTextBody.put("message", messageText);
messageTextBody.put("isseen", false);
messageTextBody.put("type", "text");
messageTextBody.put("time", ServerValue.TIMESTAMP);
messageTextBody.put("from", messageSenderId);
messageTextBody.put("to", messageReceiverId);

Map messageBodyDetails = new HashMap();

messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);

messageBodyDetails.put(message_receiver_ref + "/" + message_push_id, messageTextBody);


rootRef.updateChildren(messageBodyDetails).addOnCompleteListener(new OnCompleteListener() {
@Override
public void onComplete(@NonNull Task task)
{
if (task.isSuccessful())
{
Toast.makeText(ChatActivity.this, "Message Sent", Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}

else
{
String message = task.getException().getMessage();
Toast.makeText(ChatActivity.this, "Error:" + message, Toast.LENGTH_SHORT).show();
InputMessageText.setText("");
}




}
});





**i tried sending chat notification with the code below


and that was what triggered the error the messages still get sent but the app crashes and restarts itself.**



                    final String msg = messageText;

rootRef = FirebaseDatabase.getInstance().getReference("Users").child(fuser.getUid());
rootRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
User user = dataSnapshot.getValue(User.class);
if (notify) {
sendNotification(message_receiver_ref, user.getUsername(), msg);
}
notify = false;
}

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

}
});


}

}

private void sendNotification(String message_receiver_ref, final String username, final String message)
{
DatabaseReference tokens = FirebaseDatabase.getInstance().getReference("Tokens");
Query query = tokens.orderByKey().equalTo(message_receiver_ref);
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot)
{
for (DataSnapshot snapshot: dataSnapshot.getChildren())
{
Token token = snapshot.getValue(Token.class);
Data data = new Data(fuser.getUid(), R.mipmap.app_icon, username+": "+message, "New Message",
userid);

Sender sender = new Sender(data, token.getToken());

apiService.sendNotification(sender)
.enqueue(new retrofit2.Callback<MyResponse>() {
@Override
public void onResponse(Call<MyResponse> call, Response<MyResponse> response)
{
if (response.code() == 200)
{
if (response.body().success != 1)

{
Toast.makeText(ChatActivity.this, "Failed!", Toast.LENGTH_SHORT).show();
}
}
}

@Override
public void onFailure(Call<MyResponse> call, Throwable t)
{

}
});
}
}

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

}
});
}


}


this is the logcat below



 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference
at com.paddi.paddi.paddi.ChatActivity.SendMessage(ChatActivity.java:504)
at com.paddi.paddi.paddi.ChatActivity.access$200(ChatActivity.java:58)
at com.paddi.paddi.paddi.ChatActivity$2.onClick(ChatActivity.java:251)
at android.view.View.performClick(View.java:5274)
at android.view.View$PerformClick.run(View.java:21543)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5765)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)






android firebase firebase-realtime-database firebase-authentication






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 20 at 22:48









Frank van Puffelen

226k28369396




226k28369396










asked Nov 20 at 22:31









John Enokela

105




105








  • 1




    I don't see any code setting fuser before calling fuser.getUid()
    – Michael Butscher
    Nov 20 at 22:40










  • you have declared 'fuser' but have not assigned before you use it.
    – Chamila Lakmal
    Nov 21 at 4:24














  • 1




    I don't see any code setting fuser before calling fuser.getUid()
    – Michael Butscher
    Nov 20 at 22:40










  • you have declared 'fuser' but have not assigned before you use it.
    – Chamila Lakmal
    Nov 21 at 4:24








1




1




I don't see any code setting fuser before calling fuser.getUid()
– Michael Butscher
Nov 20 at 22:40




I don't see any code setting fuser before calling fuser.getUid()
– Michael Butscher
Nov 20 at 22:40












you have declared 'fuser' but have not assigned before you use it.
– Chamila Lakmal
Nov 21 at 4:24




you have declared 'fuser' but have not assigned before you use it.
– Chamila Lakmal
Nov 21 at 4:24












1 Answer
1






active

oldest

votes


















0














You are getting the following error:



java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference


Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:



fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();





share|improve this answer





















    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402579%2fnull-pointer-exception-as-notification-was-added%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    You are getting the following error:



    java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference


    Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:



    fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();





    share|improve this answer


























      0














      You are getting the following error:



      java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference


      Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:



      fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();





      share|improve this answer
























        0












        0








        0






        You are getting the following error:



        java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference


        Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:



        fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();





        share|improve this answer












        You are getting the following error:



        java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a null object reference


        Because your fuser object is not initialized. To solve this, please add the following line of code in your onCreate() method:



        fuser = FirebaseAuth.getInstance().getCurrentUser().getUid();






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 21 at 10:00









        Alex Mamo

        39k72758




        39k72758






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53402579%2fnull-pointer-exception-as-notification-was-added%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Tonle Sap (See)

            I get strange results when I access the Sqlitedatabase with Unity C# via XAMPP

            Guatemaltekische Davis-Cup-Mannschaft