How to pass Data from firebase database to sms? - java

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

Related

On Android, how do you get the data from an email address in Firebase, then access the child, and from there you access the other Firebase data?

The following file explains better what I really mean. It's a screenshot of data sent from a dummy user in Firebase:
The code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
// ref.addValueEventListener(new ValueEventListener() {
ref.orderByChild("Email").equalTo("testing3#testing.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = dataSnapshot.child("Name").getValue().toString();
String state = dataSnapshot.child("State").getValue().toString();
String stateRegion = dataSnapshot.child("StateRegion").getValue().toString();
String telephone = String.valueOf(dataSnapshot.child("Telephone").getValue());
nameEditText.setText(name);
stateEditText.setText(state);
stateRegionEditText.setText(stateRegion);
telephoneEditText.setText(telephone);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Please, can some person help?
More information about data stored in the Firebase:
Because I cannot see a more detailed database schema of yours, I assume that all those user objects are direct children under your Users node, and also assuming that you want to find the user that has the Email set to testing3#tesing.com, to display his particular details, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryUsersByEmail = usersRef.orderByChild("Email").equalTo("testing3#testing.com");
queryUsersByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("Name").getValue(String.class);
Log.d("TAG", name);
String state = ds.child("State").getValue(String.class);
Log.d("TAG", state);
String stateRegion = ds.child("State Region").getValue(String.class);
Log.d("TAG", stateRegion);
String telephone = ds.child("Telephone").getValue(String.class);
Log.d("TAG", telephone);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Paul SMith
Rio de Janeiro
Rio de Janeiro
(00)00000-0000

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......
}

Unable to fetch data from Firebase (Android)

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

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 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