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
Related
Here is my Firebase Realtime Database structure:
I want to retrieve each and every image in a child(images1,images2,images3,images4 are the child names)
private void loadmybanners1() {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("BannerImages");
ref.orderByChild("images2").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds : snapshot.getChildren()) {
final String myImg1 = "" + ds.child("image").getValue();
try{
Picasso.get().load(myImg1).networkPolicy(NetworkPolicy.OFFLINE).into(ban2Iv, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
Picasso.get().load(myImg1).into(ban2Iv);
}
});
} catch (Exception e) {
ban2Iv.setImageResource(R.drawable.ic_image);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
I have used this code to retrieve the image2. But from that, I can only retrieve the images1 child data. What are the modifications to do?
I want to retrieve each and every image in a child
To get each and every child within your BannerImages node, there is no need to use a query, you can simply use a DatabaseReference, as in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference bannerImagesRef = rootRef.child("BannerImages");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String myImg1 = dataSnapshot.child("images1").child("image").getValue(String.class);
Picasso.get().load(myImg1)
String myImg2 = dataSnapshot.child("images2").child("image").getValue(String.class);
Picasso.get().load(myImg2)
//And so on for the other images3, images4, and images5 children
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
bannerImagesRef.addListenerForSingleValueEvent(valueEventListener);
Add this dependency
implementation 'com.github.bumptech.glide:glide:4.10.0'
After getting Url from Firebase.Just Use below line
Glide.with(context).load(Firbase Url).into(imageView);
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 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();
}
}
});
Not sure why, but with the code I have, I cannot seem to get the value of 'isOnline':
dolRef = DatabaseReference dolRef = FirebaseDatabase.getInstance().getReference("DriversOnline");
dolRef = dolRef.child("iosDriver");
dolRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String driverid = ds.getKey();
// get value of 'isOnline'
dolRef = dolRef.child(driverid);
Log.e(TAG, "dolRef: " + dolRef);
dolRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dss : dataSnapshot.getChildren()) {
String online = dss.child("isOnline").getValue(String.class);
Log.e(TAG, "Online: " + online);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Below is a part of my firebase db:
"DriversOnline" : {
"iosDriver" : {
"BruEGfToc8axIWJk1o01fxcwd8I2" : { // driverId
"isOnline" : "true",
"latitude" : 45.276,
"longitude" : -66.064
}
}
}
Any idea why I can't get the value of 'isOnline' other than null ?
I think you're nesting your listeners one level deeper than needed.
DatabaseReference iosRef = FirebaseDatabase.getInstance().getReference("DriversOnline/iosDriver");
iosRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot driverSnapshot: dataSnapshot.getChildren()) {
String driverid = driverSnapshot.getKey();
DataSnapshot isOnlineSnapshot = driverSnapshot.child("isOnline");
System.out.println(isOnlineSnapshot.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
Some things to note:
Reassigning one generically named dolRef variable 4 times in a block of code like this is a code-smell. It makes it much harder to follow what's going on, and to check if the variable points to the right location. Give each of them a name that clearly indicates what they point to, as I've done above.
There is no need to attach a second listener, as the value of isOnline is right in the driverSnapshot. You can just request the child snapshot with the right name, and then the value from that.
Don't ignore error, as that hides potential problems. At the very least throw them, as I've done above.
driverid = FirebaseDatabase.getInstance().getReference("driver");//If there is another driver table, the path must be two layers.
driverid.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Driver driver = dataSnapshot.getValue(Driver.class);//class model
dolRef = FirebaseDatabase.getInstance().getReference("DriversOnline/iosDriver").child(driver.getDriverID);
dolRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
DriversOnline driversOnline= dataSnapshot.getValue(DriversOnline .class);//class model
log.d("driverid","isOnline :"+driversOnline.getisOnline)
//display -> isOnline : true
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
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.