Reading data from firebase realtimedatabase - java

I am writing data to the database using another class with a constructor, but I still need to read data from the database. In the documentation, when using other classes, you need to create HashMap lists for each element, but I have 2 classes (since I need to write more than 255 entries to the database) and in each class, I will have to write a HashMap. How can I load the name of a DB variable that is identical to the name in the file itself? For example int b = 0; and in the database - b: 0 and how can you get the value of each variable from the database?
I send data like this:
if (user != null) {
if(database.child(getEmail)==null) {
User newUser = new User(getEmail, coins, ....);
User1 newUser1 = new User1(a256, a257, ....);
database.child(getEmail).push().setValue(newUser1);
database.child(getEmail).push().setValue(newUser);
}
I read data like this:
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for(DataSnapshot ds : snapshot.getChildren()){
User user = ds.getValue(User.class);
//saving information witch will read from db in SharedPreferences
PreferenceConfig.GetEmail(getApplicationContext(), getEmail);
PreferenceConfig.GetCoin(getApplicationContext(), getEmail);
PreferenceConfig.GetA256(getApplicationContext(), a256);
...
}
}
database.addValueEventListener(valueEventListener);
But i can`t understend how can i get data from db without hashmap
JSON file:
{
"User": {
"mail#gmail:com": {
"-NHTVinbEVUAqJwK8Umt": {
"getEmail": "mail#gmail.com",
"coins": 100,
.....
},
"-NHTVinpCPOJ4UPZvgpN": {
"a256":0,
"a257":0
...............
}
}
}
}

You won't be able to read the data under fields that are dynamically created:
{
"User": {
"mail#gmail:com": {
"-NHTVinbEVUAqJwK8Umt": {
"getEmail": "mail#gmail.com",
"coins": 100,
},
"-NHTVinpCPOJ4UPZvgpN": {
"a256":0, //👈
"a257":0 //👈
}
}
}
}
You'll be able to read all the data if your second child will have the same fields as the first one:
{
"User": {
"mail#gmail:com": {
"-NHTVinbEVUAqJwK8Umt": {
"getEmail": "mail#gmail.com",
"coins": 100,
},
"-NHTVinpCPOJ4UPZvgpN": {
"getEmail": "other#gmail.com", //👈
"coins": 200, //👈
}
}
}
}
Now, to read the data from such a structure, you have to create a reference that points to mail#gmail:com node and make a get() call as you can see in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference emailRef = db.child("User").child("mail#gmail:com");
emailRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String email = ds.child("getEmail").getValue(String.class);
Log.d("TAG", email);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
mail#gmail.com
other#gmail.com
Or you can map each DataSnapshot object into an object of type User:
User user = ds.getValue(User.class);
This operation will work, only if your User class contains two fields called getEmail and coins. The first being a string and the second one a number.

Related

How to do Arithmetic operations between two nodes of Firebase Realtime Database in Android Studio

I am having two tables Customers and Transaction nodes. Transaction node is related to data of Customer node by Vehicle Number a data in Customer node. I want to subtract the amount paid from the Customer node Due Amount
Customer Table:-
"Customers": {
"-NFFTcWFGLXi063jCTcT": {
"branch": "Rajeev Nagar",
"currentDownPayment": "80000",
"currentdueAmount": "20000.0",
"customerAadharNumber": "123456",
"customerAddress": "ANYWHERE",
"customerName": "VIKASH",
"customerPhoneNumber": "7481900892",
"customerTenure": "12",
"dateOfdelevry": "28/10/2022",
"downPayment": "100000",
"duePayment": "100000.0",
"emiPerMonth": "8333",
"emiStartDate": "26/10/2022",
"granterName": "RATHI",
"granterPhoneNumber": "7481900896",
"localitymodal": "NEAR ME",
"motorNumber": "QWERT",
"outStandingAmount": "120000.0",
"vehicleAmount": "200000",
"vehicleBodyType": "Steel",
"vehicleColour": "Gray",
"vehicleNumber": "1234567890QWERTYU"
},
Transection table:-
Transaction": {
"1234567890QWERTYU": {
"-NFFZLr7-9sTrZ1OlbjF": {
"dateOfPayment": "27/10/2022",
"discountGiven": "00",
"discountRemarks": "8000",
"lateFine": "no discount ",
"paymentReceived": "500"
}
The key of the Transaction Table is the same as the Customer Table Vehicle Number see the last data of the Customer Table
databasePaymentUpdate = FirebaseDatabase.getInstance().getReference("Customers");
databasePaymentUpdate.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
for (DataSnapshot ds : snapshot.getChildren()) {
String VehicleNumber = ds.child("vehicleNumber").getValue(String.class);
String vehNo = PaymentUpdateVehicleNumber.getText().toString().trim();
if (VehicleNumber.equals(vehNo)) {
Toast.makeText(PaymentUpdate.this, "Welcome to Jyoti Motors", Toast.LENGTH_SHORT).show();
}
To solve this problem, you have to use nested listener, as you can see in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = db.child("Customers");
customersRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> customersTask) {
if (customersTask.isSuccessful()) {
for (DataSnapshot customerSnapshot : customersTask.getResult().getChildren()) {
String vehicleNumber = customerSnapshot.child("vehicleNumber").getValue(String.class);
DatabaseReference vehicleNumberRef = db.child("Transaction").child(vehicleNumber);
vehicleNumberRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> vehicleNumberTask) {
if (vehicleNumberTask.isSuccessful()) {
long sum = 0;
for (DataSnapshot paymentSnapshot : vehicleNumberTask.getResult().getChildren()) {
String paymentReceived = paymentSnapshot.child("paymentReceived").getValue(String.class);
sum += Integer.valueOf(paymentReceived)
}
Log.d("TAG", "sum: " + sum);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
And the result in the logcat will be:
sum: 500
Please also note, that is recommended to store the prices as numbers and not as strings, case in which the above addition should look like this:
long paymentReceived = paymentSnapshot.child("paymentReceived").getValue(Long.class);
sum += paymentReceived;

how to get specific child with spacific attribute ..here is my firebase

Here is my Firebase Realtime Database schema. I want to get passwords and usernames from all employees.
Is there a way to get a specific value of a child in the Realtime Database?
To actually get the user names and passwords from all employees, you have to create a reference that points to the "Employs" node, perform a get() call and attach a listener. So please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference employsRef = db.child("Admin").child("Employs");
employsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("name").getValue(String.class);
String password = ds.child("name").getValue(String.class);
Log.d("TAG", name + "/" + password);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
usman/88568558458

Cannot get reference to my auto generated push IDs in android

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

Adding Data to firebase Realtime Database showing Error

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.

how to load data from firebase into arraylist in java

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());
}
});

Categories