firebase equalto multiple values - android

I'm working with firebase, I can get data from firebase with this code
String value1 = "Jack"
DatabaseReference data = FirebaseDatabase.getInstance().getReference().child("users");
Query personsQuery = data.orderByChild("desc").equalTo(value1);
one value works well, how can I get data with array value like this
String value1[] = {"Larry", "Moe", "Curly"};
Edit:
this code lists all names
mPeopleRVAdapter = new FirebaseRecyclerAdapter<Productget, NewsViewHolder>(personsOptions) {
#Override
protected void onBindViewHolder(Product.NewsViewHolder holder, final int position, final Productget model) {
holder.setTitle(model.getTitle());
}
#Override
public Product.NewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.product_row, parent, false);
return new Product.NewsViewHolder(view);
}
};
mPeopleRV.setAdapter(mPeopleRVAdapter);
Can I filter this code for Larry, Moe and Curly?

You can try to get your data with a snapshot and store it into a map like this
Map<String, String> map = (Map<String, String>) dataSnapshot.getValue();
check this answer

Firebase Realtime Database won't be able to do that out of the box, you may need to structure your data differently in other to get desired results, see https://firebase.google.com/docs/database/android/structure-data#best_practices_for_data_structure
For instance you could do composite keys (if you are trying to filter on different childs/fields at once). Also you could try to loop though those different conditions ("Larry", "Moe", "Curly"), download the entire parent node and filter your self; depends on what you are trying to achieve.
If you are ok to Fetch all data (all users), then you could filter by name using a HashMap for example:
First Create and populate the HashMap:
HashMap<Stirng, User> hashmap = new HashMap<>();
ValueEventListener userListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
hashmap.put(user.getName(), user);
}
};
mPostReference.addValueEventListener(userListener);
Then on your adapter you could filter on your data:
//String value1[] = {"Larry", "Moe", "Curly"};
ArrayList<User> fullNameList = new ArrayList<>(); //filtered users array list
for (int i = 0; i<value1.length; i++){
if(hashmap.containsKey(value1[i])){
fullNameList.add(hashmap.get(value1[i]));
}
}
Firestore on the other hand does support more complex queries:
https://firebase.google.com/docs/firestore/query-data/queries#compound_queries

Related

Query is not working properly in firebase database?

I have database of "date" "part" "heat" "defect" these all are child of defect
I tried to filter with date. It's working for 19/4/2021 fine. But not working for any other date. For any other that are present in database it showing result of first two data.
Please refer to these screenshots:
Full database
For 19/4/2021 filter
For any other date
com.google.firebase.database.Query query = defect.orderByChild("date").equalTo(query);
ValueEventListener valuelistener2 = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot _dataSnapshot) {
map_list = new ArrayList<>();
try {
GenericTypeIndicator <HashMap<String, Object>> _ind = new GenericTypeIndicator<HashMap< String, Object>>() {};
for (DataSnapshot _data : _dataSnapshot.getChildren()) {
HashMap <String, Object> _map= _data.getValue(_ind);
map_list.add(_map);
}
I also have attached source code photo heresource
Source 1

I am trying to fetch multiple values query from Firestore am i doing it right?

I used hashmap to get the data from Filter data fragment that the user wants
to display, and I want to build a dynamic Firestore fetch query, but I'm
not sure if this is the right way to do it.
I'm new to firestore query but I’ve tried to setup build a dynamic query by store the variables into the query using foreach, in the code explain I transform this code
Query filterQuery= db.collection("Property").
.whereEqualTo("noBathrooms", "5")
.whereEqualTo("noRooms", "2");
to this.
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
filterQuery=propertyRef.whereEqualTo(key,value);
}
here where I setup the query
public void filterData(){
Query filterQuery =null;
for(Map.Entry<String, Object> entry : list.entrySet()) {
String key = entry.getKey();
String value = entry.getValue().toString();
Log.i(key,value);
filterQuery=propertyRef.whereEqualTo(key,value);
}
dataFetch(filterQuery,R.id.rentRV);
}
and here where i am bulidng it
private void dataFetch(Query query,int rvView){
FirestoreRecyclerOptions<Property> options = new
FirestoreRecyclerOptions.Builder<Property>()
.setQuery(query, Property.class)
.build();
mAdapter = new DiscoverAdapter(options);
RecyclerView recyclerView = root.findViewById(rvView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new
LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false));
recyclerView.setAdapter(mAdapter);
mAdapter.startListening();
mAdapter.setOnItemClickListener((documentSnapshot, position) -> {
Property property = documentSnapshot.toObject(Property.class);
String id = documentSnapshot.getId();
Bundle mBundle = new Bundle();
mBundle.putString("id", id);
Toast.makeText(getContext(), id, Toast.LENGTH_SHORT).show();
});
}

Sorting and querying documents in couchbase-lite android

What I want to do is finding all records that match some id and sorted by a name. The data looks something like:
{
type:"receiving",
saleName:"Harshitha",
penId:"7aac88118420858d62f5ea55e22"
}
{
type:"receiving",
saleName:"Tom",
penId:"81fb1a79526f4e2bdc77aa7d73d"
}
{
type:"receiving",
saleName:"James",
penId:"81fb1a79526f4e2bdc77aa7d73d"
}
I want to get documents with some specific penID sorted by saleName.
Ex:- I want to get documents with this penId ‘81fb1a79526f4e2bdc77aa7d73d’ and sort them by saleName. Like this order:-
{
type:"receiving",
saleName:"James",
penId:"81fb1a79526f4e2bdc77aa7d73d"
}
{
type:"receiving",
saleName:"Tom",
penId:"81fb1a79526f4e2bdc77aa7d73d"
}
My view like this,
View view = database.getView("receiving_view");
if (view.getMap() == null) {
view.setMap(new Mapper() {
#Override
public void map(Map<String, Object> document, Emitter emitter) {
if (document.get("type").equals("receiving") ) {
List<Object> keys = new ArrayList<Object>();
keys.add(document.get("penId"));
keys.add(document.get("saleName"));
emitter.emit(keys, document);
}
}
}, "1.1");
}
return view;
Then I tried to get data like this,
View view = getView("receiving_view");
Query query = view.createQuery();
List<Object> keys = new ArrayList<Object>();
keys.add("81fb1a79526f4e2bdc77aa7d73d");
List<Object> allKeys = new ArrayList<Object>();
allKeys.add(keys);
query.setKeys(allKeys);
query.run();
It’s not working because I passed one key, but their are two keys in the view… But I can’t pass the ‘saleName’ as a key because I want only to sort by ‘saleName’. What is the best way to do this?
Finally I found the solution. I don’t want to use setKeys here, I should use range of keys, not a specific set of keys.
I set startKey to [penID] and endKey to [penID, {}]. The empty map sorts after any other value, so this key range includes all keys that start with penID. I change my data getting method. Now this is what it is looks like,
View view = getView("receiving_view");
Query query = view.createQuery();
query.setStartKey(Arrays.asList("81fb1a79526f4e2bdc77aa7d73d"));
query.setEndKey(Arrays.asList("81fb1a79526f4e2bdc77aa7d73d", new HashMap<String, Object>()));
query.run();

How to get specific record from ArrayList stored in fireabase

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.

Sorting Database list android by likes

I am building recipes app. I have page in my app that retrieves all the recipes from the database on Firebase into ListView. Each Recipe has these variables:
public String key;
public String uid;
public String title;
public String type;
public String ingredients;
public String instructions;
public int likes;
Here's the function that retrieves all the data :
//Retrieve Data from database
public void retriveData() {
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recipes = new ArrayList<Recipe>();
for(DataSnapshot data : dataSnapshot.getChildren()) {
Recipe r = data.getValue(Recipe.class);
recipes.add(r);
}
allRecipeAdapter = new AllRecipeAdapter(AllRecipeActivity.this,0,0,recipes);
lv.setAdapter(allRecipeAdapter);
}
}
}
Now i want to create another screen that also has a ListView and i would like to sort the Recipes by nubmer of likes and then enter the top 10 recipes into the ListView.
I searched on Google i found the function OrderByValue but i can't figure out how to use it i realized how to works but i can't implement this to my project.
Gaëtan Maisse and KLHauser gave you solutions that work in pure client-side code. Here's an alternative that uses Firebase Database queries, which means the ordering and filtering happen on the server:
// assuming that database refers to the list of all recipe
Query topRecipes = database.orderByChild("likes").limitToLast(10);
topRecipes.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
recipes = new ArrayList<Recipe>();
for(DataSnapshot data : dataSnapshot.getChildren()) {
Recipe r = data.getValue(Recipe.class);
// add the recipe to the front of the list
recipes.add(0, r);
}
allRecipeAdapter = new AllRecipeAdapter(AllRecipeActivity.this,0,0,recipes);
lv.setAdapter(allRecipeAdapter);
}
}
Since Firebase queries always sort items in ascending order, the query takes the last 10 items - those are the ones with the highest like count. To reverse those items, the code inserts each item to the from of the list, instead of appending them to the end.
You can sort your list using a Comparator and then get a sublist of 10 first elements before displaying it in the ListView:
Comparator<Recipe> likesOrderComparator = new Comparator<Recipe>() {
public int compare(Recipe recipe1, Recipe recipe2) {
return recipe1.likes < recipe2.likes ? -1 : recipe1.likes == recipe2.likes ? 0 : 1;
}
};
Collections.sort(recipes, likesOrderComparator);
List<Recipe> topTenRecipes = recipes.subList(0, 9);
// Now display topTenRecipes in a ListView
Java7:
Collections.sort(list, new Comparator<Recipe>() {
#Override
public int compare(Recipe r1, Recipe r2) {
if (r1.getLikes() > r2.getLikes())
return 1;
if (r1.getLikes() < r2.getLikes()
return -1;
return 0;
}
});
Java8 (using lambda):
recipes.stream()
.sorted((r1, r2) -> Integer.compare(r1.getLikes(),
r2.getLikes()))

Categories

Resources