In-App notifications without server side coding in Firebase - android

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)

Related

Notification device to device

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

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.

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

Firebase Storage OnSuccessListeners not successful in time

After thorough debugging, I have concluded that the reason my GridView is not displaying any of my Images is because both of my OnSuccessListeners in getData() and getImage() from when I get the thumbnail and title from Firebase Storage are not successful yet.
I do all of this in my getData() method, which I call after the user selects their Google Place in onActivityResult. The method should instantiate a new ImageItem(Bitmap, String) but is returning a null ImageItem due to the onSucessListeners not being successful yet. Any ideas?
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
String v = m.get("url");
Log.d("url", v);
String bu = m.get("bucket");
Log.d("bucket", bu);
b = getImage(bu, v);
StorageReference iR = httpsReference.child(bu).child("thumb");
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
gridAdapter.data.add(new ImageItem(b, t, bu, v));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public Bitmap getImage(String bx, String vu) {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference httpsReference = storage.getReferenceFromUrl(myUrl);
String v = vu;
Log.d("url", v);
String bu = bx;
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
hasImage = true;
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
return b;
}
}
****************UPDATE 1/7/2017*********************
private void getData() {
imageItems = new ArrayList<>();
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child((String) p.getName()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterator<DataSnapshot> iter = dataSnapshot.getChildren().iterator();
FirebaseStorage storage = FirebaseStorage.getInstance();
final StorageReference httpsReference = storage.getReferenceFromUrl("gs://socialnetwork-4b0c9.appspot.com");
while (iter.hasNext()) {
hasImage = false;
hasTitle = false;
HashMap<String, String> m = (HashMap<String, String>) iter.next().getValue();
final String v = m.get("url");
Log.d("url", v);
final String bu = m.get("bucket");
Log.d("bucket", bu);
StorageReference iR = httpsReference.child(bu).child("thumb");
final long ONE_MEGABYTE = 1024 * 1024;
iR.getBytes(ONE_MEGABYTE).addOnSuccessListener(new OnSuccessListener<byte[]>() {
#Override
public void onSuccess(byte[] bytes) {
// Data for "images/island.jpg" is returns, use this as needed
b = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
httpsReference.child(bu).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
// Metadata now contains the metadata for 'images/forest.jpg'
t = storageMetadata.getCustomMetadata("title");
hasTitle = true;
gridAdapter.data.add(new ImageItem(b, t, bu, v));
Log.d("title", t);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
Log.d("error", "ERROr");
// Uh-oh, an error occurred!
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
************************METHOD PERTAINING TO GRIDVIEW AND GRIDADAPTER*********
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(this, data);
p = place;
gridView = (GridView) findViewById(R.id.grid_View);
gridAdapter = new GridViewAdapter(this, R.layout.grid_item_layout);
getData();
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
ImageItem item = (ImageItem) parent.getItemAtPosition(position);
//Create intent
Intent intent = new Intent(PlaceActivity.this, VideoActivity.class);
intent.putExtra("bucket", item.getBucket());
intent.putExtra("dUrl", item.getdUrl());
//Start details activity
startActivity(intent);
}
});
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(this, data);
// TODO: Handle the error.
} else if (resultCode == RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
This is a classic asynchronous programming issue:
var a = 1;
incrementAsync(function() {
a = 2;
});
console.log(a); // prints 1 because the function hasn't returned yet
You need to instead perform the action in the async function:
var a = 1;
incrementAsync(function() {
a = 2;
console.log(a); // prints 2 now
});
So I'd re-write your function as:
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
FirebaseStorage mStorage = FirebaseStorage.getInstance();
mDatabase.getReference("...").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
ModelObject modelObject = storage.getValue(ModelObject.class);
// Or just download the object here...
mStorage.getReferenceFromUrl(modelObject.getUrl()).getMetadata().addOnSuccessListener(new OnSuccessListener<StorageMetadata>() {
#Override
public void onSuccess(StorageMetadata storageMetadata) {
String title = storageMetadata.getCustomMetadata("title");
gridAdapter.data.add(...);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Uh-oh, an error occurred!
}
});
}
...
});

Firebase Implementation freezes app while downloading data

This is my Service class which is calling to all listener
public class DBService extends Service {
private static final String TAG = DBService.class.getName();
private DatabaseReference reference;
private static final String FIREBASE_EMAIL = "xxxxxxx#workindia.in";
private static final String FIREBASE_PASSWORD = "xxxxxx";
#Override
public void onCreate() {
super.onCreate();
FirebaseDatabase database = FirebaseDatabase.getInstance();
reference = database.getReference();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
FirebaseAuth auth = ((StartApplication) getApplication()).getAuth();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
if (user == null) {
String email = ObjectGraph.getEmployeeProfile().getEmail();
String password = ObjectGraph.getEmployeeProfile().getMobile_no();
if (password != null && !password.trim().isEmpty()) {
if (email == null || email.trim().isEmpty()) {
email = password + FIREBASE_EMAIL;
}
signIn(auth, email, FIREBASE_PASSWORD);
}
} else {
addListeners();
}
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
addListeners();
return null;
}
private void signIn(final FirebaseAuth auth, final String email, final String password) {
Log.i(TAG, "Login");
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
boolean isResetTimeStamp = true;
setTimeStamp(isResetTimeStamp);
addListeners();
} else {
register(auth, email, password);
}
}
});
FirebaseAuth.AuthStateListener authListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
Log.e(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
Log.e(TAG, "onAuthStateChanged:signed_out");
}
}
};
auth.addAuthStateListener(authListener);
}
private void addListeners() {
EmployeeProfile profile = ObjectGraph.getEmployeeProfile();
if (profile != null && profile.getMobile_no() != null && !profile.getMobile_no().trim().isEmpty()) {
reference.child(AppConstants.WORKINDIA_USERS_LAST_TIME).child(profile.getMobile_no().trim()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> child = (Map<String, Object>) dataSnapshot.getValue();
Log.e(TAG, "DATA " + child);
if (child == null) {
/*Query Listener Other listener*/
Query recentPostsQuery = reference.child(AppConstants.WORKINDIA_JOB_NODE).limitToFirst(1000);//.orderByChild("timestamp");
recentPostsQuery.addValueEventListener(jobBulKDownloadListener);
} else {
long lastSyncTime = (Long) child.get(AppConstants.TIMESTAMP);
Log.e(TAG, "DATA " + lastSyncTime);
/*Query Listener Other listener*/
Query recentPostsQuery = reference.child(AppConstants.WORKINDIA_JOB_NODE)
.orderByChild(AppConstants.TIMESTAMP)
.startAt(lastSyncTime)
.limitToFirst(1000);//.orderByChild("timestamp");
recentPostsQuery.addValueEventListener(jobBulKDownloadListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
});
}
}
private void register(final FirebaseAuth auth, final String email, final String password) {
Log.e(TAG, "register");
auth.createUserWithEmailAndPassword(email, password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.e(TAG, "register true");
signIn(auth, email, password);
} else {
Log.e(TAG, "register fail");
}
}
});
}
ValueEventListener jobBulKDownloadListener = new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(), "jobBulKDownloadListener+ onDataChange", Toast.LENGTH_SHORT).show();
new Thread(new Runnable() {
#Override
public void run() {
try {
if (dataSnapshot != null) {
long time = System.currentTimeMillis();
Log.d(TAG, "Start Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
List<Job> jobs = new ArrayList<Job>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
WrapperJob job1 = snapshot.getValue(WrapperJob.class);
Job job = job1.getData();
jobs.add(job);
}
if (jobs.size() > 0) {
parseJobs(jobs);
}
Log.d(TAG, "After Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
}
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
Crashlytics.logException(e);
}
}
}).start();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
};
private void parseJobs(List<Job> jobs) {
/* Job Operations*/
}
}
Why it is getting hanged ?? I have kept almost everything on background thread
This may not be the problem, but in your jobBulKDownloadListener it's probably safer to operate on the DataSnapshot on the main thread instead of your worker thread. You could refactor it like this:
ValueEventListener jobBulKDownloadListener = new ValueEventListener() {
#Override
public void onDataChange(final DataSnapshot dataSnapshot) {
Toast.makeText(getApplicationContext(), "jobBulKDownloadListener+ onDataChange", Toast.LENGTH_SHORT).show();
if (dataSnapshot != null) {
final List<Job> jobs = new ArrayList<Job>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
WrapperJob job1 = snapshot.getValue(WrapperJob.class);
Job job = job1.getData();
jobs.add(job);
}
if (jobs.size() > 0) {
new Thread(new Runnable() {
#Override
public void run() {
try {
long time = System.currentTimeMillis();
Log.d(TAG, "Start Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
parseJobs(jobs);
Log.d(TAG, "After Process : " + (System.currentTimeMillis() - time) / 1000 + " Seconds");
} catch (Exception e) {
Log.e(TAG, e.getMessage(), e);
Crashlytics.logException(e);
}
}
}).start();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e(TAG, databaseError.getMessage(), databaseError.toException());
}
};

Categories

Resources