I have a firebase database that has a name and number in it for each of my stores. I want a spinner to show the names of each store so we can select one. the store name example is "0023 franklin", and i want to order them by the number.
my code to make the spinner is
mydb.orderByValue().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Is better to use a List, because you don't know the size
// of the iterator returned by dataSnapshot.getChildren() to
// initialize the array
final List<String> areas = new ArrayList<String>();
for (DataSnapshot areaSnapshot: dataSnapshot.getChildren()) {
Store storeName = areaSnapshot.getValue(Store.class);
areas.add(storeName.getStoreName());
}
Spinner areaSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> areasAdapter = new ArrayAdapter<String>(checkout.this, android.R.layout.simple_spinner_item, areas);
areasAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
areaSpinner.setAdapter(areasAdapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
it shows all the stores but doesn't order them by the number. and the stores are not added in the database in order.
how to i make this happen?
adding JSON
storelist:
-KvIoZC0AbpD1-SJJrIS
faxNum: 987654321
storeName: 0024 Franklin
-KvIobgHLouocLpMkN6k
faxNum: 1234567890
storeName: 0003 Randle
You can use any of the following methods to sort the data:
orderByChild()
orderByValue()
orderByKey()
You can store that number with a key like 'storeNumber' and use the available method like:
orderByChild("storeNumber");
for more usage refer to :
https://firebase.google.com/docs/database/android/lists-of-data?authuser=0#sort_data
Related
Im getting an object from firebase, and there are two ways how i can get object
this one
text1
15.10.2021
text3
12.10.2021
text2
29.11.2021
text4
1.1.2022
or this one
{text = text1 , date = 15.10.2021}
{text = text3 , date = 12.10.2021}
{text = text2 , date = 29.11.2021}
{text = text4 , date = 1.1.2022}
I am need to sort this object by dates like that
text3 12.10.2021
text1 15.10.2021
text2 29.11.2021
text4 1.1.2022
I'm trying to add all into list but I don't know how to sort them.
in list it looks like this
[text1, 15.10.2021, text3, 12.10.2021, text2, 29.11.2021, text4, 1.1.2022]
Im doing that for RecyclerView, and initially im getting dates and strings from Firebase like that
List<String> reminder = new ArrayList<>();
List<String> date = new ArrayList<>();
dbf.child("Reminders").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
reminder.clear();
date.clear();
for(DataSnapshot child2 : snapshot.getChildren()) { // getting a data from DB to ArrayList for dropping into Adapter
for(DataSnapshot tChild : child2.getChildren()) {
if (tChild.getKey().equals("text")) {
reminder.add(tChild.getValue().toString());
rem = reminder.toArray(new String[reminder.size()]); // rem = String[]
}
if (tChild.getKey().equals("date")) {
date.add(tChild.getValue().toString());
dat = date.toArray(new String[date.size()]); // dat = String[]
}
}
mainRowAdapter rAdapter = new mainRowAdapter(MainActivity.this, rem,dat);
rv.setAdapter(rAdapter);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
and then in Adapter class im use method setText()
so, the question in the top
Your dates are stored as strings in a format that is unfortunately not chronologically sortable. If you want to sort on dates, I recommend storing them in ISO-8601 format, such as "2021-10-15" so that their lexicographical order matches their chronological order.
Once you have that format, you can retrieve the nodes from the database in the correct order with:
DatabaseReference reminders = dbf.child("Reminders");
Query remindersByDate = reminders.orderByChild("date");
remindersByDate.addValueEventListener(...
Also see:
Firebase sort by points depending on date
Firebase endAt() not working with date string?
Querying by range in firebase
I have 5 elements in RecyclerView(elements taken from DB) with dates and texts. Two different lists. For dates and for strings. One fragment contains 1 date and 1 string text. So, im need to sort elements by date, like that
Result which i want
text1 10.09.2021
text2 13.09.2021
text3 30.09.2021
text4 1.12.2021
Result which i have
text3 30.09.2021
text4 1.12.2021
text1 10.09.2021
text2 13.09.2021
texts and dates is a two different Lists
The question is, how i can sort dates as strings(may be?) with no text loss, and where im supposed to do that (after getting from db and before retrieve data in adapter? or after loading elements in adapter and then getting them back for sort (looks bad)
thats how im get data from DB and retrieve in adapter
List<String> reminder = new ArrayList<>();
List<String> date = new ArrayList<>();
Calendar test = Calendar.getInstance();
long pars = test.getTimeInMillis();
System.out.println(pars);
dbf.child("Reminders").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
reminder.clear();
date.clear();
for(DataSnapshot child2 : snapshot.getChildren()) { // getting a data from DB to ArrayList for dropping into Adapter
for(DataSnapshot tChild : child2.getChildren()) {
if (tChild.getKey().equals("text")) {
reminder.add(tChild.getValue().toString());
rem = reminder.toArray(new String[reminder.size()]);
}
if (tChild.getKey().equals("date")) {
date.add(tChild.getValue().toString());
dat = date.toArray(new String[date.size()]);
}
}
mainRowAdapter rAdapter = new mainRowAdapter(MainActivity.this, rem,dat);
rv.setAdapter(rAdapter);
rv.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
setText in AdapterClass
holder.reminder.setText(reminder[position]);
holder.date.setText(date[position]);
in another topic i saw this one, but this cannot help me in my situation? may be some analogies exist?
Collections.sort(categories, new Comparator<Categories>() {
#Override
public int compare(Categories lhs, Categories rhs) {
return lhs.title.compareTo(rhs.title);
}
});
the best place to sort your data is when you get your data from db by a query, but if you want to do it manually on your list the best format for saving your date is like this:
2021.09.10
2021.09.13
2021.09.30
2021.12.01
because string sort can apply to your date.
To sort the dates in descending order, you can simply use:
collections.reverseorder();
Hi I am trying to populate recycler view by getting data from two different nodes in firebase. However I am getting two separate listings... one of each node. I want to combine them and show as a single item. My original question is posted here if more files are required to be seen : Populating Recycler View From Nested Queries in Firebase
My Fragment is as follows
// Firebase
fbDatabaseRootNode = FirebaseDatabase.getInstance().getReference();
fbDatabaseRefGroupList = fbDatabaseRootNode.child("groups_list").child(current_user_id);
fbDatabaseRefGroups = fbDatabaseRootNode.child("groups");
fbDatabaseRefGroupList.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Array to Get Group List
lGroupsList = new ArrayList<>();
if (dataSnapshot.exists()) {
// Clear Array to Get Group List
lGroupsList.clear();
for (DataSnapshot glSnapshot : dataSnapshot.getChildren()) {
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = glSnapshot.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsList.add(g);
// Get The Group ID To Get Data From Other Nodes
String groupID = String.valueOf(glSnapshot.getKey());
fbDatabaseRefGroups.child(groupID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Array to Get Group List
lGroupsList2 = new ArrayList<>();
if (dataSnapshot.exists()) {
// Clear Array to Get Group List
lGroupsList2.clear();
// String groupName = (String) dataSnapshot.child("group_name").getValue();
// String groupTagLine = (String) dataSnapshot.child("group_tagline").getValue();
// String groupMemberCount = (String) dataSnapshot.child("group_member_count").getValue();
// Use The Model To Format Array List and Pass It Into It
GroupsListModel g = dataSnapshot.getValue(GroupsListModel.class);
// Array to Get Group List
lGroupsList2.add(g);
// Joining The Arrays To Get One Array
lGroupsList.addAll(lGroupsList2);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
aGroupList = new GroupsListAdapter(getContext(), lGroupsList);
rvGroupList.setAdapter(aGroupList);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
However the problem seems to be that instead of joining the two nodes to show the item as one, I am getting two items in the list (first one containing data from lGroupsList and second one from lGroupsList2). They do not seem be joining.
// Joining The Arrays To Get One Array
lGroupsList.addAll(lGroupsList2);
I have stored ArrayList in firebase DB, is there any way to get specific record from firebase using particular id (memberId) from ArrayList
Currently, I'm able to get the tripMemberList ArrayList but I want to get specific record from ArrayList using memberId
I don't want to retrieve full ArrayList only need a single record from tripMemberList using memberId
I'm attaching a firebase DB structure below
Edit: How i add a record to firebase
TripChatDTO tripChatDTO = new TripChatDTO();
tripChatDTO.setTripId(jsonObject.getInt("travelId"));
tripChatDTO.setTripName(travelDTO.getTitle());
tripChatDTO.setTripPicUrl(jsonObject.getString("image"));
List<TripMemberDTO> memberDTOList = new ArrayList<>();
for (int i = 0; i < invitedFriendArray.length(); i++) {
JSONObject jsonObject1 = invitedFriendArray.getJSONObject(i);
TripMemberDTO dto = new TripMemberDTO();
dto.setMemberId(jsonObject1.getInt("id"));
dto.setAdmin(false);
dto.setNotification(true);
memberDTOList.add(dto);
}
// Add Admin record
TripMemberDTO tripMemberDTO = new TripMemberDTO();
tripMemberDTO.setMemberId(loggedInUser.getId());
tripMemberDTO.setAdmin(true);
tripMemberDTO.setNotification(true);
memberDTOList.add(tripMemberDTO);
// Add all Member record to travel
tripChatDTO.setTripMemberList(memberDTOList);
String channelName = "Trip-" + tripChatDTO.getTripId();
// Create tip
FirebaseDatabase.getInstance().getReference().child(TRIP).child(channelName).setValue(tripChatDTO);
it might be anywhere in the list I want to find a record using `memberId
Then loop over the children of the top element
tripMemberRef rootRef = FirebaseDatabase.getInstance().getReference()
.child("Trips/Trip-190/tripMemberList");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot c : dataSnapshot.getChildren()) {
String memberId = c.child("memberId").getValue(String.class);
Log.d("TAG", memberId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
Assuming that Trips is a direct child of the Firebase root, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("Trips").child("Trip-190").child("tripMemberList").child("0");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String memberId = dataSnapshot.child("memberId").getValue(String.class);
Log.d("TAG", memberId);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
But remember, Firebase is a NoSQL database which is structured as pairs of key and values. This means that every object within a Firebase database is a Map and not an ArrayList.
I am new to android and just learned to create a users profile like facebook or instagram, currently I have registered four users with email/password and in database am storing there email, name, phone. In another activity am trying to fetch only the names of the registered users like "People you may know" in facebook, but it is displaying nothing.
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
UserInformation userInformation = new UserInformation();
userInformation.setName(ds.child("users").child("name").getValue(UserInformation.class).getName());
ArrayList<String> array = new ArrayList<>();
array.add(userInformation.getName());
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array);
mListView.setAdapter(adapter);
}
is this correct way of fetching it because am getting NullPointerException, UserInformation is model class containing getters and setters.
fire-18b42
users
KWE45gijkfJDK6782IBkjas(UID)
email: "#example.com"
name: "Example"
phone_num: 10000000
This is how I have stored the data to database once the user is registered,
now like this I have four users and I want to extract every ones name in seperate listView.
To display those names, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersdRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersdRef.addListenerForSingleValueEvent(eventListener);
And the output will be in this case all your user names.
Firebase is NoSql. You need to retrieve all users from myRef.child("users") and apply iterator to get names of all users.