Error in reading the Firebase value: pricecode - java

Please tell me what is my mistake? I'm trying to count the pricecode and shove it into user -> price. But instead, it gives an error or a link, and not the value "1000"
enter image description here
public void onClickB1 (View view)
{
DatabaseReference bd = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference bd1 = bd.child("pricecode");
String id = mDataBase.getKey();
//String key = dataSnapshot.getKey();
String name = String.valueOf(textB1.getText());
**String price = bd1.child("pricecode").getValue(String.class);**
User newUser = new User(id,name,price);
//mDataBase.push().setValue(newUser);
if (!TextUtils.isEmpty(name)) // проверка пустой строки
{
mDataBase.push().setValue(newUser);
}
else
{
Toast.makeText(this,"Заполните поля",Toast.LENGTH_LONG).show();
}
}

There is no way you can call getValue() on an object of the type DatabaseReference. Why? Because there is no such method inside the class. On the other hand, DataSnapshot class contains a getValue() method. So to be able to read that value, you have to attach a listener as in the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = db.child("User");
userRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
DataSnapshot snapshot = task.getResult();
String priceCode = snapshot.child("pricecode").getValue(String.class);
Log.d("TAG", "priceCode: " + priceCode);
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
As I already mentioned in an earlier question of yours, store the prices as numbers and not strings.

Related

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

How to check if user entered userid already exists in the firebase through java?

I've tried so many ways to check if a user id is already in the firebase but all method are in vain.
Below is my code to check if user id exists but whatever data I enter it does not show the required error.
userid = findViewById(R.id.userid);
String userVal = userid.getEditText(). getText().toString();
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
if(userquery) {
userid.setError("This user name already exists");
return;
}
Whenever I try to add existing value in the input it accepts the value and overwrites in the database.
Here is the screenshot of my firebase database.
Your code so far only sets up a query. It doesn't actually execute the query, so there's no way it can detect whether the data exists. To execute a query, you have to attach a listener to it.
So in your case, that could be something like:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (!task.isSuccessful()) {
Log.e("firebase", "Error getting data", task.getException());
}
else if (task.getResult().exists()) {
userid.setError("This user name already exists");
}
}
});
On older SDK versions the equivalent would be:
boolean userquery = FirebaseDatabase.getInstance().getReference().child("user").orderByChild("userid").equals(userVal);
userquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
userid.setError("This user name already exists");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}

Reading data from Firebase Realtime Database for a specific user

What is the proper way to read data from Firebase Realtime Database? I have created a database "Mybill"s with child bills. In child Bills, I am saving UserId from FirebaseAuth so it should be easy to find bills for a specific user and in userID child, I have a child that I have created using the .push() method and in that, I have data about the bill.
It looks like this:
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
this is my code for now :
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("bills");
Query checkUser = ref.orderByChild("UserId").equalTo(Autentication.GetUser());
// Attach a listener to read the data at our posts reference
checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("email").getValue(String.class);
String market = dataSnapshot.child("market").getValue(String.class);
String price = dataSnapshot.child("price").getValue(String.class);
String date = dataSnapshot.child("date").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
How should I change my Java code so I can get all the bills saved for a specific user (the user that is currently logged in)
To do that, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("bills").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds .child("email").getValue(String.class);
String market = ds .child("market").getValue(String.class);
String price = ds .child("price").getValue(String.class);
Log.d("TAG", email + "/" + market + "/" + price);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The "date" cannot be read as a String, as it's an object. So the most appropriate way would be to read it as a Map<String, Object>. In this way, you are getting only the bills that correspond to a specific user (logged-in user).

How to edit the data inside the unique id of a child in firebase database?

Trying to implement a read receipt feature in my app...
Posting Data
private void sendMessage() {
String messageText = messageArea.getText().toString();
if (TextUtils.isEmpty(messageText)) {
Toast.makeText(getApplicationContext(), "Can't Send Blank Message", Toast.LENGTH_SHORT).show();
} else {
String message_sender_ref = "Messages/" + MessageSenderId + "/" + MessageRecieverId;
String message_reciver_ref = "Messages/" + MessageRecieverId + "/" + MessageSenderId;
Map messageTextBody = new HashMap<>();
messageTextBody.put("Message", messageText);
messageTextBody.put("Seen", "False");
messageTextBody.put("Type", "Text");
messageTextBody.put("Time", ServerValue.TIMESTAMP);
messageTextBody.put("From", MessageSenderId);
DatabaseReference user_message_key = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).push();
String message_push_id = user_message_key.getKey();
Map messageBodyDetails = new HashMap();
messageBodyDetails.put(message_sender_ref + "/" + message_push_id, messageTextBody);
messageBodyDetails.put(message_reciver_ref + "/" + message_push_id, messageTextBody);
mDatabaseReference.updateChildren(messageBodyDetails, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d("Chat_Log", databaseError.getMessage().toString());
}
messageArea.setText("");
}
});
}
}
Now how do i access the "Seen = False" data which is inside a unique ID... i can access it through ValueEventListener but how do i make changes of that? i know only to fetch the data but i want to change the data of it... Can someone help me out please
Tried method
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
I tried this above method but it just creates one more hild alongside it and sets its value to true.... someone please help me out... Thanks in advance
Database - https://ibb.co/js3iDd
This method you are trying to use
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
is replacing or overwriting your current value at that reference, i would suggest to make a map and use updateChildren to just update the value at the desired reference, also if you need to update multiple values at the same reference, this will save you multiple setValues()
Map<String, Object> update = new HashMap<String,Object>();
update.put("Seen", true);
seenRef.updateChildren(update);
but you can also do the same as you are doing without "" in your setValue() because you want to poot a boolean true or false inside it and you are sending a string "True" to the database , this will create a new key replacing/overwriting that same ref with the value Seen : true
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue(true);
Please check your seenRef, i just checked your db and i think is missing one more ref
so just change your ref
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child(your_push_id_message).child("Seen");
in order to get your_push_id_message you will need to get that push id of the message to do that, first attach a listener to it and getKey()
seenRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
String pushMessage = snapshot.getKey();
dataSnapshot.child(pushMessage).child("Seen").setValue(true);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
You are doing wrong because you are the directly updating value not with message-id which you generating for the message using push()
Here you doing
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child("Seen");
seenRef.setValue("True");
But you are not referring message id in which you need to do.
Like bellow
DatabaseReference seenRef = mDatabaseReference.child("Messages").child(MessageSenderId).child(MessageRecieverId).child(Message-Id).child("Seen");
seenRef.setValue("True");

Retrieve a single entry from firebase

Below is my firebase data.
users
a81b0dec-671e-4840-9977-e932274928fb
email: "s#s.com"
screenname: "SSS"
totalmoney: "0"
uid: "a81b0dec-671e-4840-9977-e932274928fb"
c934beeb-51d2-4919-bff0-64153abff1dd
email: "p#p.com"
screenname: "PPP"
totalmoney: "0"
uid: "c934beeb-51d2-4919-bff0-64153abff1dd"
e0187af9-20a9-4088-a86c-7fb8cf3b4d47
email: "o#o.com"
screenname: "OOO"
totalmoney: "0"
uid: "e0187af9-20a9-4088-a86c-7fb8cf3b4d47"
How can I retrieve the node with uid = "a81b0dec-671e-4840-9977-e932274928fb".
Here's what I have tried so far, but it's not working.
String uid = "a81b0dec-671e-4840-9977-e932274928fb";
Query query = fb.orderByChild("uid").equalTo(uid);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot data) {
// TODO Auto-generated method stub
Log.i("SINGLE VALUE EVENT", data.toString());
}
#Override
public void onCancelled(FirebaseError error) {
// TODO Auto-generated method stub
}
});
Your current code executes a query. Since a query can match multiple child nodes, it returns a list of values. Even when there is only one matching result, it returns a list of one.
You can handle this in your code by iterating through the children:
public void onDataChange(DataSnapshot data) {
for (DataSnapshot userSnap: data.getChildren) {
Log.i("SINGLE VALUE EVENT", userSnap.child("email").getValue(String.class));
}
}
But in this case you don't even need a query, since you've (wisely) also stored the users under their uid. That means you can directly access the user by that uid, which saves some code and will be faster:
String uid = "a81b0dec-671e-4840-9977-e932274928fb";
DatabaseReference user = fb.child(uid);
user.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot data) {
Log.i("SINGLE VALUE EVENT", data.child("email").getValue(String.class));
}
public void onCancelled(FirebaseError error) {
Log.e(TAG, error);
}
});
You shouldn't duplicate the id, instead use:
ref.orderByKey().equalTo()
You can find what you are searching for there:
https://www.firebase.com/docs/android/guide/retrieving-data.html
To make your code more dynamic..you could declare a string for getting the uid values
EditText edt = (EditText)findViewById(R.id.editText);
String edtText = edt.getText().toString().trim();
String uid = edtText;
DatabaseReference db = fb.child(uid);
db.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
Toast.makeText(this, "Email for supplied user is : " + snapshot.child("email").getValue(String.class), Toast.LENGTH_SHORT).show();
}
public void onCancelled(FirebaseError error) {
Toast.makeText(this,"Error as a result of " + error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
If you know for sure that you're expecting only one entry (in this case since every record has a unique id), using psudo code I'd say, retrieve the 0 index of returned data.

Categories