Hi I am trying to develop an application. I can tell you I'm new to this. I want to aggregate the number values of children under a title using Firebase database. How can I achieve this?
Example Children1 = "10" Children2 = "20" I want Children1 + Children2 = 30
You can try this
private FirebaseDatabase database = FirebaseDatabase.getInstance();
private final DatabaseReference myRef = database.getReference("IndexOfYourDatabase"); //Init your ref according to your index
private int res = 0;
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
res += Integer.parseInt(messageSnapshot.child("").getValue().toString()); //acces to the value of every child and count them in res.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
Don't forget to replace IndexOfYourDatabase by gour Index
By this way you implement a for loop to add up the values of your children
If you want to calculate single values from different childrens then use below code :-
FirebaseDatabase.getInstance().getReference().child("database root name").child("database root field key").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int val1 = Integer.parseInt(dataSnapshot.child("childern1").getValue().toString();
int val2 = Integer.parseInt(dataSnapshot.child("childern2").getValue().toString();
int total = val1 +val2;
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you want to calculate number of records,
private int totalval= 0;
FirebaseDatabase.getInstance().getReference().child("database root name").child(database root key name).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot innerChild : dataSnapshot.child("childern1").getChildren()) {
totalVal + = Integer.parseInt(innerChild.child("").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Related
Hello all i have a my fire-base structure like this
Firebase Database
I have an array list inside an node in fire-base , I need to loop through this list and jump to each ID to get information i need like the database photo shows.
what I've tried so far
public static void checkIfCurrentUserLiked(final HomeFragment.PostsViewHolder postsViewHolder, String postKey) {
userID = Objects.requireNonNull(FirebaseAuth.getInstance().getCurrentUser()).getUid();
likesRef = FirebaseDatabase.getInstance().getReference().child("likes");
postsRef = FirebaseDatabase.getInstance().getReference().child(postKey);
postsRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("likes")) {
for (DataSnapshot ds : dataSnapshot.child("likes").getChildren()) {
likesRef.child(Objects.requireNonNull(ds.getValue()).toString())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
Like like = snapshot.getValue(Like.class);
if (like != null && like.getLikedUserID().equals(userID)) {
postsViewHolder.likesImage.setImageResource
(R.drawable.ic_item_home_post_like_filled);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) { }
});
}
i have no error , just nothing happens , data are not fetched as expected
Change this:
postsRef = FirebaseDatabase.getInstance().getReference().child(postKey);
into this:
postsRef = FirebaseDatabase.getInstance().getReference().child("posts").child(postKey);
According to your database, you have node posts before the postKey, therefore you need to add it when referencing to a location.
Above is my firebase database I am trying to pull from.
As you can see I have a "table" called "Make". I have succesfully been able to pull this data into a Listview within my app. The code for this is below.
I now need to pull all the data from "VW_Data" table. This table has over 1000 childen named as "0" up to "1000" with the same headings in each such as "Bearing", "Altitude" etc but with different values. I would like to be able to pull "Bearing" value only from ALL 1000 children of "VW_Data" and display in a list.
However i have attempted only to try pull "VW_Data/0/Bearing" multiple ways which have not worked.
Here is my updated code for this class:
public class Graphview extends Activity
{
//Holds the values gathered from firebase
final ArrayList<String> graphlist = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//Sets the layout according to the XML file
setContentView(R.layout.activity_graphview);
//XML variable
final ListView listViewG = findViewById(R.id.listviewG);
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
database.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot datas : dataSnapshot.getChildren())
{
String bearing = (String) datas.child("Bearing").getValue();
//Add the info retrieved from datasnapshot into the ArrayList
graphlist.add(bearing);
arrayAdapter = new ArrayAdapter<>(Graphview.this, R.layout.itemview, graphlist);
listViewG.setAdapter(arrayAdapter);
//Will refresh app when the data changes in the database
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}//End onCreate()
Try this :
DatabaseReference database = FirebaseDatabase.getInstance().getReference().child("VW_Data");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> verticalSnapshotItr = dataSnapshot.getChildren();
if (verticalSnapshotItr != null) {
for (DataSnapshot verticalItemSnapshot : verticalSnapshotItr) {
String altitude = (String) verticalItemSnapshot.child("Altitude").getValue();
// Parse rest keys here
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try this:
DatabaseReference db = FirebaseDatabase.getInstance()
.getReference()
.child("VW_Data");
db.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String bearing = datas.child("Bearing").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
snapshot is at VW_Data then use the for loop, you will be able to iterate inside "0" and retrieve the value bearing
I have data in database:
database in firebase
I want read all child (Belgia, Czechy, Polska...) and display it in Text Field, but AFTER click the button (I don't change data in database).
The button have assigned below function:
public void f_btn_zaczytaj_dane(View view) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String value = dataSnapshot.getValue(String.class);
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
txt_opis_panstwa.setText(value);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Befrore i write in code:
FirebaseDatabase database;
DatabaseReference myRef;
database = FirebaseDatabase.getInstance();
myRef = database.getReference("kraj");
Unfortunately, when I press the button nothing happens.
I will be grateful for the help
Regards, Marcin
You have to iterate through your children
public void f_btn_zaczytaj_dane(View view) {
myRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
for (DataSnapshot country : dataSnapshot.getChildren()) {
txt_opis_panstwa.append(country.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference krajRef = rootRef.child("flagiistolice").child("kraj");
public void f_btn_zaczytaj_dane(View view) {
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
TextView txt_opis_panstwa = (TextView) findViewById(R.id.txt_opis_panstwa);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String country = ds.getkey();
txt_opis_panstwa.append(country);
Log.d("TAG", country);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
krajRef.addListenerForSingleValueEvent(eventListener);
}
I want to query the data from Firebase on Android.
And this is my data
And this is my Android Studio code :
Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
myFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
int size= (int) snapshot.getChildrenCount();
txtMyCoffee.setText(""+size);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Question : The total count of the children is 4. How would I filter the children to only count children whose "coffeeNo" is "Acoffee"?
Just improve your query to get only the result your are looking for:
DatabaseReference databaseRef = FirebaseDatabase.getInstance().getReferenceFromUrl("https://....../myCoffee/"+phone+"");
Query acoffeeQuery = databaseRef.orderByChild("coffeeNo").equalTo("Acoffee");
acoffeeQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
final int size = (int) snapshot.getChildrenCount();
//size is equal to 2
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
This way, you do not have to loop over all results and you do not have
to implement a counter manually.
Please use the following code:
Firebase rootRef = new Firebase("https://....../myCoffee/" + phone);
rootRef.addValueEventListener(new ValueEventListener() {
Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String coffeeNo = ds.child("coffeeNo").getValue(String.class);
if(coffeeNo.equals("Acoffee")) {
size++;
}
}
txtMyCoffee.setText(String.valueOf(size));
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
Edit: Another approach is to use a simple query like this:
Firebase rootRef = new Firebase("https://....../myCoffee/"+phone+"");
Query query = rootRef.orderByChild("coffeeNo").equalTo("Acoffee");
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int size = (int) dataSnapshot.getChildrenCount();
txtMyCoffee.setText(String.valueOf(size));
}
#Override
public void onCancelled(FirebaseError firebaseError) {}
});
Your txtMyCoffee in both cases will display: 2.
Firebase myFirebaseRef = new Firebase("https://....../myCoffee/"+phone+"");
myFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
int count=0;
for(DataSnapshot item: dataSnapshot.getChildren())
{
String coffeeNo=item.child("coffeeNo").toString();
if(coffeeNo.equals("Acofee")
count+=1;
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
Try something like this
This is my randomly retrieving data codes:
mDataSelect.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> lst = new ArrayList<String>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Collections.shuffle(lst);
lst.add(String.valueOf(ds.getKey()));
randomGenerator = new Random();
int index = randomGenerator.nextInt(lst.size());
String item = lst.get(index);
idofcaps.setText(item);
final DatabaseReference capsSelect = mDataSelect.child(item);
capsSelect.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dss) {
String post_Image = (String) dss.child("Image").getValue();
Picasso.with(StartCapsActivity.this).load(post_Image).into(caps);
String post_name = (String) dss.child("Translation").getValue();
translation.setText(post_name);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
});
I have a next button in my screen which has the same code for retrieve another image from database. However, I don't want to retrieve same image again. How can I prevent this redundancy?
Create an arraylist then add the retrieved key. Then remove possible duplicate keys. How do I remove repeated elements from ArrayList?