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
Related
This question already has answers here:
Class java.util.Map has generic type parameters, please use GenericTypeIndicator instead
(5 answers)
Closed 1 year ago.
Trying to retrieve a list of string from Firebase Database but i am keep getting this error "DatabaseException: Class java.util.List has generic type parameters, please use GenericTypeIndicator instead". I also have gone through other answers but none of them helped.
My code:
private void incrementCount(){
reference = FirebaseDatabase.getInstance().getReference("devices").child("deviceIdList");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : snapshot.getChildren()) {
list = ds.getValue(List.class);
Log.d("TAG", "size of deviceId Array" + list.size());
}
if (!list.contains(androidId)){
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("posts").child(postId);
HashMap<String, Object> hashMap = new HashMap<>();
hashMap.put("counter", counter++);
myRef.updateChildren(hashMap);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
json structure of my db. It only have one item for now:
"devices" : {
"deviceIdList" : [ "b5ac388d1c1bf0c3", "j4l322n4ş2nş3n3ğ" ]
},
You cannot convert any object to generic List object. You need to define which type of objects the list accepts.
Firebase provides a GenericTypeIndicator to resolve this.
Usage:
GenericTypeIndicator<List<String>> typeIndicator = new GenericTypeIndicator<List<String>>() {};
And then pass typeIndicator as the type argument in your getValue()
E g.
list = ds.getValue(typeIndicator)
Should solve your problem.
Thanks
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
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.
What should be my query be if I want to get the list of all records which gender = 0 and userType = 1? I'm quite new to firebase and I can't find any sources that teaches compound some queries.
first of all create a node name userList and add instances of user with key 0,1,2,3 and so on like in screen shot in question. It becomes an array of userList
List<User> userList = new ArrayList<>();
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
<User> user = postSnapshot.getValue(<User>.class);
userList .add(user);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
And you can also use Firebase RecyclerAdapter like this
Firebase is no SQL. it doesn't have where clause. You can use orderBy,startAt,endAt function to achieve filtering . See this and this.
Filter most on the server, do the rest on the client
orderBy('gender')
.startAt('0').endAt('0')
and in onDataChange
for (DataSnapshot postSnapshot: snapshot.getChildren())
{
<User> user = postSnapshot.getValue(<User>.class);
if(user.getUserType == 1)
userList .add(user);
}