Calculating the sum of Firebase records values - android

I have a database structure like this one here.
My objective is to get the total of the two amounts 12000 and 15000 and that would be 27000..However the code i have tried to use is giving me a value like null1200015000 . Here is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mystatement);
listview = (ListView) findViewById(R.id.listview);
textView4 = (TextView) findViewById(R.id.textView4);
dref = FirebaseDatabase.getInstance().getReference();
DatabaseReference dref = FirebaseDatabase.getInstance().getReference();
dref = dref.child("Expenditure");
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
//Adding it to a stringString expenses = "Amount: "+dogExpenditure.getAmount()+"\nReason for Use: "+dogExpenditure.getItem()+"\n\n";
String amount = dogExpenditure.getAmount();
textView4.setText(amount);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
Anyone with an idea on how to achieve this???
Here is my DogExpenditure class:
public class DogExpenditure {
private String amount;
private String item;
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
}

Define DogExpenditure dogExpenditure globally and Use this
dref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
//Adding it to a stringString expenses = "Amount: "+dogExpenditure.getAmount()+"\nReason for Use: "+dogExpenditure.getItem()+"\n\n";
}
if(dogExpenditure.size()>0){
int amt=0;
for(int i=0;i<dogExpenditure.size();i++){
amt =amt+Integet.parseInt(dogExpenditure.get(i).getAmount())
}
textView4.setText(""+amt);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});

If I understand it correctly it should be quite simple:
First, change amount in DogExpenditure into double or int:
public class DogExpenditure {
private int amount;
...
public int getAmount() {
return amount;
}
...
}
Then inside your onDataChange() just increment it by each amount value. Like this:
public void onDataChange(DataSnapshot snapshot) {
int totalAmount = 0;
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
DogExpenditure dogExpenditure = postSnapshot.getValue(DogExpenditure.class);
totalAmount += dogExpenditure.getAmount();
}
textView4.setText(totalAmount.toString());
}

Related

Do calculation by retrieving data from Child Node is not working at all in Android Studio/Firebase

I have a problem to do subtract calculation by retrieving data from a Child Nod. As you can see my layout below, what I want to do is to get Remaining Kcal value by calculating Daily Kcal value minus Total Kcal and display the Remaining Kcal to the TextView.
I suspected the calculation for the subtraction part (code below) is not working at all as I tried to put the remainingCount/remainingCalorie value into firebase but nothing happened.
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is relevant code to do this operation, whereby I need to retrieve "daily calorie' from User first, then I can do the substraction daily calorie (Required Kcal) - total calorie consume (Total Kcal) = Remaining Calorie (Remaining Kcal):
//**********************DATABASE REFERENCE FOR USER REQUIRED CALORIE***************************//
requiredCalorieRef = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
requiredCalorieRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String userCalorieSuggestion = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
userRequiredCalorie.setText((userCalorieSuggestion +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//CALCULATE AND DISPLAY TOTAL CALORIE ACCORDING TO DATE
private void updateTotalCalorie(final String date_n) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("UsersRecords").child(FirebaseAuth.getInstance().getCurrentUser().getUid()).child(date_record);
nameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for (DataSnapshot foodTypeSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: foodTypeSnapshot.getChildren()) {
double foodCalorie = Double.valueOf(recordSnapshot.child("foodCalorie").getValue(String.class));
count = count + foodCalorie;
userTotalCalorie.setText((count +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("totalCalorie", count);
values.put("Date Consume", date_n);
final double finalCount = count;
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
updateRemainingKcal(finalCount);
}
});
}
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
//CALCULATE AND DISPLAY REMAINING CALORIE
private void updateRemainingKcal(final double finalCount) {
DatabaseReference userRecord = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = userRecord.child("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double remainingCount = 0;
for (DataSnapshot userChild: dataSnapshot.getChildren()) {
for (DataSnapshot recordSnapshot: userChild.getChildren()) {
double userCalorie = Double.valueOf(recordSnapshot.child("daily calorie").getValue(String.class));
remainingCount = userCalorie - finalCount;
userRemainingCalorie.setText((remainingCount +"kcal"));
myHistoryRef = FirebaseDatabase.getInstance().
getReference("History").child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date_record).child("Total Calorie");
Map<String, Object> values = new HashMap<>();
values.put("remainingCalorie", remainingCount);
myHistoryRef.updateChildren(values).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
});
}
}
Log.d("TAG", remainingCount + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
This is my firebase looks like - there is no node of RemainingCalorie at all at History node:
How can I solve this issue despite knowing the problem. I have tried several ways but nothing could help to solve this code problem.
I have solved my own problem. Thank you, finally did it. This is right code for those who have same problem in future:
private void updateRemaining(final int finalCount) {
userDatabase = FirebaseDatabase.getInstance().getReference("Users").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
userDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
String user = String.valueOf((dataSnapshot.child("daily calorie").getValue()));
int dailyCalorie = Integer.parseInt(user);
int remainingCalorie = dailyCalorie-finalCount;
userRemainingCalorie.setText((remainingCalorie +"kcal"));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
throw databaseError.toException();
}
});
}
this is the screen-shot

Need help regarding a firebase Query to append the values of a key from multiple nodes of the same child

I want to retrieve the value for each category and then add it to the MPAndroid Pie Chart module that I'm using.
Basically, I want to:
Get value for Communication from month 1
Get value for Communication from month 2
Add the values
Add it to my List Cats with Cats.add(new PieEntry(my_total_value,category_name);
This is what I'm currently implementing for my radar chart but it duplicates each category for each month because it adds a value to the list for each month:
public void setYearRadar(final String date, boolean incexp)
{
final String incexpt;
if(incexp)
{
incexpt="Expense";
}
else
{
incexpt="Income";
}
final DatabaseReference dRef = FirebaseDatabase.getInstance().getReference();
dRef.child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date)
.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Rcats = new ArrayList<>();
Rlabel = new ArrayList<>();
for (DataSnapshot d: dataSnapshot.getChildren())
{
Query expQuery =
dRef.child("Users")
.child(cAuth.getCurrentUser().getUid())
.child(date)
.child(d.getKey())
.child("Transactions")
.child("Category")
.child(incexpt);
if(expQuery!=null)
{
expQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Float x=0f;
for (DataSnapshot d : dataSnapshot.getChildren())
{
x = x + Float.parseFloat(d.getValue().toString());
}
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (Float.parseFloat(d.getValue().toString()) > 0.0)
{
Rcats.add(new RadarEntry(Float.parseFloat(d.getValue().toString())/x*100, d.getKey())); //Adding value and converting to percentage
Rlabel.add(d.getKey());
}
}
if (!Rcats.isEmpty()&& Rcats.size()>2 && Rlabel.size()>2)
{
initRadarChart(Rcats,Rlabel,date,incexpt);
}
else
{
rc.setVisibility(LinearLayout.GONE);
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
This is how my Categories look like
This is my whole data structure
And here is the even more messy PieChart class
private void setYearPie(final String date, Boolean incexp)
{
final String incexpt;
if(incexp)
{
incexpt="Expense";
}
else
{
incexpt="Income";
}
final DatabaseReference dRef = FirebaseDatabase.getInstance().getReference();
dRef.child("Users")
.child(FirebaseAuth.getInstance().getCurrentUser().getUid())
.child(date)
.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
Ycats = new ArrayList<>();
Ylabel = new ArrayList<>();
for (DataSnapshot d: dataSnapshot.getChildren())
{
Query expQuery =
dRef.child("Users")
.child(cAuth.getCurrentUser().getUid())
.child(date)
.child(d.getKey())
.child("Transactions")
.child("Category")
.child(incexpt);
if(expQuery!=null)
{
expQuery.addListenerForSingleValueEvent(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
for (DataSnapshot d : dataSnapshot.getChildren())
{
if (Float.parseFloat(d.getValue().toString()) > 0.0)
{
Ycats.add(new PieEntry(Float.parseFloat(d.getValue().toString()), d.getKey()));
Ylabel.add(d.getKey());
x = 0f;
}
if (!Ycats.isEmpty())
{
initPieChart(Ycats,Ylabel,date,incexpt);
}
else
{
//pc.setVisibility(LinearLayout.GONE);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
}
}
#Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
My expected outcome is that I want to create the final list for each category entered once with values from each month for that category, Eg. if in month 1 food=400 and in month 2 food=800 then I want my final list added as {1200,food}
I'm at my wits end here, and my brain has stopped working, I'd really appreciate any help, thanks.

How to sum multiple values from firebase

I'm new at android programming as well as firebase. first of all look at the picture
Details image
In there I want to get all the "cost" part in total(sum). I've created the reference like that
DatabaseReference databaseBazars=firebaseDatabase.getInstance().getReference("BazarList");
now what procedure I can follow to get sum and show it in list view or in a toast message).
I've done this to get all the data from that(BazarList) node . and it perfectly showing on the listview.
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
now, how can I get the sum part of the cost. anyone, please help me
here is the Bazar Class
public class Bazar {
String bid;
String date;
String cost;
String name;
String item;
public Bazar(){
}
public Bazar(String bid, String date, String cost, String name,String item) {
this.bid = bid;
this.date = date;
this.cost = cost;
this.name = name;
this.item= item;
}
public String getBid() {
return bid;
}
public String getDate() {
return date;
}
public String getCost() {
return cost;
}
public String getName() {
return name;
}
public String getItem() {
return item;
}
}
To solve this, please use the following code:
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
Integer total = 0;
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
Integer cost = Integer.valueOf(bazar.getCost());
total = total + cost;
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
Log.d("TAG", total + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
The output will be: 59512.
when you have bazarList with items from firebase then simply iterate over list and do sum
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
double sum=getSum(); // at this moment your list have results so call getSum to get SUM
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
below is code which will do the trick
private double getSum()
{
double sum;
for( int i = 0; i < bazarList.size(); i++)
{
sum += bazarList.get(i).getCost; // Assuming Bazar class has getCost Method
}
return sum;
}
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
bazarList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
// Iterate and add all costs to sum
double sum = 0;
for (Bazar b : bazarList) {
sum += Double.parseDouble(b.getCost())
}
BazarList adapter = new BazarList(Bazar_Data_Input.this, bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
mReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (i in snapshot.children) {
val item = i.getValue(CartItem::class.java)
cartList!!.add(item!!)
}
var sum = 0.0
for (itm: CartItem in cartList!!) {
sum += itm.itemPrice.toDouble()
}
total_value.text = sum.toString()
//Initialise my adapter
mRecyclerView.adapter = CartItemsAdapter(applicationContext, cartList!!)
}
}
override fun onCancelled(error: DatabaseError) {
}
})

How to retrieve all child data in Firebase and show in xml layout

I am creating an App with Firebase in which user can add data and show the data directly from Firebase Database. Data is inserted successfully and it looks like this in database after each value inserted.
This is the picture of my database:
I want to retrieve all the data in Student (eg studentName & studentPhoneNumber) and displayed in a .xml layout file. Since i use legacy SDK in my code, i dont know how to use DatabaseReference.
ShowButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Student student = postSnapshot.getValue(Student.class);
String ShowDataString =ShowDataTextView.getText()+ "Name : "+student.getStudentName()+"\nPhone Number : "+student.getStudentPhoneNumber()+"\n\n";
ShowDataTextView.setText(ShowDataString);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Data Access Failed" + firebaseError.getMessage());
}
});
}
});
My Student.class look like this:
public class Student {
private String name;
private String phoneNumber;
public Student() {
}
public String getStudentName() {
return name;
}
public void setStudentName(String name) {
this.name = name;
}
public String getStudentPhoneNumber() {
return phoneNumber;
}
public void setStudentPhoneNumber(String phonenumber) {
this.phoneNumber = phonenumber;
}
}
Take student arrayList and add students data to list.
FirebaseAuth mFirebaseAuthInstance = FirebaseAuth.getInstance();
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
FirebaseUser mFirebaseCurrentUser = mFirebaseAuthInstance.getCurrentUser();
DatabaseReference mDatabaseRef = mFirebaseDatabase.getReference("User").child(mFirebaseCurrentUser.getUid()).child("Student");
mDatabaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
ArrayList<Student> studentList=new ArrayList<Student>();
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Student student = postSnapshot.getValue(Student.class);
studentList.add(student);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Data Access Failed" + firebaseError.getMessage());
}
});
Use RecylerView to load data to xml,refer the below link to use RecylerView
More reference
Try this
public class FethingDatas extends AppCompatActivity {
RecyclerView ry_fetchdata;
Firebase firebase;
ArrayList<Pojo_Recylerview> arrayList = new ArrayList<>();
Pojo_Recylerview pojo_recylerview_obj;
Display_Adapter display_adapter;
private RecyclerView.LayoutManager layoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fething_datas);
ry_fetchdata = findViewById(R.id.ry_fetchdata);
firebase = new Firebase("https://fir-project-87eac.firebaseio.com/").child("Userdata");
layoutManager = new LinearLayoutManager(this);
ry_fetchdata.setLayoutManager(layoutManager);
ry_fetchdata.setItemAnimator(new DefaultItemAnimator());
display_adapter = new Display_Adapter(this,arrayList);
ry_fetchdata.setAdapter(display_adapter);
firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists())
{
arrayList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren())
{
String subject= (String) dataSnapshot1.child("subject").getValue();
String username = (String) dataSnapshot1.child("username").getValue();
pojo_recylerview_obj = new Pojo_Recylerview();
Log.d("subject","username"+subject +" "+username);
pojo_recylerview_obj.setSubject(subject);
pojo_recylerview_obj.setUsername(username);
arrayList.add(pojo_recylerview_obj);
}
display_adapter.notifyDataSetChanged();
}else
{
Toast.makeText(FethingDatas.this,"No More Data Found",Toast.LENGTH_LONG).show();
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
}

How to extract a list of objects from Firebase DataSnapshot on android

I want to convert all Firebase DataSnapshot children to a list in android.
Something like this:
mFirebaseRef = new Firebase(FIREBASE_URL);
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> td = (ArrayList<String>) dataSnapshot.getValue();
//notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
I hope below code works
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
<YourClass> post = postSnapshot.getValue(<YourClass>.class);
Log.e("Get Data", post.<YourMethod>());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
Firebase stores a sequence of values in this format:
"-K-Y_Rhyxy9kfzIWw7Jq": "Value 1"
"-K-Y_RqDV_zbNLPJYnOA": "Value 2"
"-K-Y_SBoKvx6gAabUPDK": "Value 3"
If that is how you have them, you are getting the wrong type. The above structure is represented as a Map, not as a List:
mFirebaseRef = new Firebase(FIREBASE_URL);
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
List<Object> values = td.values();
//notifyDataSetChanged();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
DatabaseReference databaseReference = mFirebaseDatabase.getReference(FIREBASE_URL);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
Log.v(TAG,""+ childDataSnapshot.getKey()); //displays the key for the node
Log.v(TAG,""+ childDataSnapshot.child(--ENTER THE KEY NAME eg. firstname or email etc.--).getValue()); //gives the value for given keyname
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope it helps!
as Frank said Firebase stores sequence of values in the format of "key": "Value"
which is a Map structure
to get List from this sequence you have to
initialize GenericTypeIndicator with HashMap of String and your Object.
get value of DataSnapShot as GenericTypeIndicator into Map.
initialize ArrayList with HashMap values.
GenericTypeIndicator<HashMap<String, Object>> objectsGTypeInd = new GenericTypeIndicator<HashMap<String, Object>>() {};
Map<String, Object> objectHashMap = dataSnapShot.getValue(objectsGTypeInd);
ArrayList<Object> objectArrayList = new ArrayList<Object>(objectHashMap.values());
Works fine for me, Hope it helps.
I did something like this :
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Map<String, Object> objectMap = (HashMap<String, Object>)
dataSnapshot.getValue();
List<Match> = new ArrayList<Match>();
for (Object obj : objectMap.values()) {
if (obj instanceof Map) {
Map<String, Object> mapObj = (Map<String, Object>) obj;
Match match = new Match();
match.setSport((String) mapObj.get(Constants.SPORT));
match.setPlayingWith((String) mapObj.get(Constants.PLAYER));
list.add(match);
}
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
In my case only given solution worked fine.
Screenshot of Firebase ArrayList structure:
How to fetch whole list from Firebase from DataSnapshot.
GenericTypeIndicator<Map<String, List<Education>>> genericTypeIndicator = new GenericTypeIndicator<Map<String, List<Education>>>() {};
Map<String, List<Education>> hashMap = dataSnapshot.getValue(genericTypeIndicator);
for (Map.Entry<String,List<Education>> entry : hashMap.entrySet()) {
List<Education> educations = entry.getValue();
for (Education education: educations){
Log.i(TAG, education.Degree);
}
}
Education.java: (Model class).
public class Education implements Serializable{
public String Degree;
public String Result;
}
Hope this would works fine.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
User user = postSnapshot.getValue(User.class);
list.add(user);
}
for (int i=0;i<list.size();i++)
{
Log.e("Name",list.get(i).getname());
Log.e("Phone",list.get(i).getphone());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("error",firebaseError.getMessage());
}
});
Class model
class User{
String name;
String phone;
public String getname() {
return name;
}
public void setname(String name) {
this.name = name;
}
public String getphone() {
return phone;
}
public void setphone(String phone) {
this.phone = phone;
}
}
List binding
List<User> list= new ArrayList <>();
this work for you
If you use Kotlin, the next one is a good solution:
myRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
val list = dataSnapshot.children.map { it.getValue(YourClass::class.java)!! }
Log.d("TAG", "Value is: $list")
}
Saving and Retriving data to - from Firebase ( deprecated ver 2.4.2 )
Firebase fb_parent = new Firebase("YOUR-FIREBASE-URL/");
Firebase fb_to_read = fb_parent.child("students/names");
Firebase fb_put_child = fb_to_read.push(); // REMEMBER THIS FOR PUSH METHOD
//INSERT DATA TO STUDENT - NAMES I Use Push Method
fb_put_child.setValue("Zacharia"); //OR fb_put_child.setValue(YOUR MODEL)
fb_put_child.setValue("Joseph"); //OR fb_put_child.setValue(YOUR MODEL)
fb_put_child.setValue("bla blaaa"); //OR fb_put_child.setValue(YOUR MODEL)
//GET DATA FROM FIREBASE INTO ARRAYLIST
fb_to_read.addValuesEventListener....{
public void onDataChange(DataSnapshot result){
List<String> lst = new ArrayList<String>(); // Result will be holded Here
for(DataSnapshot dsp : result.getChildren()){
lst.add(String.valueOf(dsp.getKey())); //add result into array list
}
//NOW YOU HAVE ARRAYLIST WHICH HOLD RESULTS
for(String data:lst){
Toast.make(context,data,Toast.LONG_LENGTH).show;
}
}
}
mDatabase.child("token").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot:dataSnapshot.getChildren())
{
String key= snapshot.getKey();
String value=snapshot.getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(ListUser.this,databaseError.toString(),Toast.LENGTH_SHORT).show();
}
});
Only work If child have no SubChild
Works Like a Charm
final DatabaseReference senderDb = FirebaseDatabase.getInstance().getReference(Constant.NODE_MESSAGE).child(myId + "_" + otherId);
senderDb.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Map<String, Object> td = (HashMap<String,Object>) dataSnapshot.getValue();
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
DatabaseReference objRef = senderDb.child( childDataSnapshot.getKey());
Map<String,Object> taskMap = new HashMap<String,Object>();
taskMap.put("is_read", "1");
objRef.updateChildren(taskMap); //should I use setValue()...?
Log.v("Testing",""+ childDataSnapshot.getKey()); //displays the key for the node
}
//notifyDataSetChanged();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You Need to write a custom Deserializer and then loop it and get the values of the hasmap.
Custom Deserializer:-
public class UserDetailsDeserializer implements JsonDeserializer<AllUserDetailsKeyModel> {
/*
bebebejunskjd:{
"email": "akhilbv1#gmail.com",
"mobileNum": "12345678",
"password": "1234567",
"username": "akhil"}*/
#Override public AllUserDetailsKeyModel deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
Gson gson = new Gson();
Type AllUserDetailsResponseModel =
new TypeToken<HashMap<String, AllUserDetailsResponseModel>>(){}.getType();
HashMap<String, AllUserDetailsResponseModel> user =
gson.fromJson(jsonObject, AllUserDetailsResponseModel);
AllUserDetailsKeyModel result = new AllUserDetailsKeyModel();
result.setResult(user);
return result;
}
}
The code in comments is my object model and u should replaceAllUserDetailsKeyModel with your model class and add this to the rest client like below:-
private Converter.Factory createGsonConverter() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(AllUserDetailsKeyModel.class, new UserDetailsDeserializer());
Gson gson = gsonBuilder.create();
return GsonConverterFactory.create(gson);
}
This the custom Convertor for Retrofit.
In your onResponse you just loop with hasmaps and get value by key and my model class looks like below:-
public class AllUserDetailsKeyModel {
private Map<String, AllUserDetailsResponseModel> result;
public Map<String, AllUserDetailsResponseModel> getResult() {
return result;
}
public void setResult(Map<String, AllUserDetailsResponseModel> result) {
this.result = result;
}
}
probably you need to give a Type T where T is your data Type and my model consists only of a hashmap and getters and setters for that.
And finally set Custom Convertor to retrofit like below:- .addConverterFactory(createGsonConverter())
Let me know if you need more clarifications.
Use GenericTypeIndicator to get List of Child Node from Firebase ArrayList structured DataBase
//Start of Code
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot snapshot){
GenericTypeIndicator<List<YourClassName>> t = new GenericTypeIndicator<List<YourClassName>>{};
List<YourClassName> messages = snapshot.getValue(t);
Log.d("Get Data Size", messages.size());
}
}
#Override
public void onCancelled(FirebaseError firebaseError){
Log.e("The read failed: ",firebaseError.getMessage());
}
});
your problem is why your code doesn't work.
this your code:
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.e("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
<YourClass> post = postSnapshot.getValue(<YourClass>.class);
Log.e("Get Data", post.<YourMethod>());
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
})
you miss the simplest thing: getChildren()
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference reference = FirebaseAuth.getInstance().getReference("Donald Trump");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int count = (int) dataSnapshot.getChildrenCount(); // retrieve number of childrens under Donald Trump
String[] hairColors = new String[count];
index = 0;
for (DataSnapshot datas : dataSnapshot.getChildren()){
hairColors[index] = datas.getValue(String.class);
}
index ++
for (int i = 0; i < count; i++)
Toast(MainActivity.this, "hairColors : " + hairColors[i], toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
ArrayList<String> keyList = new ArrayList<String>();
mKeyRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childDataSnapshot : dataSnapshot.getChildren()) {
String temp = childDataSnapshot.getKey();
keyList.add(temp);
i = keyList.size();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
This code is working fine to add all firebase key into arraylist, you can do it with firebase values, of other static values.
DatabaseReference mRootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference mMainMenuRef = mRootRef.child("tut_master");//main
DatabaseReference mSubMenuRef = mMainMenuRef.child("english");//sub
List<Tutorial> tutorialNames=new ArrayList<>();
mSubMenuRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long id = ds.child("id").getValue(Long.class);
String name = ds.child("name").getValue(String.class);
Tutorial tut = new Tutorial();
tut.setTutId(id+"");
tut.setTutName(name);
tutList.add(tut);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
private FirebaseDatabase firebaseDatabase= FirebaseDatabase.getInstance();
private DatabaseReference databaseReference= firebaseDatabase.getReference();
private DatabaseReference mChildReference= databaseReference.child("data");
mChildReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
User commandObject = ds.getValue(User.class);
Log.d("TAG", commandObject.getMsg());
}
Toast.makeText(MainActivity.this,dataSnapshot.toString(),Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
This will help you, you just have to create a model class containing String msg.
Use Gson is my favorite solution.
mFirebaseRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Type StringListType = new TypeToken<List<String>>(){}.getType();
List<String> td = new Gson().fromJson(dataSnapshot.getValue(), StringListType);
}
});
if you think the code to get TypeToken is unintuitive. You can write a class to contain all types you need. So next time, you can get those types quickly.
class TypeTokens{
static public final Type StringListType = new TypeToken<List<String>>(){}.getType();
static public final Type StringMapType = new TypeToken<Map<String, String>>(){}.getType();
static public final Type LongMapType = new TypeToken<Map<String, Long>>(){}.getType();
static public final Type DateMapType = new TypeToken<Map<String, Date>>(){}.getType();
}
Here goes my 2 cents contribution (in Kotlin):
private fun getData(childUid:String) {
refDB = firebaseDB.reference.child(MAIN_DATABASE_FOLDER).child(childUid)
if(childEventDataListener == null) {
childEventDataListener = object : ChildEventListener {
override fun onChildAdded(snapshot: DataSnapshot, previousChildName: String?) {
for(snap in snapshot.children) {
val newParcel = snapshot.getValue(YourClassConverter::class.java)!!
}
}
override fun onChildChanged(snapshot: DataSnapshot, previousChildName: String?) { }
override fun onChildRemoved(snapshot: DataSnapshot) { }
override fun onChildMoved(snapshot: DataSnapshot, previousChildName: String?) {}
override fun onCancelled(error: DatabaseError) {}
}
refDB.addChildEventListener(childEventDataListener!!)
}
}
The class YourClassConverter shall follow this rule as noted in the getValue header's comment shown below. I prefer to use this converter since I can control the default values passed when some of them are not defined in the firebase.
This method is used to marshall the data contained in this snapshot into a class of your choosing. The class must fit 2 simple constraints:
The class must have a default constructor that takes no arguments
The class must define public getters for the properties to be assigned. Properties without a public getter will be set to their default value when an instance is deserialized
An example class might look like:
class Message {
private String author;
private String text;
private Message() {}
public Message(String author, String text) {
this.author = author;
this.text = text;
}
public String getAuthor() {
return author;
}
public String getText() {
return text;
}
}
// Later
Message m = snapshot.getValue(Message.class);

Categories

Resources