I want to get to a listview the data on "Categorias" folder, but i try everthing and i can't do this.
Fragment code:
myRef.addValueEventListener(new ValueEventListener() {
public static final String TAG = "TNW";
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
list3 values = td.values();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity().getApplicationContext(), "Ese usuario ya existe ", Toast.LENGTH_SHORT).show();
}
});
Its very simple, here is the code to fetch your values.
DatabaseReference db = FirebaseDatabase.getInstance().getReference("people");
db.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
//get the categorias node
DataSnapshot dsCategorias = ds.child("categorias");
//loop inside the categorias node for all children
for(DataSnapshot dbValSnapshot: dsCategorias.getChildren()){
//Assuming all children have only boolean values
//getting the key and the values
String key = dbValSnapshot.getKey();
boolean value = dbValSnapshot.getValue(Boolean.class);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Let me know if you are not able to understand any part of my code. Thanks
Related
I want to change the value of child "toggleStatus" under Reference "BetSlip" as shown below. The already set value is "on" so I want such that when I click the button the value of "toggleStatus" is changed to "off"
BetSlipActivity.toggleCollapse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = betSlip.get(position).getTimeStamp();
String toggleStatus = betSlip.get(position).getToggleStatus();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
//set value to off
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
//set value to on
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
If you've got the DataSnapshot for a path in the database, it's easy to get the DatabaseReference that you need to update it:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("BetSlip");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot ds: snapshot.getChildren()) {
String timestamp = ""+ ds.child("timeStamp").getValue();
String toggleStatus = ""+ ds.child("toggleStatus").getValue();
if (timeStamp.equals(timestamp) && toggleStatus.equals("on")) {
ds.child("toggleStatus").getRef().setValue("off");
}
if (timeStamp.equals(timestamp) && toggleStatus.equals("off")) {
ds.child("toggleStatus").getRef().setValue("on");
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
Since you're updating the node based on its existing value, strictly speaking you might need to use a transaction for it.
I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: dataSnapshot "+dataSnapshot.getValue());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I'm new to android app development and firebase as well. i m fetching data from sample node and getting DataSnapshot value like below.
{size=[Small, Large, Ex-Large], type=[Type 1, Type 2], color=[Red, Green, Blue], category=[T-Shirt, Jeans, Sweater]}
need some expect help, any suggestion will greatly appreciated.
Thanks
To retrieve values separately, you can use a code like this:
databaseReference.child("category").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (int i=0;i<3;i++) {
// category is an ArrayList you can declare above
category.add(dataSnapshot.child(String.valueOf(i)).getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { // Do something for this
}
});
Similarly you can add values of other nodes in your other ArrayLists, just by changing the value of Childs in this code.
Firebase has no native support for arrays. If you store an array, it really gets stored as an "object" with integers as the key names.
// we send this
['hello', 'world']
// Firebase stores this
{0: 'hello', 1: 'world'}
Best Practices: Arrays in Firebase
// TRY THIS
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
youNameArray = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
String data = snapshot.getValue(String.class);
youNameArray.add(data);
}
Log.v("asdf", "First data : " + youNameArray.get(0));
}
Something like this:
databaseReference = FirebaseDatabase.getInstance().getReference("/sample");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot sampleSnapshot: dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange: sampleSnapshot "+sampleSnapshot.getKey()+" = "+sampleSnapshot.getValue());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
The difference is that in my answer I loop over dataSnapshot.getChildren() to get each individual sample snapshot. The sampleSnapshot.getValue() call should return a List.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference refence = database.getReference();
refence.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot snapshot) {
// TODO Auto-generated method stub
ArrayList array= new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()){
String data = ds.getValue().toString();
array.add(data);
}
System.out.println(array);
}
#Override
public void onCancelled(DatabaseError error) {
// TODO Auto-generated method stub
}
});
In my case String.class does not work instead .toString method works
String data = ds.getValue().toString();
I have the following Firebase Database :
I need to delete all the entries/database objects sharing the same "date_cours" type.
I tried the following method to delete all the entries sharing the same date_cours "10/09/2018", for example :
private void Delete_CR_Lessons(Date date) {
final String date_a_supprimer_string = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.child("date_cours").orderByKey().equalTo("10/09/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
dataSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
}//fin de la methode Delete_CR_Lessons
I have no error during the execution of the method.
In the Logs, I can see my Log "test1" but not the log "test2".
Does anyone know what I am missing ?
You are providing wrong path and than you are trying to delete wrong datasnapshot value for example try to use: postsnapshot.getRef().removeValue(); instead of dataSnapshot.getRef().removeValue(); because dataSnapshot doesn't point to the value which you want to delete. That is why you used for loop to get all value nodes from your database. Check code below:
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.orderByChild("date_cours").equalTo("01/10/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
postsnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});