I am retrieving longitude and latitude values of each user from firebase but problem is that i want to add that values of each user in one list so there are many list that’s why I’m using arraylist of arraylist.
So for first user
longitude = 12345 , latitude = 23456
and for 2nd user
longitude = 45678 , latitude = 67891.
Now my question is i want to add longi and lat of first user in list [ 12345 , 23456 ] and for 2nd user [ 45678 , 67891]
By using arraylist of arraylist is equal to [[
12345,23456 ],[ 45678 , 67891 ] ].
My code:-
Initialization:-
ArrayList<String> longitudes = new ArrayList<>();//for storing latitude and longitude values
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >();
//for storing combine values of longitude and latitude
databaseReference.child("hospital").addValueEventListener(new ValueEventListener() {
@SuppressLint("SetTextI18n")
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
longitudes.clear();
for (DataSnapshot snapshot1: snapshot.getChildren()) {
longitudes.add(snapshot1.child("longitude").getValue().toString());
longitudes.add(snapshot1.child("latitude").getValue().toString());
aList.add(count,longitudes);
count++;
}
count=0;
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
But it is giving output as
[[12345,23456,45678 , 67891],[ 12345,23456,45678 , 67891]] It is repeating the values
But I am expecting for each user like
[[12345,23456],[45678 , 67891]]
2
Answers
The implementation is basically wrong as I can see you are trying to add in the longitudes array for the latitude as well.
Your
longitudes
is always the same list. Create a newArrayList
and assign it tolongitudes
on every loop iteration instead of clearing and reusing the existing one.Remove your existing
longitudes
variable and make your loop look like this:I would further like to suggest not to represent lat+long as a List with 2 elements, just create your own class with 2 fields orif your are on java14+, use a record:
and then use that in your list: