I have a field in Firebase: balance. What I need is that after a person enters a sum 100, the field changes the value to 100. Then when the person enters a sum of 50, the field value becomes 150.
How do I write processing logic on the client? Summation of data. I think it is over-easy, but I need your help!
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String user_id = mAuth.getCurrentUser().getUid();
String balance = dataSnapshot.child(user_id).child("Balance").getValue(String.class);
mCountPayment.setText(balance + " ₽");
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mPaymentButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
paymentIntent();
}
});
}
private void paymentIntent() {
final String user_id = mAuth.getCurrentUser().getUid();
final String count = mPaymentList.getText().toString().trim();
if (!TextUtils.isEmpty(count)) {
mDatabaseUsers.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mDatabaseUsers.child(user_id).child("Balance").setValue(count);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
To write a value to the realtime database based on an existing value, you will need to use a transaction.
The basic code for your transaction will look like this:
DatabaseReference balanceRef = FirebaseDatabase.getInstance().getReference("/Users/"+ user_id +"/Balance");
Long delta = 50l;
balanceRef.runTransaction(new Transaction.Handler() {
#Override
public Transaction.Result doTransaction(MutableData mutableData) {
Long balance = mutableData.getValue(Long.class);
if (balance == null) {
mutableData.setValue(delta);
}
else {
Long amount = mutableData.getValue(Long.class);
amount = amount + delta;
mutableData.setValue(amount);
}
return Transaction.success(mutableData);
}
#Override
public void onComplete(DatabaseError databaseError, boolean b,
DataSnapshot dataSnapshot) {
// Transaction completed
Log.d(TAG, "balanceTransaction:onComplete:" + databaseError);
}
});
Related
Hy, I'm writing an application that has to get specific data from firebase using the position of the item in the listView. My problem is that I have no idea how to take it this item on firebase.
For all child of Torneo I have to control all the nameCreator.
I have tried this:
public Boolean RegisterUser(Data data, final int position, final Context c){
boolean registration;
final ArrayList<String> Creator = new ArrayList<>();
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(data.child("nameCreator").getValue().toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
return registration;
}
Data is a class with some getter and setter that I have created.
position is the position of the element on the list view.
Thanks for answers.
Change the following:
databaseReference.orderByChild("Tornei").equalTo(Integer.toString(position)).addListenerForSingleValueEvent(new ValueEventListener() {
into this:
databaseReference.child("Tornei").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
Creator.add(datas.child("nameCreator").getValue().toString());
if(Creator.equals(data.getNameCreator())){
registration = false;
}else{
registration = true;
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Then you will be able to loop and retrieve the value of nameCreator
It's easy.
【Step 1 | Get Snapshot Data and Save in Global Variable】
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference fruitsReference = rootReference.child("fruits");
DataSnapshot fruitsData;
#Override
protected void onStart() {
super.onStart();
fruitsReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshots) {
fruitsData = dataSnapshots;
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
【Step 2 | Find Your Target Position through the Loop】
public void onClick(View view) {
int index = 0;
for (DataSnapshot childSnapshot : fruitsData.getChildren()) {
if (index == 1) { //your target position
DatabaseReference currentFruitReference = childSnapshot.getRef();
currentFruitReference.setValue("peach"); //do whatever you want
}
index++;
}
}
I need to find if a child with particular value in one of its fields exists in Firebase.
Below is my database structure:
To check if a field exists,you can do this:
DatabaseReference ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
ref.addValueEventListener(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//then it exists
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
This will check if
child("bdxhATalcDRJCiZZcUFUJo3yrJF2") exists in the database.
If you do this:
ref=FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2").orderByChild("chat_id").equalTo(chatid);
then it will check if that child also exists in the database
In your case you would set up query like this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference.orderByChild("chat_id").equalTo("CHAT_ID_To_COMPARE");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This would filter your data at server side and no need to filter data at app side.
postRef = FirebaseDatabase.getInstance().getReference().child("bdxhATalcDRJCiZZcUFUJo3yrJF2");
postRef.orderByChild("chat_id").equalTo(chat_id)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
//bus number exists in Database
} else {
//bus number doesn't exists.
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
etEmail is an EditText
I did it for userEmail's value... as I don't have any username other than the email.
for a structure like this...
"users": {
pushId: {
"userEmail": {
}
}
}
onCreate
etEmail.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(final CharSequence s, int start, int before, int count) {
//yourFunction();
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference().child("users");
databaseUsers.orderByChild("userEmail").equalTo(String.valueOf(s))
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot issue : dataSnapshot.getChildren()) {
// do something with the individual object
//User email already exists
//do something
//return; stops the function from executing further
return;
}
} else {
// email doesn't exists.
// do something
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
#Override
public void afterTextChanged(Editable s) {
}
});
When you do the reference and you have your DataSnapshot, you can check it like this:
yourref.child("chat_id").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
//Do something
}
}
exists()
Returns true if the snapshot contains a non-null value.
Also returns true if this DataSnapshot contains any data. It is slightly more efficient than using DataSnapshot.getValue() !== null.
I have JsonString by receive DataSnapShot:
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
in normal if i know the key (-L3Mh7kKl04GSrndbrVD) ill code:
JSONObject a = new JSONObject(c);
JSONObject jsonUser = a.getJSONObject("-L3Mh7kKl04GSrndbrVD");
But i dont have that key, How i can get that value (name, pass, img, ...) with code, im newbie. Thanks all alot
try this:
DatabaseReference references=FirebaseDatabase.getInstance().getReference().child("user");
references.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot data: dataSnapshot.getChildren()){
String name=data.child("name").getValue().toString();
String password=data.child("pass").getValue().toString();
String img=data.child("img").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here the reference is the user node, then using the for loop it will iterate inside every push id to give you the values (name,img,pass,...).
Try this
myRef.child("user").orderByChild("u_email").equalTo(name).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String c = dataSnapshot.getValue().toString();
Log.w(Login.TAG, "Data: "+ c);
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String u_img = ds.child("u_img").getValue(String.class);
String u_pass = ds.child("u_pass").getValue(String.class);
String u_address = ds.child("u_address").getValue(String.class);
Log.d("TAG",u_img + " / " + u_pass + " / " + u_address);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
database rules
my database
I have a problem with writing data in firebase database
It must give an id for the data using method postId()
Sometimes its give me a right id and another time wrong id or updata data in an id was created
the id must be like this for all user post
[user1]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
[user2]
postId1
postId2
postId3
postId4
postId5
.
.
postId100000
........................................................................
if (auth.getCurrentUser() != null) {
mDatabase.child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID).setValue(adver,
new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError == null) {
Toast.makeText(getContext(), "Data is saved successfully", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getContext(), "Data isn,t saved , please try again", Toast.LENGTH_LONG).show();
}
}
});
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(auth.getCurrentUser().getUid()).child(POSTID);
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mAdUserDatabse.child("userid").setValue(auth.getCurrentUser().getUid());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void postId() {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
if (snapshot.hasChild(auth.getCurrentUser().getUid())) {
// run some code
mAdUserDatabse = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO");
mAdUserDatabse.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
please save my life
You're running a loop and overwriting value of postId again and again, so the postId is equal to the count of last child. So you're always getting the postId count for last user.
so have a look again at the part
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.e(snap.getKey(), snap.getChildrenCount() + "");
if (snap.getChildrenCount() != 0) {
postId = "postId" + String.valueOf(snap.getChildrenCount() + 1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
} else {
postId = "postId" + String.valueOf(1);
SharedPreferencesUtils.setStringPreference(getActivity(), "postId", postId);
}
}
Consider using separate key for every user's postId or make a function to get key for one user something like this
public void getPostId(String userId) {
final String postId = "post";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("AdUsersINFO").child(userId);
rootRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
long c = snapshot.getChildrenCount();
if(c==) postId = postId+"1";
else postId = postId+ c+1;
},
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
};
I have just added few values using Firebase:
Screen from Firebase
I would like to sum up those values and display 15 as a result in the log.
Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DatabaseReference beersRef = FirebaseDatabase.getInstance().getReference("Rank");
final ArrayList<Integer> score = new ArrayList<>();
score.add(9);
score.add(2);
score.add(4);
beersRef.push().setValue(score);
beersRef.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To achieve this, please use the following code. It's the simples way.
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference rankRef = rootRef.child("Rank");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int sum = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
int value = ds.getValue(Integer.class);
sum =+ sum + value;
}
Log.d("TAG", sum);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
rankRef.addListenerForSingleValueEvent(eventListener);
Your output will be: 15
use ValueEventListner and , don't use childEventListner,
follow the below line...Here " UI and UI.class " means...java class name ..where you put getters and setters ...
here I store int value in firebase...so need to convert int value to String and set a text to text viewholder...if u don't store in int ..than u can use String
beersRef.addValueEventListener(new ValueEventListener() {`
#Override
public void onDataChange(DataSnapshot dataSnapshot) {``
int total = 0;
for (DataSnapshot ds : dataSnapshot.getChildren()) {
UI result = ds.getValue(UI.class);
total = total + result.getMrp_final();
}
String tl = total + "";
tv_total.setText(tl);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
make sure int total value is zero...
thankyou