Reading from a simple FireBase Database - android

I'm having some issues reading from a Firebase Database.
I have a pretty simple layout
{
"lot" : {
"lot1" : "low",
"lot2" : "low",
"lot3" : "low"
}
}
Of course MyAppName { } is above this all.
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();
// Read from the database
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
lotMap = (HashMap) dataSnapshot.getValue();
Log.d("[Directions Activity]: ", "Lot1 value ====== " +lotMap.get("lot"));
Iterator it = lotMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
Log.d("[Directions Activity]: ", "iterator " + pair.getKey() + " = " + pair.getValue());
System.out.println();
it.remove(); // avoids a ConcurrentModificationException
}
}
Here's what returns from log
D/[Directions Activity]:: Lot1 value ====== null //null obviously
//because key lot1 doesn't exist
D/[Directions Activity]:: lot = {lot3=low, lot2=low, lot1=low}
So to me, it looks like it's returning the string {lot3=low, lot2=low, lot1=low}, but I'd like to be able to get an array, with each value if possible.
Is this achievable??

I had the same question and this is what i used. Modifying to fit the question here
private List<String> lotList;
lotList = new ArrayList<>();
DatabaseReference reference= database.getInstance().getReference().child("lot");
Now adding value event listener
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Iterable<DataSnapshot> mData = dataSnapshot.getChildren();
for(DataSnapshot d : mData){
String lot_string = d.getValue(String.class);
lotList.add(lot_string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

There's some tweak in your code. Your
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getInstance().getReference();
should be write like this,
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference database = myRef.child("anyValueNameYouSpecifyInConsole");
Those 2 lines should be declare outside onCreate method. The one that you need to specify with addValueEventListener is the 2nd DatabaseReference, not the first one. So, it should looks like this from my example,
database.addValueEventListener (new ValueEventListener)
and it will import method.
If you wish the data to be displayed in a particular TextView, then just findViewById the TextView you wanna use and include it in onDataChange method like so,
String x = dataSnapshot.getValue(String.class);
textViewNameDeclared.setText(x);
And don't forget to change the security rule for reading.

you can use typecast to JSONObject and parse the JSONObject
JSONObject jsonObject= new JSONObject((Map)dataSnapshot.getValue());
JSONObject jsonObj= (JSONObject) jsonObject.get("lot");
for (Object key : jsonObj.keySet()) {
//based on you key types
String keyStr = (String)key;
Object keyvalue = jsonObj.get(keyStr);
//Print key and value
System.out.println("key: "+ keyStr + " value: " + keyvalue);
}
if you using java 8 than you use lamada expression.

Related

Get Value from Firebase Database

I need to get the string value from the node passcode in my Firebase database to compare with a user input, but unfortunately I am not able to get the value. This is the link to my firebase database in the below image.
This is my codes below:
final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("pin_code");
mDatabase.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
if (rface.equals("") || rface.equals(null)){
// Creating new user node, which returns the unique key value
// new user node would be /users/$userid/
String userId = mDatabase.push().getKey();
// creating user object
Pin pin = new Pin(authUserId, userPassword);
mDatabase.child(userId).setValue(pin);
Intent intent = new Intent(PinActivity.this, ProfileActivity.class);
startActivity(intent);
}
else {
Toast.makeText(PinActivity.this,"Invalid PIN code", Toast.LENGTH_SHORT).show();
return;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This is the json code
{
"pin_code" : {
"id" : "TQYTo1NHNnhPJnOxhe1Vok3U6ic2",
"pincode" : "12345"
}
}
This FirebaseDatabase.getInstance().getReference("pin_code") does not refer to the node you're looking for. Most likely you know the id property, in which case you can get the node with:
DatabaseReference collection = FirebaseDatabase.getInstance().getReference("p...");
Query query = collection.orderByChild("id").equalTo("TQT...ic2");
query.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
for (DataSnapshot child: dataSnapshot.getChildren()) {
String rface = (String) child.child("pincode").getValue();
if (rface.equals(userPassword) && !rface.equals("")){
The changes I made:
On the first line we get the collection: the node under which you want to run a query. You struck out the name of that node in the screenshot, but it's the second line you marked.
In the second line we create a query on the id property of each child node under the collection.
In the onDataChange we added a loop. This is needed because a query against the Firebase Database will potentially have multiple results. So the dataSnapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result. We loop over dataSnapshot.getChildren() to handle those multiple results.
If there can ever only be one node with the same id, you should consider changing your data structure to use the id as the key of the node. So:
pin_codes
uid1: "pincode1"
uid2: "pincode2"
Your code then becomes significantly simpler, because you don't need to query for the user anymore. You can just directly read from the path:
DatabaseReference user = FirebaseDatabase.getInstance().getReference("pin_codes").child("TQT...ic2");
user.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
String rface = (String) dataSnapshot.getValue();
if (rface.equals(userPassword) && !rface.equals("")){
Try change this:
String rface = (String) dataSnapshot.child("pincode").getValue();
To this:
String rface = (String) dataSnapshot.child("pincode").getValue(String.class);
Use the following::
Object some = dataSnapshot.getValue();
String value = some.toString();

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.

Query child value when you don't know parent Key

I am trying to query a child node value but I don't know parent key, I want to query for Firebase Adapter. I want to access userid node under area but I don't know the Id of parent i.e -KqPJMsjSb5CbPcq4nXv
Here is the snapshot of Record:
Please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userIdRef = rootRef.child("areas").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String areaId = ds.child("areaId").getValue(String.class);
Boolean booked = ds.child("booked").getValue(Boolean.class);
Integer bookingHour = ds.child("bookingHour").getValue(Integer.class);
//and so on
Log.d("TAG", areaId + " / " + booked + " / " + bookingHour);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
In which userId is the id of the user that said that is not missing.
When you execute a query against the Firebase Database, there will potentially be multiple results.
So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.

Reading data from firebase database fails

I am reading the data from the firebase database.Following is snapshot of the data stored in database.
In the snap string starting with "8SS..." is the uid of the user. Following is the code for retrieving the data from firebase database.
//To check if uid of current user and database user matches.
Query q = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid()).equalTo(FirebaseAuth.getInstance().getCurrentUser().getUid());
q.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
Log.d(TAG, "Yay!!");
User us = singleSnapshot.getValue(User.class);
String string = "Name: "+ us.getName()+"\nAddress: "+ us.getlat()+ us.getlon()+ "\n\n";
n.setText(string);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
// read query is cancelled.
Log.d(TAG, "loadPost:onCancelled", databaseError.toException());
}
});
User class contains getters and setters.
The error is that only empty Text View appears concluding reading from database fails.
How to evaluate if query is true or false?
What is the error while reading from ValueEventListener()?
I tried using this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Location").child("8SS0uk4FmiPUtXP208Tx8Cqxt2z2");
And then calling on ref.addListenerForSingleValueEvent() but still nothing gets displayed.
I tried using this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid());
This gives dataSnapShot : "DataSnapshot={key='-Kn...', value="latitude:.., longitude:..., Name:..."}. But this is not how I expected it to be.
The database structure should have been Location --> Uid --> Name : "Jane", .. .
This is my code for inserting data in the database.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser() ;
refDatabase = FirebaseDatabase.getInstance().getReference().child("Location").child(user.getUid());
DatabaseReference newPost = refDatabase.push();
//the push() command is already creating unique key
Map<String, String> mapname = new HashMap<String, String>();
mapname.put("Name", n.getText().toString());
mapname.put("latitude", Double.toString(lat));
mapname.put("longitude", Double.toString(longt));
mapname.put("user id", user.getUid());
newPost.setValue(mapname);
I solved this question by introducing multiple for loops.
So, the snapshot of my first child was dataSnapShot : "DataSnapshot={key='-Kn...', value="latitude:.., longitude:..., Name:..."}.
Below is the code to extract all the values and keys :
mRef.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "Children" + dataSnapshot.getKey());
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
String st = singleSnapshot.getKey();
Log.d(TAG, "Yay!!" + singleSnapshot.child(st));
st = "";
int count=0;
for(DataSnapshot singleSnap : singleSnapshot.getChildren()) {
Log.d(TAG, "String" + singleSnap.getValue());
//n.setText(us.getName());
if(count==0) {
st = "Name: " + singleSnap.getValue() + '\n';
}
else if(count==1) {
st = st + "Latitude: " + singleSnap.getValue() + '\n';
}
else if(count==2) {
st = st + "Longitude: " + singleSnap.getValue() + '\n';
}
count++;
}
final TextView rowTextView = new TextView(Menu5.this.getActivity());
rowTextView.setText((CharSequence) st);
ll.addView(rowTextView);
}
}
This gives single key and value pair for every unique id of created by push.So, I had to hard code the concatenation and display as the structure will remain same throughout the app.
Why are you using equal to and then getting the current user. .child(user.getUid()) should already be your current user which gives you the value of the child you are trying to listen to.
I think the uuid's are the children of "8SSOuk.......".
So it should look something like this:
FirebaseDatabase.getInstance().getReference().child("Location").child("8SSOuk.......").child(user.getUid());

How to remove a specific child in Firebase (Android)

Instead of setting the data to null from the child of table Driver.. I want that specific child to be removed.
Here is my sample code.
driverRef = new Firebase(Config.FIREBASE_URL_DRIVER);
Query pendingBus = driverRef.orderByChild("busNum").equalTo(busNum);
pendingBus.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
String busnumber = snapshot.child("busNum").getValue().toString();
String empID = snapshot.child("empId").getValue().toString();
if (busnumber.equals(busNum)) {
snapshot.getRef().child("age").setValue("");
snapshot.getRef().child("busNum").setValue("");
snapshot.getRef().child("driversName").setValue("");
snapshot.getRef().child("empId").setValue("");
snapshot.getRef().child("latitude").setValue("");
snapshot.getRef().child("longitude").setValue("");
snapshot.getRef().child("password").setValue("");
snapshot.getRef().child("username").setValue("");
}
}
and this is the output of that method setValue
Instead of using setValue to null
I use .removeValue
Example: snapshot.getRef().child("age").removeValue();
this is worked for me
databaseReference = databaseReference.child("Users").child(mobile);
databaseReference.setValue(null);

Categories

Resources