I am making an android app through android studio in java language. I have linked it to firebase Realtime database. There are auto generated push IDs as the last child. I want to retrieve my database values back in an activity. I am facing problem in giving reference to the push IDs.
This is what I have tried.
myRef = myfire.getReference().child("Data").child(strUID).child("Traffic").child("Wedding");
final String uid =myRef.getKey();
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
String stData1 = (Objects.requireNonNull(dataSnapshot.child("stData1").getValue())).toString();
String stData2 = (Objects.requireNonNull(dataSnapshot.child("stData2").getValue())).toString();
String stData3 = (Objects.requireNonNull(dataSnapshot.child("stData3").getValue())).toString();
String stData4 = (Objects.requireNonNull(dataSnapshot.child("stData4").getValue())).toString();
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
Please provide a practical example.
Edit
This is my database structure:------------
Data>>
user id>>>>
Traffic>>>>
Wedding>>>>
Auto ID>>>
>stData1
>stData2
>stData3
>stData4 //I want to get this last value//
my json file
{
"Data" : {
"UyhzVqsz1BVFKoePa2NEmlPFu382" : {
"Traffic" : {
"Wedding" : {
"-MYKeSN8GZ8WbI-8TfVB" : {
"stData1" : "15 Apr 2021,06:43:00:pm",
"stData2" : "Wedding",
"stData3" : "kkk",
"stData4" : "100"
}
}
}
}
}
}
The only ways to get a node is by either knowing its full path, or by knowing the path to the parent node, and then some unique value under the node. Neither seems to be the case for the stData4 in your JSON, so you'll have to load the entire Wedding node and then loop over the results to get the part you want.
This isn't too bad though:
myRef = myfire.getReference("Data").child(strUID).child("Traffic/Wedding");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
Toast.makeText(getApplicationContext(),"Data Not Available",Toast.LENGTH_LONG).show();
} else {
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
String stData1 = childSnapshot.child("stData1").getValue(String.class);
String stData2 = childSnapshot.child("stData2").getValue(String.class);
String stData3 = childSnapshot.child("stData3").getValue(String.class);
String stData4 = childSnapshot.child("stData4").getValue(String.class);
}
category basic = new category(stData1,stData2,stData3,stData4);
tvBalance.setText(stData4);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
The code above assumes that:
strUID has the value UyhzVqsz1BVFKoePa2NEmlPFu382
Related
I am making an app based on firebase Realtime database. I have set rules as given below:
{
// Allow anyone to read data, but only authenticated content owners can
// make changes to their data
"rules": {
"Users": {
"$uid": {
".read": true,
// or ".read": "auth.uid != null" for only authenticated users
".write": "auth.uid == $uid"
}
}
}
}
I am trying to add data by the following code in java. But getting Error.
myfire = FirebaseDatabase.getInstance();
myRef = myfire.getReference("Users").child("Some Authentic User");
//======================
btnAdmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stName = etName.getText().toString();
stRoll = etRoll.getText().toString();
etName.setText("");
etRoll.setText("");
myRef = myfire.getReference();
myRef.child("201").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
model model =new model();
model.setFb01name(stName);
model.setFb04roll(stRoll);
myRef.child("Basic").setValue(model);
Toast.makeText(getApplicationContext (),"Sorry",Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext (),"Error",Toast.LENGTH_SHORT).show();
}
});
}
});
My model class goes like this:
public class model {
String fb01name;
String fb04roll;
public model() {
}
public model(String fb01name, String fb04roll) {
this.fb01name = fb01name;
this.fb04roll = fb04roll;
}
public String getFb01name() {
return fb01name;
}
public void setFb01name(String fb01name) {
this.fb01name = fb01name;
}
public String getFb04roll() {
return fb04roll;
}
public void setFb04roll(String fb04roll) {
this.fb04roll = fb04roll;
}
}
I cannot find the error. The logcat is blank.
I was successful in adding data previously .But after changing the rules it failed.I want the database path like this:
(Main Node)Users--
(first Child)---Authenitic User(As added by "Add User")
(second child)-----some id( like '201')
(Targeted Children) 1 ------fb01name (and its value)
2------fb04roll (and its value)
Can anybody will please guide me practically?
Since onCancelled is called on your listener, that means that you don't have permission to read the data that you're trying to access. If you log the databaseError.toException() that you get in onCancelled you should also see that, as it should tell you that permission was denied.
Distilling your code down, you're attaching a listener to:
myRef = myfire.getReference();
myRef.child("201").addValueEventListener(...
So that is the path /201 in the database, where indeed your rules don't grant anyone read access.
My best guess is that the myRef = myfire.getReference(); line is a mistake, and removing it will lead to reading /Users/Some Authentic User/201, which is probably what you want to do.
Back-end: Springboot
Front-end: ReactJS
CloudRepo: Firebase Realtime Database
I have a Springboot application that GETs data from the Firebase Realtime Database.
This data is then served via a GET request from reactJS.
I get the JSON object in reactJS as :
What I am trying to do is to map the firebase snapshot to a Java Collection. Here is What I have done so far:
DatabaseReference ref = FirebaseService.getFirebaseDatabase().getReference("/devices/device1");
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot: dataSnapshot.getChildren()) {
DeviceData message = messageSnapshot.getValue(DeviceData.class);
System.out.println(message);
}
Map<String, DeviceData> document = (Map<String, DeviceData>) dataSnapshot.getValue();
setUpdatedDocumentData(document);
}
public void onCancelled(DatabaseError error) {
System.out.print("-----Error-----:\n" + error.getMessage());
}
});
My POJO looks like this:
public class DeviceData {
String sensor_1;
String sensor_2;
public DeviceData() {}
public DeviceData(String sensor_1, String sensor_2) {
this.sensor_1 = sensor_1;
this.sensor_2 = sensor_2;
}
public String getSensor_1() {
return sensor_1;
}
public void setSensor_1(String sensor_1) {
this.sensor_1 = sensor_1;
}
public String getSensor_2() {
return sensor_2;
}
public void setSensor_2(String sensor_2) {
this.sensor_2 = sensor_2;
}
#Override
public String toString() {
return "DeviceData{" +
"sensor_1='" + sensor_1 + '\'' +
", sensor_2='" + sensor_2 + '\'' +
'}';
}
}
I am getting null in my sensor_1 and sensor_2 log. How can I map the above firebase structure to a collection?
Under each /devices/$device node, you have two nested levels:
For the date
For the time.
Your code only has once loop over the children of the device node, so your messageSnapshot variable is actually a snapshot with all data for all timestamps for a specific date.
To handle your structure correctly, you need two nested loops:
DatabaseReference ref = FirebaseService.getFirebaseDatabase().getReference("/devices/device1");
ref.addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot timeSnapshot: dataSnapshot.getChildren()) {
DeviceData message = timeSnapshot.getValue(DeviceData.class);
System.out.println(message);
}
}
Map<String, DeviceData> document = (Map<String, DeviceData>) dataSnapshot.getValue();
setUpdatedDocumentData(document);
}
public void onCancelled(DatabaseError error) {
System.out.print("-----Error-----:\n" + error.getMessage());
}
});
If you only care about the latest timestamp on the latest date, you can reduce the amount of data you read from the database by only getting the latest date:
DatabaseReference ref = FirebaseService.getFirebaseDatabase().getReference("/devices/device1");
ref.orderByKey().limitToLast(1).addValueEventListener(new ValueEventListener() {
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot timeSnapshot: dataSnapshot.getChildren()) {
DeviceData message = timeSnapshot.getValue(DeviceData.class);
System.out.println(message);
}
}
Map<String, DeviceData> document = (Map<String, DeviceData>) dataSnapshot.getValue();
setUpdatedDocumentData(document);
}
public void onCancelled(DatabaseError error) {
System.out.print("-----Error-----:\n" + error.getMessage());
}
});
You'll still have to read all timestamps for that date, but at least you're now only reading data for the most recent day.
I am trying to make a message section in my app.
Model Description:
You can ignore DUYURU, it isn't related with topic.
child of DUYURU means author's uid.
Number represents messages unique index.
Model
My java-android code:
mRef = FirebaseDatabase.getInstance().getReference("Tests").child("DUYURU");
mRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
posts.clear();
for (DataSnapshot userMessages:snapshot.getChildren()) {
//These 2 values become null since childs are not exist
String sender = userMessages.child("sender").getValue(String.class);
String photoUri = userMessages.child("photoUri").getValue(String.class);
String uid = userMessages.getKey();
for (DataSnapshot dataSnapshot: userMessages.getChildren()) {
Post post = dataSnapshot.getValue(Post.class);
post.setPostInfo(sender,photoUri,uid);
post.setIndex(Integer.parseInt(dataSnapshot.getKey()));
posts.add(post);
}
}
Collections.sort(posts,Collections.<Post>reverseOrder());
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Log.e(TAG, "onCancelled: ",error.toException() );
}
});
Then sender's value becomes null since there is no child called sender.
So how can i create a child if not exists while messages are retrieving.
//checking if object is not exist in for loop
if (!userMessages.hasChild("sender")) {
mRef.child(userMessages.getKey()).child("sender").setValue("sendername");
}
I am working with firebase database and i was trying to get the value of a child using this code below and may System.out.println(MyCredit.toString()); is always returns null: Please see my firebase database
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.addListenerForSingleValueEvent(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get map of users in datasnapshot
CollectCredits((Map<String,Object>) dataSnapshot.getValue());
}
#Override
public void onCancelled(DatabaseError databaseError) {
//handle databaseError
}
});
private void CollectCredits(Map<String,Object> users) {
MyCredit = new ArrayList<>();
//iterate through each user, ignoring their UID
for (Map.Entry<String, Object> entry : users.entrySet()){
//Get user map
Map singleUser = (Map) entry.getValue();
//Get Credit field and append to list
MyCredit.add((Long) singleUser.get("Credit"));
Toast.makeText(MainActivityCustonlistViewnew.this, "Credit : " +String.valueOf(MyCredit), Toast.LENGTH_SHORT).show();
}
System.out.println(MyCredit.toString());
}
Try this:
private void CollectCredits(DataSnapshot dataSnapshot) {
MyCredit = new ArrayList<>();
//iterate through each dataSnapshot
for (DataSnapshot d1 : dataSnapshot.getChildren()){
MyCredit.add(d1.getValue());
}
}
Let me give you some suggestions, Try to check your firebase database path both the root and child path because some time you did everything correctly but the path you specified to your Database reference which is not referring to the correct path. So it can produce the same result what are getting right now.
I have this piece of code in swift which loads up data from Firebase into dictionary a dictionary object.
i need to do same in java but its not dont know how. pl
// This is swift version
var yourArray = NSMutableArray()
func GetData() {
ref = Database.database().reference()
ref.child(bookTitle).observe(.value, with: { (snapshot) in
let children = snapshot.children
let allObj = children.allObjects
for i in 0 ..< allObj.count {
self.yourArray.add(allObj[i])
}
}) { (error) in
print(error)
}
Try This One
List<MyPojoClass> myList = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
myList.clear();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
MyPojoClass pojo= postSnapshot.getValue(MyPojoClass.class);
myList.add(pojo);
// here you can access others property of pojo class.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});