Unable to fetch data from Firebase (Android) - java

I am trying to fetch the data from the google firebase but every time i tried to fetch the data. "Else" case is running everytime. Tried to change if(dataSnapshot.exists()) but getting the same error. Please help to resolve it.
public void retrieveProfileInfo() {
currentUserID = mAuth.getUid();
key = rootRef.child("profiles").push().getKey();
rootRef.child("users-profiles").child(currentUserID).child(key)
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
if ((dataSnapshot.child("name").getValue()) != null){
String retrieveName = dataSnapshot.child("name").getValue().toString();
String retrieveStatus = dataSnapshot.child("about").getValue().toString();
nameBox.setText(retrieveName);
aboutBox.setText(retrieveStatus);
} else {
Toast.makeText(UserProfileActivity.this, currentUserID+"else - retrieveProfileInfo()",
Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
Log.i("retrieveProfileInfo : ", "error is : " + e);
Toast.makeText(UserProfileActivity.this, e+" : Error",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}

You cant push a random key and read from it, you need to loop through children under users-profile/userID:
public void retrieveProfileInfo() {
//current user ID
currentUserID = mAuth.getUid();
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds:dataSnapshot.getChildren()){
//get the values
String name = ds.child("name").getValue(String.class);
String about = ds.child("about").getValue(String.class);
String uid = ds.child("uid").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// log error
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
rootRef.child("users-profiles").child(currentUserID).addValueEventListener(listener);
}

Related

When I send a message I can see it in firebase but i cannot read it on emulator or my phone it show nothing

I am making chat app ... but when i send a message it sent and i can see it on firebase but in emuloter and phone i can't ... why it happen ? i think problem may be in readMessages()
This is my chat activity class
userQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String name = "" + ds.child("name").getValue();
hisImage = "" + ds.child("image").getValue();
nameTv.setText(name);
try {
Picasso.get().load(hisImage).placeholder(R.drawable.ic_defult_img_face).into(profileTv);
} catch (Exception e) {
Picasso.get().load(R.drawable.ic_defult_img_face).into(profileTv);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = messageEt.getText().toString().trim();
if (TextUtils.isEmpty(message)) {
Toast.makeText(ChatActivity.this, "Cannot send empty message...", Toast.LENGTH_SHORT).show();
} else {
sendMessage(message);
}
}
});
readMessages();
seenMessages();
}
read and send function
private void readMessages() {
chatList = new ArrayList<>();
DatabaseReference dbRef = FirebaseDatabase.getInstance().getReference("Chats");
dbRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
chatList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Modelchat chat = ds.getValue(Modelchat.class);
if (myUid.equals(chat.getReceiver()) && hisUid.equals(chat.getSender()) ||
hisUid.equals(chat.getReceiver()) && myUid.equals(chat.getSender())) {
chatList.add(chat);
}
adapterChat = new AdapterChat(ChatActivity.this, chatList, hisImage);
adapterChat.notifyDataSetChanged();
recyclerView.setAdapter(adapterChat);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void sendMessage(String message) {
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
String timeStamp = String.valueOf(System.currentTimeMillis());
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("Sender", myUid);
hashMap.put("receiver", hisUid);
hashMap.put("message", message);
hashMap.put("timeStamp", timeStamp);
hashMap.put("isSeen", false);
databaseReference.child("Chats").push().setValue(hashMap);
messageEt.setText("");
}
anyone can help me ?
if you want more code or please comment and i will submit it.
I will give some hints:
Move this in your readMessages():
chatList.clear();
And place it under this:
chatList = new ArrayList<>();
//here...
Make sure that your Modelchat looks like this:
class Modelchat{
//the main thing is that these must be written exactly like the keys in your database
private String Sender;
private String receiver;
private String message;
private String timeStamp;
private boolean isSeen;
public Modelchat(String Sender,String receiver,String message,String timeStamp,boolean isSeen){
this.Sender=Sender;
this.receiver=receiver;
this.message=message;
this.timeStamp=timeStamp;
this.isSeen=isSeen;
}
//generate also getters and setters......
}

How to pass Data from firebase database to sms?

I am getting a data from my firebase database, but when I pass it to a parameter and use it to write in SMS it only get one data in SMS, but when I use toast it displays all the data but when i pass to sms i only getting one? whats wrong in my code? and how can I display all data i retrieve in my sms function bellow are my code and a screenshot of my firebasedatabase, I want to display all productName and quantity.
thank you for your help
Firebasedatabase Example
=== smsSendToBtn (This code is for retrieving the data from the Firebasedatabase) ===
smsSendToBtn.setOnClickListener(new View.OnClickListener() {
//private String Cart;
public void onClick(View view) {
DatabaseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
final DatabaseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
String getDate = snap.getKey();
reff2.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
String myProductName = snap1.child("productName").getValue(String.class);
String myQuantity = snap1.child("quantity").getValue(String.class);
Toast.makeText(getApplicationContext(),myProductName + " " + myQuantity,Toast.LENGTH_SHORT).show();
setSMSData(myProductName,myQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
=== setSMSdata function ===
private void setSMSData (String myProductName, String myQuantity) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", "Order "+ myProductName +" "+ myQuantity +" (Sent Via
SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
This is an example
List<String> prods = new ArrayList<>();
List<String> quantity = new ArrayList<>();
smsSendToBtn.setOnClickListener(new View.OnClickListener() {
//private String Cart;
public void onClick(View view) {
DatabaseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
final DatabaseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
String getDate = snap.getKey();
reff2.child("User View").child(Prevalent.CurrentOnlineUsers.getPhone()).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
String myProductName = snap1.child("productName").getValue(String.class);
String myQuantity = snap1.child("quantity").getValue(String.class);
prods.Add(myProductName );
quantity.Add(myQuantity);
Toast.makeText(getApplicationContext(),myProductName + " " + myQuantity,Toast.LENGTH_SHORT).show();
}
setSMSData(prods,quantity);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
SetSMSData
private void setSMSData(List<String> products,List<String> quantitys) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
List<String> format = new ArrayList<>();
int i=-1;
foreach(String str in products){
i++;
format.Add(str+":"+quantitys[i];
}
String formats= Arrays.toString(format);
smsSIntent.putExtra("sms_body", "Order "+formats+" (Sent Via SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}

How to retrieve data from firebase database and pass all the data to sms

How can i get all the data under my Products Firebase database, i only want to get the productName and quantity. the date in the image is my productID not actual date. my problem is i only get one productName and quantity in under the Product table.
so far this is the code i created
=== This is my current code ===
=== this is the onclick method ===
DatabseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
DatabseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("User View").child(phoneNumber).child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
//first get all the dates
String getDates = snap.getKey();
//add all the dates to reff2
reff2.child("User View").child(phoneNumber).child("Products").child.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
//value of product
String myProductName = snap1.child("ProductName").getValue(String.class);
//value of quanity just convert it to int if you want to calculate
String myQuantity= snap1.child("quantity").getValue(String.class);
//add your method
setSMSData(myProductName,myQuantity);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
=== THis is the setSMSData ====
private void setSMSData (String myProductName, String myQuantity) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", "Order "+ myProductName +":"+ myQuantity +" (Sent Via SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
IF you want to get all the productName and quantity on a specific number base on your structure you can use this
DatabaseReference reff = FirebaseDatabase.getInstance().getReference("Cart List");
final DatabaseReference reff2= FirebaseDatabase.getInstance().getReference("Cart List");
reff.child("user View").child("09553706928").child("Products").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap: dataSnapshot.getChildren()){
String getDate = snap.getKey();
reff2.child("user View").child("09553706928").child("Products").child(getDate).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snap1: dataSnapshot.getChildren()){
String myProductName = snap1.child("ProductName").getValue(String.class);
Toast.makeText(getApplicationContext(),myProductName,Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
And in your method setSMSData()
private void setSMSData(String productName,String quantity) {
// add the phone number in the data
Uri uri = Uri.parse("smsto:" + "09257777547");
Intent smsSIntent = new Intent(Intent.ACTION_SENDTO, uri);
// add the message at the sms_body extra field
smsSIntent.putExtra("sms_body", "Order "+ productName+":"+quantity+" (Sent Via
SKIP MOBILE)");
try{
startActivity(smsSIntent);
} catch (Exception ex) {
Toast.makeText(CartActivity.this, "Your sms has
failed...",
Toast.LENGTH_LONG).show();
ex.printStackTrace();
}
}
});

How can i bring just one data from firebase database?

I want to know how to get one data from the list of key
i know the key
but what i want to just get from one data what i saved
i don't understand why it is null
in the value 'petcode' is saved key
This is what i trying to get the data petname
reference = FirebaseDatabase.getInstance().getReference().child("Pets").child(firebaseUser.getUid()).child(petcode);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
petname = String.valueOf(dataSnapshot.child("petname"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
but when i see the log
petname value is null
how can i get data from it?
try this:-
ref.child("-LiCZpsymgNgtNcCinpHR5").child("petname").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
try {
if (snapshot.getValue() != null) {
try {
Log.e("TAG", "" + snapshot.getValue()); // your name values you will get here
} catch (Exception e) {
e.printStackTrace();
}
} else {
Log.e("TAG", " it's null.");
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("onCancelled", " cancelled");
}
});
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("Pets").child(firebaseUser.getUid()).child(petcode).child("petname");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String petname = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
conformDialog.setMessage("Something bad happened!, try again");
conformDialog.setCancelable(true);
conformDialog.setCanceledOnTouchOutside(true);
}
});
and do not use addValueEventListener for a single event, it will monitor forever

How to create a condition if there is the same value in firebase

How can I see if there is an equal value in a child and not save if it exists.
I tried doing this here but it did not work:
How can I check if a value exists already in a Firebase data class Android
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario);
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("id")) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Create yourself another function that pushes the data to firebase and call it from inside your listener. (in this example, create the function pushValueToFirebase)
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean exists = false;
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals(idUsario) {
exists = true;
}
}
if (!exists) {
//Your code here to push idUsario
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this:
FirebaseAuth autenticacao = ConfiguracaoFirebase.getFirebaseAutenticacao();
final String idUsuario = CustomBase64.codificarBase64(autenticacao.getCurrentUser().getEmail());
DatabaseReference firebase = ConfiguracaoFirebase.getFirebaseDatabase().child("historico").child(idUsuario).child("id");
firebase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Toast.makeText(getActivity(), "Exist", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity(), "No Exist", Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Add the child id to the reference above child("historico").child(idUsuario).child("id") then use exists() to check if this dataSnapshot is in your database.

Categories

Resources