Notification device to device - android

I am a newbie in programming and trying to modify an open source application
I want to add notifications when a user receives a message from another user
I did all the instructions and followed a lot of lessons but the notifications didn't work
I created
MyFirebaseInstanceIDService
MyFirebaseMessagingService
MySingleton
OreaNotification
Sender
token
data
client
I think must add something to buttonMessageSend OnClickListener but i dont know
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.message_activity);
messageActivity = this;
this.toolbarTextViewUserName = (TextView) findViewById(R.id.toolbarTextViewUserName);
this.toolbarTextViewUserStatus = (TextView) findViewById(R.id.toolbarTextViewUserStatus);
this.toolbarImageViewUserImage = (RoundedImageView) findViewById(R.id.toolbarImageViewUserImage);
this.editTextMessageText = (EditText) findViewById(R.id.editTextMessageText);
this.buttonMessageSend = (ImageButton) findViewById(R.id.buttonMessageSend);
this.buttonMessageImage = (ImageButton)findViewById(R.id.buttonMessageImage);
loadingBar = new ProgressDialog(this);
this.listChatsClass = new ArrayList<>();
this.relativeLayoutMessageChat = (RelativeLayout) findViewById(R.id.relativeLayoutMessageChat);
this.toolbarToolbar = (Toolbar) findViewById(R.id.toolbarToolbar);
setSupportActionBar(this.toolbarToolbar);
getSupportActionBar().setTitle((CharSequence) "");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
this.toolbarToolbar.setNavigationOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MessageActivity.this.finish();
}
});
this.recyclerViewMessageView = (RecyclerView) findViewById(R.id.recyclerViewMessageView);
this.recyclerViewMessageView.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.setStackFromEnd(true);
this.recyclerViewMessageView.setLayoutManager(linearLayoutManager);
allTokens = FirebaseDatabase.getInstance().getReference("Tokens");
this.currentUser = this.firebaseAuth.getCurrentUser().getUid();
this.profileUser = getIntent().getStringExtra("user_uid");
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.currentUser).addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#javax.annotation.Nullable DocumentSnapshot documentSnapshot, #javax.annotation.Nullable FirebaseFirestoreException e) {
if (documentSnapshot != null) {
profileUserName = documentSnapshot.getString("user_name");
}
}
});
this.buttonMessageSend.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String obj = MessageActivity.this.editTextMessageText.getText().toString();
String str = "";
if (!obj.equals(str)) {
MessageActivity messageActivity = MessageActivity.this;
messageActivity.sendMessage(messageActivity.currentUser, MessageActivity.this.profileUser, obj);
} else {
Toast.makeText(MessageActivity.this, "Please type message to send", Toast.LENGTH_SHORT).show();
}
MessageActivity.this.editTextMessageText.setText(str);
}
});
editTextMessageText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if(s.toString().trim().length()==0)
{
UserTypingStatus("noOne");
}
else
{
UserTypingStatus(profileUser);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
readMessage(this.currentUser, this.profileUser);
this.toolbarTextViewUserName.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MessageActivity.this.chatProfile();
}
});
this.toolbarTextViewUserStatus.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MessageActivity.this.chatProfile();
}
});
this.toolbarImageViewUserImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
MessageActivity.this.chatProfile();
}
});
buttonMessageImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
selectImageAttachment();
}
});
}
/* access modifiers changed from: private */
public void chatProfile() {
Intent intent = new Intent(this, ProfileActivity.class);
intent.putExtra("user_uid", this.profileUser);
startActivity(intent);
}
/* access modifiers changed from: private */
public void sendMessage(final String str, final String str2, final String str3) {
HashMap hashMap = new HashMap();
hashMap.put("chat_datesent", Timestamp.now());
hashMap.put("chat_dateseen", Timestamp.now());
hashMap.put("chat_sender", str);
hashMap.put("chat_receiver", str2);
hashMap.put("chat_message", str3);
hashMap.put("chat_seenchat", "no");
String str4 = "delete";
hashMap.put("delete_sender", str4);
hashMap.put("delete_receiver", str4);
String str5 = "chats";
this.firebaseFirestore.collection(str5).add((Map<String, Object>) hashMap).addOnCompleteListener(new OnCompleteListener<DocumentReference>() {
public void onComplete(#NonNull Task<DocumentReference> task) {
if (task.isSuccessful()) {
final HashMap hashMap = new HashMap();
String str = "user_datesent";
hashMap.put("user_datesent", Timestamp.now());
String str2 = "user_sender";
hashMap.put("user_sender", str);
String str3 = "user_receiver";
hashMap.put("user_receiver", str2);
String str4 = "user_message";
hashMap.put("user_message", str3);
String str5 = AppEventsConstants.EVENT_PARAM_VALUE_NO;
String str6 = "user_unread";
hashMap.put("user_unread", str5);
final HashMap hashMap2 = new HashMap();
hashMap2.put("user_datesent", Timestamp.now());
hashMap2.put("user_sender", str2);
hashMap2.put("user_receiver", str);
hashMap2.put("user_message", str3);
hashMap2.put("user_unread", str5);
final HashMap hashMap3 = new HashMap();
hashMap3.put("user_datesent", Timestamp.now());
hashMap3.put("user_sender", str2);
hashMap3.put("user_receiver", str);
hashMap3.put("user_message", str3);
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.currentUser).collection("chats").document(MessageActivity.this.profileUser).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
String str = "chats";
final String str2 = "users";
if (((DocumentSnapshot) task.getResult()).exists()) {
MessageActivity.this.firebaseFirestore.collection(str2).document(MessageActivity.this.currentUser).collection(str).document(MessageActivity.this.profileUser).update(hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.profileUser).collection("chats").document(MessageActivity.this.currentUser).update(hashMap3).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (!task.isSuccessful()) {
loadingBar.dismiss();
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.profileUser).collection("chats").document(MessageActivity.this.currentUser).set((Map<String, Object>) hashMap2);
}
}
});
}
}
});
} else {
MessageActivity.this.firebaseFirestore.collection(str2).document(MessageActivity.this.currentUser).collection(str).document(MessageActivity.this.profileUser).set((Map<String, Object>) hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
loadingBar.dismiss();
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.profileUser).collection("chats").document(MessageActivity.this.currentUser).set((Map<String, Object>) hashMap2);
}
}
});
}
}
});
}
}
});
this.firebaseFirestore.collection("users").document(this.profileUser).collection(str5).document(this.currentUser).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
public void onComplete(#NonNull Task<DocumentSnapshot> task) {
if (((DocumentSnapshot) task.getResult()).exists()) {
String str = "user_unread";
MessageActivity.this.stringUnread = ((DocumentSnapshot) task.getResult()).getString(str);
MessageActivity messageActivity = MessageActivity.this;
messageActivity.intUnread = Integer.parseInt(messageActivity.stringUnread) + 1;
MessageActivity messageActivity2 = MessageActivity.this;
messageActivity2.stringUnreadz = String.valueOf(messageActivity2.intUnread);
HashMap hashMap = new HashMap();
hashMap.put(str, MessageActivity.this.stringUnreadz);
loadingBar.dismiss();
senNotification(MessageActivity.this.profileUser,profileUserName,str3);
MessageActivity.this.firebaseFirestore.collection("users").document(MessageActivity.this.profileUser).collection("chats").document(MessageActivity.this.currentUser).update(hashMap);
}
}
});
}

Related

Android Studıo E/AndroidRuntime: FATAL EXCEPTION: main

My error;
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.melikerdemkoc.myvetapp/com.melikerdemkoc.myvetapp.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.String com.google.firebase.auth.FirebaseUser.getUid()' on a
null object reference
My code;
import javax.annotation.Nullable;
public class MainActivity extends AppCompatActivity {
private static final int GALLERY_INTENT_CODE = 1023 ;
TextView fullName,email,phone,verifyMsg;
FirebaseAuth fAuth;
FirebaseFirestore fStore;
String userId;
Button resendCode;
Button resetPassLocal,changeProfileImage;
FirebaseUser user;
ImageView profileImage;
StorageReference storageReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
fullName = findViewById(R.id.profileName);
email = findViewById(R.id.profileEmail);
resetPassLocal = findViewById(R.id.resetPasswordLocal);
profileImage = findViewById(R.id.profileImage);
changeProfileImage = findViewById(R.id.changeProfile);
FirebaseApp.initializeApp(this);
fAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
storageReference = FirebaseStorage.getInstance().getReference();
StorageReference profileRef = storageReference.child("users/"+fAuth.getCurrentUser().getUid()+"/profile.jpg");
profileRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Picasso.get().load(uri).into(profileImage);
}
});
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
//
}
});
}
.
public void logout(View view) {
FirebaseAuth.getInstance().signOut();//logout
startActivity(new Intent(getApplicationContext(), com.melikerdemkoc.myvetapp.Login.class));
finish();
}
}
I wanna start my app using the firebase database but ı cant do that when ı start the app; my app is crashing.
don't read;
I'm writing because I can't post my questionI'm writing because I can't post my question
Problem
Seems your trying to access a current user does not exist.
Possible Solution
Try checking if user is signed in else should not run the code which needs the current user confirmation.
Here is your refined code.
....
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
phone = findViewById(R.id.profilePhone);
....
resendCode = findViewById(R.id.resendCode);
verifyMsg = findViewById(R.id.verifyMsg);
if (fAuth.getCurrentUser() != null) {
verifyUser();
}
else {
Log.d("tag", "The user is not authenticated");
}
}
verifyUser Method
public void verifyUser()
{
userId = fAuth.getCurrentUser().getUid();
user = fAuth.getCurrentUser();
if(!user.isEmailVerified()){
verifyMsg.setVisibility(View.VISIBLE);
resendCode.setVisibility(View.VISIBLE);
resendCode.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
user.sendEmailVerification().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(v.getContext(), "Verification Email Has been Sent.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d("tag", "onFailure: Email not sent " + e.getMessage());
}
});
}
});
}
DocumentReference documentReference = fStore.collection("users").document(userId);
documentReference.addSnapshotListener(this, new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot documentSnapshot, #Nullable FirebaseFirestoreException e) {
if(documentSnapshot.exists()){
phone.setText(documentSnapshot.getString("phone"));
fullName.setText(documentSnapshot.getString("fName"));
email.setText(documentSnapshot.getString("email"));
}else {
Log.d("tag", "onEvent: Document do not exists");
}
}
});
resetPassLocal.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final EditText resetPassword = new EditText(v.getContext());
final AlertDialog.Builder passwordResetDialog = new AlertDialog.Builder(v.getContext());
passwordResetDialog.setTitle("Reset Password ?");
passwordResetDialog.setMessage("Enter New Password > 6 Characters long.");
passwordResetDialog.setView(resetPassword);
passwordResetDialog.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// extract the email and send reset link
String newPassword = resetPassword.getText().toString();
user.updatePassword(newPassword).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(MainActivity.this, "Password Reset Successfully.", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "Password Reset Failed.", Toast.LENGTH_SHORT).show();
}
});
}
});
passwordResetDialog.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// close
}
});
passwordResetDialog.create().show();
}
});
changeProfileImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// open gallery
Intent i = new Intent(v.getContext(), com.melikerdemkoc.myvetapp.EditProfile.class);
i.putExtra("fullName",fullName.getText().toString());
i.putExtra("email",email.getText().toString());
i.putExtra("phone",phone.getText().toString());
startActivity(i);
}
});
}
Hope it solves the problem.

In-App notifications without server side coding in Firebase

I am developing an e-commerce android application in which i have two sides(admin side and user side). I have implemented in-app messaging in my application where user can send message to admin and admin can send message to user. Now, i want to add notifications to this part that when a admin or user sends message the other side receives notification if it is in the app because i want to do this without server side code. I tried googling it but couldn't find any good solution. So can anyone help?
Here is my chat class for user:
chat_messages_view_panel = (LinearLayout)findViewById(R.id.chat_messages_view_panel);
chat_messages_scroll_view = (ScrollView)findViewById(R.id.chat_messages_scroll_view);
chatImagesRef = FirebaseStorage.getInstance().getReference().child("Chat Images");
FirebaseDatabase.getInstance().getReference().child("Admins").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot item : snapshot.getChildren()) {
admin = item.getValue(Admin.class);
break;
}
loadMessages();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
FirebaseDatabase.getInstance().getReference().child("Messages").child(Prevelent.onlineUser.getEmail()).
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
for(DataSnapshot item: snapshot.getChildren())
{
Message message = item.getValue(Message.class);
if(!message_ids.contains(message.getId()))
{
message_ids.add(message.getId());
addMessage(message);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
sendButton = (ImageButton)findViewById(R.id.sendMessage);
messageContent = (EditText)findViewById(R.id.chat_message_box);
sendPictureButton = (ImageButton) findViewById(R.id.uploadImage);
loadingBar = new ProgressDialog(this);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(messageContent.getText().toString().equals("")){
return;
}
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy MM, dd");
String saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss:SSS a");
String saveCurrentTime = currentTime.format(calendar.getTime());
DatabaseReference messageRef = FirebaseDatabase.getInstance().getReference();
Map<String, Object> userdataMap = new HashMap<>();
userdataMap.put("id", Prevelent.onlineUser.getEmail() + " : " + saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("content", messageContent.getText() + "");
userdataMap.put("sentByEmail", Prevelent.onlineUser.getEmail());
userdataMap.put("sentByName", Prevelent.onlineUser.getName());
userdataMap.put("sentToEmail", admin.getEmail());
userdataMap.put("sentToName", admin.getName());
userdataMap.put("sentAt", saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("messageType", "text");
messageRef.child("Messages").child(Prevelent.onlineUser.getEmail()).child(saveCurrentDate + " " + saveCurrentTime).
updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>(){
#Override
public void onComplete(#NonNull Task<Void> task) {
messageContent.setText("");
}
});
}
});
sendPictureButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
OpenGallery();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==GalleryPick && resultCode==RESULT_OK && data!=null)
{
ImageUri = data.getData();
AlertDialog.Builder alertadd = new AlertDialog.Builder(chatActivity.this);
LayoutInflater factory = LayoutInflater.from(chatActivity.this);
final View view = factory.inflate(R.layout.alertdialog_imageview_layout, null);
ImageView imageView = view.findViewById(R.id.dialog_imageview);
imageView.setImageURI(ImageUri);
alertadd.setView(view);
alertadd.setCancelable(false);
alertadd.setPositiveButton("Upload", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
loadingBar.setTitle("Picture Upload");
loadingBar.setMessage("Please wait while your image is being uploaded");
loadingBar.setCanceledOnTouchOutside(false);
loadingBar.show();
UploadImage();
dlg.dismiss();
}
});
alertadd.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) {
dlg.dismiss();
}
});
alertadd.show();
}
}
public void UploadImage(){
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentDate = new SimpleDateFormat("yyyy MM, dd");
saveCurrentDate = currentDate.format(calendar.getTime());
SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss:SSS a");
saveCurrentTime = currentTime.format(calendar.getTime());
pictureRandomKey = saveCurrentDate + saveCurrentTime;
final StorageReference filePath = chatImagesRef.child(ImageUri.getLastPathSegment() + pictureRandomKey + ".jpg");
final UploadTask uploadTask = filePath.putFile(ImageUri);
uploadTask.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e)
{
String message = e.toString();
Toast.makeText(chatActivity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
}
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot)
{
loadingBar.cancel();
Task<Uri> urlTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
#Override
public Task<Uri> then(#NonNull Task<UploadTask.TaskSnapshot> task) throws Exception
{
if (!task.isSuccessful())
{
throw task.getException();
}
downloadImageUrl = filePath.getDownloadUrl().toString();
return filePath.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task)
{
if (task.isSuccessful())
{
downloadImageUrl = task.getResult().toString();
DatabaseReference messageRef = FirebaseDatabase.getInstance().getReference();
Map<String, Object> userdataMap = new HashMap<>();
userdataMap.put("id", Prevelent.onlineUser.getEmail() + " : " + saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("content", downloadImageUrl);
userdataMap.put("sentByEmail", Prevelent.onlineUser.getEmail());
userdataMap.put("sentByName", Prevelent.onlineUser.getName());
userdataMap.put("sentToEmail", admin.getEmail());
userdataMap.put("sentToName", admin.getName());
userdataMap.put("sentAt", saveCurrentDate + " " + saveCurrentTime);
userdataMap.put("messageType", "picture");
messageRef.child("Messages").child(Prevelent.onlineUser.getEmail()).child(saveCurrentDate + " " + saveCurrentTime).
updateChildren(userdataMap)
.addOnCompleteListener(new OnCompleteListener<Void>(){
#Override
public void onComplete(#NonNull Task<Void> task) {
messageContent.setText("");
}
});
}
}
});
}
});
}
private void addMessage(Message message)
{
if(message.getMessageType().equals("text")){
if(message.getSentByEmail().equals(Prevelent.onlineUser.getEmail()))
{
addMyMessage(message);
}
else
{
addTheirMessage(message);
}
}else{
int id = View.generateViewId();
imagesUrl.put(id, message.getContent());
if(message.getSentByEmail().equals(Prevelent.onlineUser.getEmail()))
{
addMyMessageImage(message, id);
}
else
{
addTheirMessageImage(message, id);
}
}
}
private void addTheirMessageImage(Message message, int id) {
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.their_message_image, null);
TextView sender_name_view = v.findViewById(R.id.sender_name_view);
ImageView imageView = v.findViewById(R.id.receivedImageView);
TextView message_time = v.findViewById(R.id.received_message_box_time);
sender_name_view.setText(message.getSentByName());
Picasso.get().load(message.getContent()).into(imageView);
message_time.setText(getMomentAgo(message.getSentAt()));
imageView.setId(id);
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addMyMessageImage(Message message, int id) {
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.my_message_image, null);
ImageView imageView = v.findViewById(R.id.sentImageView);
TextView message_time = v.findViewById(R.id.sent_message_box_time);
Picasso.get().load(message.getContent()).into(imageView);
message_time.setText(getMomentAgo(message.getSentAt()));
imageView.setId(id);
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addTheirMessage(Message message)
{
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.their_message, null);
TextView sender_name_view = v.findViewById(R.id.sender_name_view);
TextView message_view = v.findViewById(R.id.sender_message_body);
TextView message_time = v.findViewById(R.id.received_message_box_time);
sender_name_view.setText(message.getSentByName());
message_view.setText(message.getContent());
message_time.setText(getMomentAgo(message.getSentAt()));
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
private void addMyMessage(Message message)
{
try {
View v = LayoutInflater.from(chatActivity.this).inflate(R.layout.my_message, null);
TextView message_view = v.findViewById(R.id.my_message_body);
TextView message_time = v.findViewById(R.id.sent_message_box_time);
message_view.setText(message.getContent());
message_time.setText(getMomentAgo(message.getSentAt()));
chat_messages_view_panel.addView(v);
scrollChatToBottom();
}catch (Exception ignored)
{
}
}
public void scrollChatToBottom() {
chat_messages_scroll_view.post(new Runnable() {
#Override
public void run() {
chat_messages_scroll_view.fullScroll(ScrollView.FOCUS_DOWN);
}
});
}
private void OpenGallery()
{
Intent galleryIntent = new Intent();
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GalleryPick);
}
#SuppressLint("SimpleDateFormat")
public String getMomentAgo(String date_time){
try{
SimpleDateFormat sourceFormat = new SimpleDateFormat("yyyy MM, dd HH:mm:ss:SSS a");
SimpleDateFormat destFormat = new SimpleDateFormat("dd MMM, HH:mm a");
Date convertedDate = sourceFormat.parse(date_time);
if (convertedDate != null) {
return destFormat.format(convertedDate);
}
}catch (Exception ignored){}
return "";
}
public void imageClick(View view)
{
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
Picasso.get().load(imagesUrl.get(view.getId())).into(imageView);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
public void loadMessages(){
FirebaseDatabase.getInstance().getReference().child("Messages").child(Prevelent.onlineUser.getEmail()).
addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot)
{
for(DataSnapshot item: snapshot.getChildren())
{
Message message = item.getValue(Message.class);
if(!message_ids.contains(message.getId()))
{
message_ids.add(message.getId());
addMessage(message);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
You can follow this tutorial:
Send Device-to-Device Push Notifications Without Server-side Code
Update
You can Listen for a database specific child and show notification when there is a change happens (Simulating Server Push notification)

Null Pointer Exception as notification was added

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)
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();

Registration Page does not record user data with Firebase

public class RegisterActivity extends AppCompatActivity {
//create variables
private EditText mUsername, mPassword, mEmail, mPhone;
private Button mRegister;
private TextView mLogin;
private FirebaseAuth mAuth;
private ImageView mProfilePicture;
String user_email, user_name, user_phone, user_password;
//on creation of activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
setupViews();
//firebase instance declared
mAuth = FirebaseAuth.getInstance();
//When register is clicked
mRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//if all fields are okay using validation method
if(validate()){
//get user info
String user_email = mEmail.getText().toString().trim();
String user_password = mPassword.getText().toString().trim();
String user_phone = mPhone.getText().toString().trim();
String user_name = mUsername.getText().toString().trim();
mAuth.createUserWithEmailAndPassword(user_email, user_password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
sendEmailVerification();
FirebaseUser user = mAuth.getCurrentUser();
Toast.makeText(RegisterActivity.this, "Registration Successful", Toast.LENGTH_SHORT).show();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Registration Failed", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
//Return user back to login page
mLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}
});
}
//setup views by id from xml
private void setupViews(){
mUsername = (EditText)findViewById(R.id.editTextNewUsername);
mPassword = (EditText)findViewById(R.id.editTextNewPassword);
mEmail = (EditText)findViewById(R.id.editTextNewEmail);
mPhone = (EditText)findViewById(R.id.editTextPhone);
mRegister = (Button)findViewById(R.id.buttonRegister);
mLogin = (TextView)findViewById(R.id.textViewLogin);
mProfilePicture = (ImageView)findViewById(R.id.imageViewProfilePicture);
}
//validate if all fields are okay and not empty
private Boolean validate() {
Boolean result = false;
//convert inputs to strings
String user_name = mUsername.getText().toString();
String user_password = mPassword.getText().toString();
String user_email = mEmail.getText().toString();
String user_phone = mPhone.getText().toString();
//check if any fields are empty, if not then return result
if (user_name.isEmpty() || user_password.isEmpty() || user_email.isEmpty() || user_phone.isEmpty()) {
Toast.makeText(this, "All fields are required for registration.", Toast.LENGTH_SHORT).show();
} else {
result = true;
}
return result;
}
private void sendEmailVerification(){
FirebaseUser firebaseUser = mAuth.getCurrentUser();
if(firebaseUser!=null){
firebaseUser.sendEmailVerification().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
sendUserData();
Toast.makeText(RegisterActivity.this, "Successfully Registered, Verification mail sent!", Toast.LENGTH_SHORT).show();
mAuth.signOut();
finish();
startActivity(new Intent(RegisterActivity.this, MainActivity.class));
}else{
Toast.makeText(RegisterActivity.this, "Verification mail has'nt been sent!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void sendUserData(){
FirebaseDatabase firebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference myRef = firebaseDatabase.getReference(mAuth.getCurrentUser().getUid());
UserProfile userProfile = new UserProfile(user_phone, user_email, user_name);
myRef.setValue(userProfile);
}
}
Solved the crash with my profile page and got it to save artifical data, but found out my registration page is the problem and is not recording data. Here is my Userprofile.java for reference
public class UserProfile {
public String user_phone;
public String user_email;
public String user_name;
public UserProfile() {
}
public UserProfile(String user_phone, String user_email, String user_name) {
this.user_phone = user_phone;
this.user_email = user_email;
this.user_name = user_name;
}
public String getUser_phone() {
return user_phone;
}
public void setUser_phone(String user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
Any help would be appreciated, i'd read extensively on the topic and can't seem to see whatever small issue is causing the hold-up. Any other pointers are also welcome.
Try changing:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
assert userProfile != null;
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
With:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserProfile userProfile = dataSnapshot.getValue(UserProfile.class);
if(userProfile != null){
mProfileName.setText(userProfile.getUser_name());
mProfileNumber.setText(userProfile.getUser_phone());
mProfileEmail.setText(userProfile.getUser_email());
}
}

deactivate account from firebase chat app

i'm using the firebase database for my chat application, When i click on the deactivate button it deletes the user from the Authentication section of firebase but not from the database section of firebase and my all user activity retrieve the user data from the database section. because of this when a user deactivate his account it get delete, but his account is still visible to the other user. below this i'm attaching my codes..
public class SettingsActivity extends AppCompatActivity{
ImageView ivCamera;
private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mProfileBtn;
private Button mDeactivateBtn;
//private Button mImageBtn;
private static final int GALLERY_PICK = 1;
private StorageReference mImageStorage;
private ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
mDisplayImage = (CircleImageView) findViewById(R.id.settings_image);
mName = (TextView) findViewById(R.id.settings_name);
mStatus = (TextView) findViewById(R.id.settings_status);
mProfileBtn = (Button) findViewById(R.id.settings_profile_btn);
mDeactivateBtn = (Button) findViewById(R.id.deactivate_btn);
ivCamera = (ImageView) findViewById(R.id.ivCamera);
mProgressDialog = new ProgressDialog(this);
mImageStorage = FirebaseStorage.getInstance().getReference();
mCurrentUser = FirebaseAuth.getInstance().getCurrentUser();
String current_uid = mCurrentUser.getUid();
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);
mUserDatabase.keepSynced(true);
mUserDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue().toString();
final String image = dataSnapshot.child("image").getValue().toString();
String status = dataSnapshot.child("status").getValue().toString();
String thumb_image = dataSnapshot.child("thumb_image").getValue().toString();
mName.setText(name);
mStatus.setText(status);
if (!image.equals("default")) {
//Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
Picasso.with(SettingsActivity.this).load(image).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.avatar).into(mDisplayImage, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(SettingsActivity.this).load(image).placeholder(R.drawable.avatar).into(mDisplayImage);
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//ivGallery =(ImageView) findViewById(R.id.ivGallery);
//ivGallery.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View view) {
//}
//});
mProfileBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name_value = mName.getText().toString();
String status_value = mStatus.getText().toString();
Intent status_Intent = new Intent(SettingsActivity.this, StatusActivity.class);
status_Intent.putExtra("status_value", status_value);
status_Intent.putExtra("name_value", name_value);
startActivity(status_Intent);
}
});
ivCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent();
galleryIntent.setType("image/*");
galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(galleryIntent, "SELECT IMAGE"), GALLERY_PICK);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_PICK && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri).setAspectRatio(1, 1).start(this);
//Toast.makeText(SettingsActivity.this, imageUri, Toast.LENGTH_LONG).show();
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mProgressDialog = new ProgressDialog(SettingsActivity.this);
mProgressDialog.setTitle("Uploading Image.....");
mProgressDialog.setMessage("Please wait while we upload and process the image.");
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
Uri resultUri = result.getUri();
File thumb_filePath = new File(resultUri.getPath());
String current_user_id = mCurrentUser.getUid();
Bitmap thumb_bitmap = new Compressor(this)
.setMaxWidth(200)
.setMaxHeight(200)
.setQuality(75)
.compressToBitmap(thumb_filePath);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
final byte[] thumb_byte = baos.toByteArray();
StorageReference filePath = mImageStorage.child("profile_images").child(current_user_id + ".jpg");
final StorageReference thumb_filepath = mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");
filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if (task.isSuccessful()) {
final String download_url = task.getResult().getDownloadUrl().toString();
UploadTask uploadTask = thumb_filepath.putBytes(thumb_byte);
uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> thumb_task) {
String thumb_downloadUrl = thumb_task.getResult().getDownloadUrl().toString();
if (thumb_task.isSuccessful()) {
Map update_hashMap = new HashMap();
update_hashMap.put("image", download_url);
update_hashMap.put("thumb_image", thumb_downloadUrl);
mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
mProgressDialog.dismiss();
Toast.makeText(SettingsActivity.this, "Success Uploading.", Toast.LENGTH_LONG).show();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading thumbnail.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else {
Toast.makeText(SettingsActivity.this, "Error in Uploading.", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
}
});
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
public static String random() {
Random generator = new Random();
StringBuilder randomStringBuilder = new StringBuilder();
int randomLength = generator.nextInt(10);
char tempChar;
for (int i = 0; i < randomLength; i++) {
tempChar = (char) (generator.nextInt(96) + 32);
randomStringBuilder.append(tempChar);
}
return randomStringBuilder.toString();
}
public void deactivate(View view)
{
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user!=null)
{
mProgressDialog.setTitle("Deactivate Account");
mProgressDialog.setMessage("Deactivating...");
mProgressDialog.show();
mUserDatabase.child(mCurrentUser.getUid()).removeValue();
user.delete().addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "Account is Deactivated", Toast.LENGTH_LONG).show();
finish();
Intent intent = new Intent(SettingsActivity.this, RegisterActivity.class);
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(), "Account could not be Deactivate", Toast.LENGTH_LONG).show();
}
mProgressDialog.dismiss();
}
});
}
}
}
i want that when the user deactivate his account it will not visible anymore in the all user activity
There are multiple ways to doing this.
When you delete account of user. You should delete all nodes attaching to that user. so that any activity related to user will not be visible to other users.!
if you don't want to remove from database section. you can put another key value with the name of status. if user status is deleted or disable. don't fetch the data of that user in activity.
Hope this will help you to answer your question.
if you've still questions in your mind, you can ask.
For deleting child:
rootRef.child(node).removeValue();
Simple deleting the node.
you can customize it according to your need.
DatabaseReference delete = FirebaseDatabase.getInstance().getReference().child("Node");
delete.setValue(null);

Categories

Resources