Issue
I have created an event handler for the onClick button. When I click on the button, I want to transfer a pre-recorded number in the database to the price section.
My problem is that: when I click on the button and want to pass the value "pricecode" recorded in the database to "price". But it is mandatory that the pricecode
is pre-recorded in the database.
String price = String.valueOf(db.child("User").child("pricecode"));
and instead of the value "1000", it writes a reference to the key there. Read more in the screenshot.
public void onClickB1 (View view)
{
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
String id = mDataBase.getKey();
String name = String.valueOf(textB1.getText());
String price = String.valueOf(db.child("User").child("pricecode")); // PROBLEM
User newUser = new User(id,name,price);
//mDataBase.push().setValue(newUser);
if (!TextUtils.isEmpty(name))
{
mDataBase.push().setValue(newUser);
}
else
{
Toast.makeText(this,"empty text",Toast.LENGTH_LONG).show();
}
}
Solution
String price = String.valueOf(db.child("User").child("pricecode")); and instead of the value "1000", it writes a reference to the key there.
That's the expected behavior since the following operation:
String price = String.valueOf(db.child("User").child("pricecode"))
Does not store in the price
variable the actual value (1000) of the pricecode
field. The code inside the valueOf()
method is a reference, so when you're passing that reference to the valueOf()
method, you get:
https://testkornze...
So there is no way you can read a value of a particular field that exists in the Realtime Database without attaching a listener. I answered earlier a question of yours on how to read the value of pricecode
. So to be able to use the value of pricecode
, all operations that need data from the database should be added inside the onComplete()
method.
Answered By - Alex Mamo
Answer Checked By - Gilberto Lyons (JavaFixing Admin)