I am new to firebase and nosql database
I am trying to retrieve some specific data from a Firebase. I have a node Drugs and Assaults and that node has many unique identifier as node which has so more data into it. I want to retrieve lat/lng from each node.
Please have a look at this.Firebase database image
To get the lat/lng, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference assaultRef = rootRef.child("Assault");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String latlng = ds.child("liststring").child("2").getValue(String.class);
Log.d("TAG", latlng);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
assaultRef.addListenerForSingleValueEvent(eventListener);
You output will be:
lat/lng: (20.330198..., 77.809580...)
lat/lng: (30.786742..., 62.664079...)
Related
My Database Structure:
Hi,I'm currently working on Android Studio project. How do I retrieve a list of data in firebase with random generate key? For example, I need to retrieve the institute name, address and phone. I'm having the random generated id, how do I reference it? Thanks.
To retrieve the name, address and phone try the following:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String name = ds.child("instituteName").getValue(String.class);
String phone = ds.child("institutePhone").getValue(String.class);
String address = ds.child("instituteAddress").getValue(String.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
});
First add a reference to the root node then add a for loop to iterate inside the random if and retrieve the data.
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.
Is it possible to fetch a child from an object without the entire parent in Firebase
For example, a customer registry, where I need all the "name" fields, but I do not have the user "uid". ...
Alex's answer will work (with my comment for good measure).
But you should realize that this downloads all data of all users. There is no way in the Firebase Database to download just one property of each node. So if you want an efficient way to download just the list of names, you should keep precisely that in the database: a list of names.
usernames
uid1: "Fernando"
uid2: "Alex"
That way you can read just the list of names with:
DatabaseReference usernamesRef = FirebaseDatabase.getInstance().getReference().child("usernames");
usernamesRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String uid = childSnapshot.getKey();
String name = childSnapshot.getValue(String.class);
}
Yes it's possible. Please use this code:
DatabaseReference yourRef = FirebaseDatabase.getInstance().getReference().child("usuarios");
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String uId = (String) ds.getKey();
String nome = ds.getChild("nome").getValue(String.class);
list.add(nome);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
You first iterate to get those uid's and after that use them in the DatabaseReference.
Hope it helps.
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);
}