I am inserting data into the firebase real-time database and then getting the data and displaying it on a graph but when i insert into the database now i am using the unique getkey() method to insert the values but i would like to use the getuid() method as the user is already authenticated in the app. I'd like to know how I can change the getkey() to use the getuid().
This is my current code: The getkey() method is in the setListneners() method
FirebaseDatabase database;
DatabaseReference reference;
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/mm/yyyy");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weight);
Btn_Display = findViewById(R.id.btn_display);
graphView = findViewById(R.id.weight_graph);
series = new LineGraphSeries();
graphView.addSeries(series);
database = FirebaseDatabase.getInstance();
reference = database.getReference("WeightGraph");
setListeners();
}
private void setListeners() {
Btn_Display.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = reference.push().getKey();
long x = new Date().getTime();
int y = Integer.parseInt(weight.getText().toString());
PointValue pointValue = new PointValue(x, y);
reference.child(id).setValue(pointValue);
}
});
graphView.getGridLabelRenderer().setNumHorizontalLabels(2);
graphView.getGridLabelRenderer().setNumVerticalLabels(2);
graphView.getGridLabelRenderer().setLabelFormatter(new DefaultLabelFormatter(){
#Override
public String formatLabel(double value, boolean isValueX) {
if(isValueX){
return simpleDateFormat.format(new Date((long) value));
}else{
return super.formatLabel(value, isValueX);
}
}
});
}
#Override
protected void onStart() {
super.onStart();
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dataPoints = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
PointValue pointValue = dataSnapshot.getValue(PointValue.class);
dataPoints[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
series.resetData(dataPoints);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser mAuth = FirebaseAuth.getInstance().getCurrentUser()
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
DataPoint[] dataPoints = new DataPoint[(int) snapshot.getChildrenCount()];
int index = 0;
for(DataSnapshot dataSnapshot : snapshot.getChildren()){
PointValue pointValue = dataSnapshot.getValue(PointValue.class);
dataPoints[index] = new DataPoint(pointValue.getxValue(), pointValue.getyValue());
series.resetData(dataPoints);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
Then you can get Uid
mAuth.getUid()
If you want to write the data under the user's UID instead of the key generated by push(), you'd do something like this:
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
long x = new Date().getTime();
int y = Integer.parseInt(weight.getText().toString());
PointValue pointValue = new PointValue(x, y);
reference.child(id).setValue(pointValue);
If you want to store a list of points for each user, you'd change that last line to:
reference.child(id).push().setValue(pointValue);
So this way you get a list of auto-generated (push) IDs under each UID.
Related
i am trying to fetch all uid from database and put in a loop to compare all uid Reservations with the reservations that i am making. the point is to compare all time and parking with the new one i am booking so there will no be conflict in reservation.
the firebase strcuture:
the code
public class MainActivity5 extends AppCompatActivity {
private Button btnMove;
Button b;
RadioGroup radioGroup;
RadioButton selectedRadioButton;
FirebaseDatabase rootnode, rootnode2;
DatabaseReference reference, reference2;
ReservationClass reservationClass;
String str, TimeGroup;
FirebaseAuth auth;
String currentuser = FirebaseAuth.getInstance().getCurrentUser().getUid();
String allUsers = (String) FirebaseAuth.getInstance().getUid();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main5);
btnMove = findViewById(R.id.ConfirmBooking);
radioGroup = (RadioGroup) findViewById(R.id.ParkingSpace);
TimeGroup = getIntent().getExtras().getString("Selected Time : ");
btnMove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// moveToActivity6();
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
//get RadioButton text
String parkingSpace = selectedRadioButton.getText().toString();
final String time3 = TimeGroup;
final String parking = parkingSpace;
String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
/*Intent i = new Intent(MainActivity5.this, MainActivity6.class);
i.putExtra("Selected Parking space is: ", parkingSpace);
startActivity(i);*/
reference2 = FirebaseDatabase.getInstance().getReference("Reservation").child(id);
reference2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (!snapshot.exists()) {
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time3, parking);
reference.child(currentuser).setValue(reservationClass);
Toast.makeText(MainActivity5.this, "Booking successful", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
/* final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Reservation");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.getValue() != null) {
for (DataSnapshot ds : snapshot.getChildren()) {
String uid = "" + snapshot.getValue();
String allUsers = uid;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});*/
Query query = FirebaseDatabase.getInstance().getReference("Reservation").child(allUsers);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
selectedRadioButton = (RadioButton) findViewById(radioGroup.getCheckedRadioButtonId());
final String parkingSpace = selectedRadioButton.getText().toString();
final String time1 = TimeGroup;
final String parking = parkingSpace;
final String id = FirebaseAuth.getInstance().getCurrentUser().getUid();
for (DataSnapshot snapShot : snapshot.getChildren()) {
//Toast.makeText(MainActivity5.this, time1, Toast.LENGTH_SHORT).show();
String type = snapshot.child("time").getValue().toString();
String type2 = snapshot.child("parking").getValue().toString();
if (type.equals(time1) && type2.equals(parking)) {
Toast.makeText(MainActivity5.this, allUsers, Toast.LENGTH_SHORT).show();
}
if (!type.equals(time1) || !type2.equals(parking)) {
Toast.makeText(MainActivity5.this, type, Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity5.this, type2, Toast.LENGTH_SHORT).show();
rootnode = FirebaseDatabase.getInstance();
reference = rootnode.getReference("Reservation");
ReservationClass reservationClass = new ReservationClass(time1, parking);
reference.child(id).setValue(reservationClass);
Intent intent = new Intent(MainActivity5.this, MainActivity6.class);
startActivity(intent);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
In your current data structure this requires that you load all reservations and check them individually, meaning the performance linearly depends on the number of reservations in the system.
I highly recommend modifying your (or creating a dedicated) data structure for this, which makes what you want a direct lookup.
Reservations: {
"A1_0800-0900am": "Q1zT9iCw...OHI1",
"A4_0800-0900am": "3ReGkVGF...4Cm2",
}
So the keys here are based on the parking spot and time slot, each combination mapping to a idempotent, unique key.
With the above data structure it becomes impossible to add the new reservation for:
"A1_0800-0900am": "TDBZigbk...7Bs1",
As a reservation for that key already exists.
In fact, it is easy to enforce that existing reservations can't be overwritten in security rules with:
".write": "!data.exists()"
I am fetching data and adding it to List from firebase database.
Now i want to sort the list data based on time so that latest data will appear first on the list and then setting the updated list into my RecyclerView.Adapter. I have tried layoutmanager.setReverseLayout(true); and layoutmanager.setStackFromEnd(true); for reversing the RecyclerView but it always shows data from the middle and also I don't want to follow this method.
How can i do that.
public class HistoryActivity extends AppCompatActivity{
private String customerOrDriver, userId;
private String doctorId, patientId, pharmacyId, userDriverOrCustomer;
private Long timestamp;
private String name, service;
private SwipeRefreshLayout swipeRefreshLayout;
private RecyclerView mHistoryRecyclerView;
private RecyclerView.Adapter mHistoryAdapter;
private RecyclerView.LayoutManager mHistoryLayoutManager;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
customerOrDriver = getIntent().getExtras().getString("customerOrDriver");
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(HistoryActivity.this);
userId = sharedPreferences.getString("UID","");
mHistoryRecyclerView = (RecyclerView) findViewById(R.id.historyRecyclerView);
mHistoryAdapter = new HistoryAdapter(getDataSetHistory(), HistoryActivity.this);
mHistoryLayoutManager = new LinearLayoutManager(HistoryActivity.this);
mHistoryRecyclerView.setLayoutManager(mHistoryLayoutManager);
mHistoryRecyclerView.setHasFixedSize(true);
/*// sort the recycler view to descending order
((LinearLayoutManager) mHistoryLayoutManager).setReverseLayout(true);
((LinearLayoutManager) mHistoryLayoutManager).setStackFromEnd(true);*/
mHistoryRecyclerView.setItemAnimator(new DefaultItemAnimator());
mHistoryRecyclerView.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
mHistoryRecyclerView.setAdapter(mHistoryAdapter);
getUserHistoryIds();
}
private void getUserHistoryIds() {
//swipeRefreshLayout.setRefreshing(true);
DatabaseReference userHistoryDatabase = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(customerOrDriver).child(userId).child(Common.history_table);
userHistoryDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot history : dataSnapshot.getChildren()){
FetchRideInformation(history.getKey());
//swipeRefreshLayout.setRefreshing(false);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//swipeRefreshLayout.setRefreshing(false);
}
});
}
private void FetchRideInformation(String rideKey) {
DatabaseReference historyDatabase = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideKey);
historyDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
String rideId = dataSnapshot.getKey();
timestamp = 0L;
for(DataSnapshot child : dataSnapshot.getChildren()){
if (child.getKey().equals("timestamp")){
timestamp = Long.valueOf(child.getValue().toString());
}
}
getRideInformation(rideId, timestamp);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getRideInformation(final String rideId, final Long timestamp) {
DatabaseReference historyRideInfoDb = FirebaseDatabase.getInstance().getReference().child(Common.history_table).child(rideId);
historyRideInfoDb.addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
if (child.getKey().equals("patient")) {
patientId = child.getValue().toString();
if (!patientId.equals(userId)) {
userDriverOrCustomer = "Doctors";
getUserInformation("Patients", patientId, rideId, timestamp);
}
}
else if (child.getKey().equals("patient")) {
patientId = child.getValue().toString();
if (!patientId.equals(userId)) {
userDriverOrCustomer = "Phamacys";
getUserInformation("Patients", patientId, rideId, timestamp);
}
}
if (child.getKey().equals("doctor")) {
doctorId = child.getValue().toString();
if (!doctorId.equals(userId)) {
userDriverOrCustomer = "Patients";
getUserInformation("Doctors", doctorId, rideId, timestamp);
}
}
else if (child.getKey().equals("pharmacy")) {
pharmacyId = child.getValue().toString();
if (!pharmacyId.equals(userId)) {
userDriverOrCustomer = "Patients";
getUserInformation("Pharmacys", pharmacyId, rideId, timestamp);
}
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void getUserInformation(String otherUserDriverOrCustomer, String otherUserId, final String rideId, final Long timestamp) {
DatabaseReference mOtherUserDB = FirebaseDatabase.getInstance().getReference().child(Common.user_table).child(otherUserDriverOrCustomer).child(otherUserId);
mOtherUserDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
if (map.get("name") != null) {
name = (map.get("name").toString());
}
if(map.get("service") == null)
{
service = (map.get("phone").toString());
}
else if (map.get("service") != null) {
service = (map.get("service").toString());
}
HistoryObject obj = new HistoryObject(rideId, name, service, getDate(timestamp));
resultsHistory.add(obj);
mHistoryAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private String getDate(Long time) {
Calendar cal = Calendar.getInstance(Locale.getDefault());
cal.setTimeInMillis(time*1000);
String date = DateFormat.format("MMMM dd yyyy, hh:mm a", cal).toString();
return date;
}
private ArrayList resultsHistory = new ArrayList<HistoryObject>();
private ArrayList<HistoryObject> getDataSetHistory() {
return resultsHistory;
}
}
Simply use myList.sort() then read it the way its needed like ascending or descending amd put it in the RecyclerView
You can sort your by following way
Her i just showed you an Student object but in your case you can check with datetime
Using Lambda expression: The Java 8 equivalent code using Lambda expression would look like this:
studentlist.sort((Student s1, Student s2)->s1.getName().compareTo(s2.getName()));
Hy, I'm writing an application that has to get specific data from firebase using the position of the item in the listView. My problem is that I have no idea how to take it this item on firebase.
For all child of Torneo I have to control all the nameCreator.
I have tried this:
public Boolean RegisterUser(Data data, final int position, final Context c){
boolean registration;
final ArrayList<String> Creator = new ArrayList<>();
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(data.child("nameCreator").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
return registration;
}
Data is a class with some getter and setter that I have created.
position is the position of the element on the list view.
Thanks for answers.
Change the following:
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
into this:
databaseReference.child("Tornei").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(datas.child("nameCreator").getValue().toString());
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Then you will be able to loop and retrieve the value of nameCreator
It's easy.
【Step 1 | Get Snapshot Data and Save in Global Variable】
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference fruitsReference = rootReference.child("fruits");
DataSnapshot fruitsData;
#Override
protected void onStart() {
super.onStart();
fruitsReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshots) {
fruitsData = dataSnapshots;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
【Step 2 | Find Your Target Position through the Loop】
public void onClick(View view) {
int index = 0;
for (DataSnapshot childSnapshot : fruitsData.getChildren()) {
if (index == 1) { //your target position
DatabaseReference currentFruitReference = childSnapshot.getRef();
currentFruitReference.setValue("peach"); //do whatever you want
}
index++;
}
}
I'm trying to retrieve and convert it to strings the UserIDs that are being saved within the driver's passengerRequest like in this picture:
https://imgur.com/a/F6matnZ
here is my getAssignPassenger
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
my problem is here in this block
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
passengerID = dataSnapshot.getValue().toString();
getAssignPassengerPickUpLocation();
in the passengerID it should retrieve every userIDs that are saved in there...
how do I that?
Next problem is... IF I successfully retrieved the userIDs and how do I continue it in finding their location, here is picture of the node:
https://imgur.com/1TQQ4Ih
I already started the codes for it
here is my getAssignPassengerLocation
private void getAssignPassengerPickUpLocation() {
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
if (map.get(0) != null) {
locationLat = Double.parseDouble(map.get(0).toString());
}
if (map.get(1) != null) {
locationLong = Double.parseDouble(map.get(1).toString());
}
LatLng driverLatLng = new LatLng(locationLat, locationLong);
mMap.addMarker(new MarkerOptions().position(driverLatLng).title("Pickup Location").icon(BitmapDescriptorFactory.fromResource(R.mipmap.ic_launcher_pickup_marker)));
what should I do in this block
AssignPassengerPickupLocationref = FirebaseDatabase.getInstance().getReference().child("passengerRequest").child(passengerID).child("l");
AssignPassengerPickupLocationListener = AssignPassengerPickupLocationref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()&&!passengerID.equals("")) {
List<Object> map = (List<Object>) dataSnapshot.getValue();
double locationLat = 0;
double locationLong = 0;
is it possible to store the nodes in an Array String?
For the first one
You have to get snapshot children inside snapshot
private void getAssignedPassenger() {
String driverID = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child("Driver").child(driverID).child("passengerRequest");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
List<String> passengerIdList = new ArrayList()
for (DataSnapshot passenger Snapshot: dataSnapshot.getChildren()) {
String passengerId = passenger.getKey()
passengerIdList.add(passengerId)
}
getAssignPassengerPickUpLocation();
}else{
passengerID = "";
if(pickupMarker !=null){
pickupMarker.remove();
}
if(AssignPassengerPickupLocationListener!= null){
AssignPassengerPickupLocationref.removeEventListener(AssignPassengerPickupLocationListener);
}}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
For the second one
Actually you have to keep location same position as 'destination' instead of query in another children.
But why you need to get all users request location at the same time or inside your activity contain all users request location in one activity?
For more information:
Read and write lists
https://firebase.google.com/docs/database/android/lists-of-data
and
How to structured NoSQL
https://www.youtube.com/watch?v=v_hR4K4auoQ
I have just added few values using Firebase:
Screen from Firebase
I would like to sum up those values and display 15 as a result in the log.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseReference beersRef = FirebaseDatabase.getInstance().getReference("Rank");
final ArrayList<Integer> score = new ArrayList<>();
score.add(9);
score.add(2);
score.add(4);
beersRef.push().setValue(score);
beersRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To achieve this, please use the following code. It's the simples way.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rankRef = rootRef.child("Rank");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum =+ sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rankRef.addListenerForSingleValueEvent(eventListener);
Your output will be: 15
use ValueEventListner and , don't use childEventListner,
follow the below line...Here " UI and UI.class " means...java class name ..where you put getters and setters ...
here I store int value in firebase...so need to convert int value to String and set a text to text viewholder...if u don't store in int ..than u can use String
beersRef.addValueEventListener(new ValueEventListener() {`
#Override
public void onDataChange(DataSnapshot dataSnapshot) {``
int total = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UI result = ds.getValue(UI.class);
total = total + result.getMrp_final();
}
String tl = total + "";
tv_total.setText(tl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
make sure int total value is zero...
thankyou