Compare data from RecyclerView with Realtime Database in Firebase - java

I'm making a Quizz app and I have the questions and the answers in Realtime Database,
I have no problem displaying the information in the recyclerview, this recycler view is composed of a radio group of 3 radio buttons,
I need to compare the radio button with the record of the correct answer in realtime database.
btnacab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
database.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(corregido == false){
//for(DataSnapshot dataSnapshot : snapshot.getChildren()){
int cont = 1;
String p = "p";
npreg = p + cont;
corregirpregunta("Enfermeria", "p1");
corregido = true;
btnacab.setText("SALIR");
cont++;
// }
}else{
Intent i = new Intent(ModeloExamen3.this, GeneralTest.class);
startActivity(i);
}
myAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
pauseTimer();
}
});
*/
}
public void corregirpregunta(String tipo, String npreg){
database.child(tipo).child(npreg).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
PreguntaExamen pregunta = snapshot.getValue(PreguntaExamen.class);
if(pregunta != null){
String corr = pregunta.getCorrecta();
int n = Integer.parseInt(corr.toString());
RadioButton rbselected = findViewById(rgrex.getCheckedRadioButtonId());
int nresp = rgrex.indexOfChild(rbselected) +1 ;
if(nresp == n){
puntuacion++;
tvpuntu.setText("Puntuación: " + puntuacion+"/10");
}
resp1.setTextColor(Color.RED);
resp2.setTextColor(Color.RED);
resp3.setTextColor(Color.RED);
switch (n){
case 1:
resp1.setTextColor(Color.GREEN);
break;
case 2:
resp2.setTextColor(Color.GREEN);
break;
case 3:
resp3.setTextColor(Color.GREEN);
break;
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
The method to correct a single question works well, the problem is to make a loop so that a single method corrects all the questions that are shown in the recyclerview.

Related

Clicking on a button ends up making multiple instances of the Activity it navigates to

So I'm making an app in android studio, its like a fintech app. In one activity/page(SendMoney.java), you put in a number amount and tap the "Send Money" button, from here it goes to the page where you choose who you're sending this money to(SendReceiver.java). You select your desired recepient and tap on a second "Send Money" button, this then takes you to a success page that lists the amount sent and the username of the recepient(SendReceiverSuccessPage).
On the SendMoney page I need to get the amount inputted and pass that data to the SendReceiverSuccessPage, I've done this by using Intent and I've added this code to when the Send Money button is clicked, but in doing this what happens is that it for some reason creates multiple instances of the SendReceiver page it navigates to.
So on the SendReceiver page when I'm done and I hit the second "Send Money" button it just opens a new instance of SendReceiver whiles the SendReceiverSuccessPage is stuck in the background for some reason.
I need it to be one single smooth navigation flow where it goes from SendMoney to SendReceiver to SendReceiverSuccessPage without SendReceiver popping up multiple times and stacking ontop of the success page, all whiles being able to actively pass and retrieve the "AmountSent" data.
SendMoney.java
public class SendMoney extends AppCompatActivity {
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
Double userAmountDouble;
MaterialButton sendMoneyButton;
ImageView backspace, back;
TextView amount, currentBalanceText, currency, one, two, three, four, five, six, seven, eight, nine, zero, dot;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_money);
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
back = findViewById(R.id.back);
amount = findViewById(R.id.amount);
currency = findViewById(R.id.currency);
currentBalanceText = findViewById(R.id.current_balance);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
five = findViewById(R.id.five);
six = findViewById(R.id.six);
seven = findViewById(R.id.seven);
eight = findViewById(R.id.eight);
nine = findViewById(R.id.nine);
zero = findViewById(R.id.zero);
dot = findViewById(R.id.dot);
backspace = findViewById(R.id.backspace);
sendMoneyButton = findViewById(R.id.send_money_button);
sendMoneyButton.setText("Send GH₵0");
// Display send amount on button, in realtime
amount.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//sendMoneyButton.setText("Send GH₵0");
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// This method is called whenever the text in the EditText changes
String userInputAmount = amount.getText().toString();
sendMoneyButton.setText("Send GH₵" + userInputAmount);
}
#Override
public void afterTextChanged(Editable editable) {
//
}
});
// Connect to the database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
// Get and show available balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
currentBalanceText.setText("GH₵"+ currentBalance + " AVAILABLE");
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
// Send Money Button
sendMoneyButton.setOnClickListener(v -> {
String userInputAmount = amount.getText().toString();
if (userInputAmount.equals("") || userInputAmount.equals("0")) {
Toast.makeText(getApplicationContext(),"Please enter an amount",Toast.LENGTH_SHORT).show();
} else {
userAmountDouble = Double.parseDouble(userInputAmount);
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
assert currentBalance != null;
double currentBalanceDouble = Double.parseDouble(currentBalance);
if (userAmountDouble > currentBalanceDouble) {
Toast.makeText(getApplicationContext(),"Insufficient Balance",Toast.LENGTH_SHORT).show();
} else {
// Create an Intent and include the value of userInputAmount
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Start the SendReceiver activity
finish();
startActivity(sendReceiverIntent);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
});
// Click Listeners
back.setOnClickListener(v -> finish());
zero.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("0");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "0");
}
});
one.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("1");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "1");
}
});
two.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("2");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "2");
}
});
three.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("3");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "3");
}
});
four.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("4");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "4");
}
});
five.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("5");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "5");
}
});
six.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("6");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "6");
}
});
seven.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("7");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "7");
}
});
eight.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("8");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "8");
}
});
nine.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText("9");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + "9");
}
});
dot.setOnClickListener(v -> {
if (amount.getText().toString().equals("0")) {
amount.setText(".");
} else if (amount.getText().toString().length() == 7) {
amount.setText(amount.getText().toString());
} else {
amount.setText(amount.getText().toString() + ".");
}
});
backspace.setOnClickListener(v -> {
if (amount.getText().toString().equals("") | amount.getText().toString().equals("0")) {
amount.setText("0");
} else {
amount.setText(amount.getText().toString().substring(0, amount.getText().length() - 1));
}
});
}
}
SendReceiver.java
public class SendReceiver extends AppCompatActivity{
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
Context context;
ArrayList<SearchedUsersModel> searchedUsersModel;
RecyclerView searchedUsersRecycler;
SearchView svSearch;
MaterialButton finalSendBtn;
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sendreceiver);
// Retrieve the value of userInputAmount from the Intent
Intent intent = getIntent();
String userInputAmount = intent.getStringExtra("USER_INPUT_AMOUNT");
this.context = getApplicationContext();
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
// Hooks
searchedUsersRecycler = findViewById(R.id.recyclerUsers);
svSearch = findViewById(R.id.svSearch);
finalSendBtn = findViewById(R.id.final_send_button);
// Set the hint for the search bar
svSearch.setQueryHint("Enter name or email of user");
// On click listener for when you hit the Send button
finalSendBtn.setOnClickListener(v -> {
DatabaseReference databaseReference = database.getReference("Users");
assert firebaseUser != null;
databaseReference.child(firebaseUser.getUid()).child("transactions").child("sendTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(userInputAmount);
// Get a reference to the "transactions" collection
DatabaseReference transactionsRef = database.getReference("Transactions");
// Get a reference to the "sendTransactions" sub-collection
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
// Generate a unique ID for the new transaction
String transactionUID = sendTransactionsRef.push().getKey();
// Add the new transaction to the "sendTransactions" sub-collection
assert transactionUID != null;
sendTransactionsRef.child(transactionUID).child("amount").setValue(userInputAmount);
// This deducts the same amount from the current users main balance
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String currentBalance = snapshot.getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
assert currentBalance != null;
// The current balance minus the amount withdrawn
double amountToSubtract = Double.parseDouble(currentBalance) - Double.parseDouble(userInputAmount);
String newBalance = Double.toString(Double.parseDouble(df.format(amountToSubtract)));
// Write the new balance to the database
databaseReference.child(firebaseUser.getUid()).child("userMainBalance").setValue(newBalance).addOnCompleteListener(task -> {
if (task.isSuccessful()) {
System.out.println("Error updating user main balance: " + task.getException());
} else {
// Print an error message
System.out.println("Error updating user main balance: " + task.getException());
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
finish();
startActivity(new Intent(getApplicationContext(), SendReceiverSuccessPage.class));
});
// Connect to the database
if (svSearch != null) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
svSearch.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (!newText.isEmpty()) {
// Connect to the database
String currentUserId = Objects.requireNonNull(firebaseAuth.getCurrentUser()).getEmail();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
searchedUsersModel = new ArrayList<>();
for (DataSnapshot ds : snapshot.getChildren()) {
// Removes current user from list
SearchedUsersModel user = ds.getValue(SearchedUsersModel.class);
assert user != null;
if (!user.getMail().equals(currentUserId)) { // check if user's ID does not match current user's ID
searchedUsersModel.add(user); // add this user to the list of searched users
}
}
//Filter through the users based on Name or Email
ArrayList<SearchedUsersModel> myList = new ArrayList<>();
for(SearchedUsersModel object : searchedUsersModel) {
if(object.getMail().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
else if(object.getName().toLowerCase().contains(newText.toLowerCase())) {
myList.add(object);
}
}
SearchedUsersAdapter searchedUsersAdapter = new SearchedUsersAdapter(myList, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapter);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
} else {
// Clear the data from the RecyclerView
searchedUsersModel = new ArrayList<>();
SearchedUsersAdapter searchedUsersAdapterClass = new SearchedUsersAdapter(searchedUsersModel, finalSendBtn, svSearch);
searchedUsersRecycler.setAdapter(searchedUsersAdapterClass);
//Set button to disabled
finalSendBtn.setEnabled(false);
}
return false;
}
});
return true;
}
});
}
}
}
SendReceiverSuccessPage
public class SendReceiverSuccessPage extends AppCompatActivity {
MaterialButton greatNextButton;
TextView sendSuccessText;
public static String usersName;
FirebaseUser firebaseUser;
FirebaseAuth firebaseAuth;
FirebaseDatabase database;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sendreceiver_success_page);
// Instance of FirebaseAuth and Database
firebaseAuth = FirebaseAuth.getInstance();
database = FirebaseDatabase.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
greatNextButton = findViewById(R.id.great_next_button);
sendSuccessText = findViewById(R.id.send_success);
//Get sent amount from database
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
assert firebaseUser != null;
DatabaseReference transactionsRef = databaseReference.child(firebaseUser.getUid()).child("transactions");
DatabaseReference sendTransactionsRef = transactionsRef.child("sendTransactions");
//
sendTransactionsRef.orderByKey().limitToLast(1).addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot transactionSnapshot : dataSnapshot.getChildren()) {
String lastTransactionKey = transactionSnapshot.getKey();
assert lastTransactionKey != null;
sendTransactionsRef.child(lastTransactionKey).child("amount").addValueEventListener(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String sentAmount = snapshot.getValue(String.class);
sendSuccessText.setText("GH₵" + sentAmount + " has been sent to " + usersName);
//TODO This can also be where receiveTransactions document is created in the users database
// This sends the money to the chosen user by their name
databaseReference.orderByChild("name").equalTo(usersName).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot userSnapshot : snapshot.getChildren()) {
// Get the main balance of the chosen user
String mainBalance = userSnapshot.child("userMainBalance").getValue(String.class);
DecimalFormat df = new DecimalFormat("0.00");
// Convert the main balance and amount sent to doubles
assert mainBalance != null;
double mainBalanceDouble = Double.parseDouble(mainBalance);
assert sentAmount != null;
double amountSentDouble = Double.parseDouble(sentAmount);
// Add the amount sent to the main balance
double updatedMainBalance = mainBalanceDouble + amountSentDouble;
// Convert the updated main balance back to a string
String updatedMainBalanceString = Double.toString(Double.parseDouble(df.format(updatedMainBalance)));
// Update the main balance in the database for the chosen user
userSnapshot.getRef().child("userMainBalance").setValue(updatedMainBalanceString);
userSnapshot.getRef().child("transactions").child("receivedTransactions").child(Objects.requireNonNull(databaseReference.push().getKey())).child("amount").setValue(sentAmount);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
// Print an error message
System.out.println("Error retrieving user main balance: " + error.getMessage());
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
// Handle error
}
});
greatNextButton.setOnClickListener(v -> {
startActivity(new Intent(getApplicationContext(), MainDashboard.class));
});
}
}
There are also some Adapter classes I can add if needed.
I've been trying to figure it out with ChatGPT and have literally tried out everything.
Through testing I found out that anytime I take the
Intent sendReceiverIntent = new Intent(getApplicationContext(), SendReceiver.class);
sendReceiverIntent.putExtra("USER_INPUT_AMOUNT", amount.getText().toString());
sendReceiverIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
lines out of the sendMoney button it ended up not creating multiple instances and working exactly like how I need it to. The only problem is that the amount sent that I need to pass to the success page isn't recoreded or passed. So ideally, if I could find a way or alternative to getting this data to the desired page without putting it into the button OnClick or having it create multiple instances of the activity.

How to listen for changes in android studio using firebase

I am having a hard time reading changes on my firebase. What I am trying to do is for every change when the start button is triggered a dialog will show saying, "This has already been executed."
I tried using addListenerForSingleValueEvent but it seems that the dialog only showed when all of the children have changed.
startBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentWeek = programTrackers.get(0).getWeek();
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("ProgramTracker")
.child(GlobalUser.getmUser().getiD())
.child(programTrackers.get(0).getProgramId());
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
final int childCount = (int) dataSnapshot.getChildrenCount();
int count = 0;
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
ProgramTracker programTracker = snapshot.getValue(ProgramTracker.class);
if (programTracker.getProgramExerciseWeek() == currentWeek) {
programTrackChecker.add(programTracker);
}
count++;
}
if (count == childCount) {
boolean isFinished = false;
//last iteration
for (int i = 0; i < programTrackChecker.size(); i++) {
if (programTrackChecker.get(i).isProgramExerciseFinished()) {
isFinished = true;
} else
isFinished = false;
}
if (isFinished) {
AlertDialog.Builder builder = new AlertDialog.Builder(DayExerciseActivity.this);
builder.setMessage("You have already completed all exercises. Are you sure you want to do it again?");
builder.setPositiveButton("Yes", (dialogInterface, i) -> {
startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
.putExtra("programTrackers", programTrackers)
.putExtra("exerciseNum", String.valueOf(0)));
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.show();
} else
startActivity(new Intent(DayExerciseActivity.this, DoProgramActivity.class)
.putExtra("programTrackers", programTrackers)
.putExtra("exerciseNum", String.valueOf(0)));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You need to change this:
databaseReference.addListenerForSingleValueEvent(new ValueEventListener
Into this:
databaseReference.addValueEventListener(new ValueEventListener
From the docs:
public abstract void onDataChange (DataSnapshot snapshot)
This method will be called with a snapshot of the data at this location. It will also be called each time that data changes

How to sum the data and transfer it to Firebase?

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

Get data from firebase from a specific position

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++;
}
}

Trying to write same child to firebase twice

I am trying to execute this if statement so the value 'Like' with the unique id is written to the database twice. The line of code is:
mDatabaseChemRef.child(uploadCurrent.getNumber()).child(mAuth.getCurrentUser().getUid()).setValue("Like");
and the database is stored like so:
{
"467" : {
"4ulBYMRcP4WbhTCFXHSTNwX2yPU2" : "Like"
}
}
So essentially I want the "Like" along side the same unique ID to be written twice rather than once. Below is the full code. So when the user clicks the like button I want it to like twice rather than once is there a way to write this line twice?
holder.mLikebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mProcessTechLike = true;
mDatabaseTechRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(uploadCurrent.getCategory().equals("Technology")) {
if (mProcessTechLike) {
if (dataSnapshot.child(uploadCurrent.getNumber()).hasChild(mAuth.getCurrentUser().getUid())) {
//delete like
dataSnapshot.child(uploadCurrent.getNumber()).child(mAuth.getCurrentUser().getUid()).getRef().removeValue();
mProcessTechLike = false;
Toast.makeText(mContext, "Vote Retracted", Toast.LENGTH_LONG).show();
holder.mLikebtn.setColorFilter(null);
} else {
Resources res = mContext.getResources();
final int newColor = res.getColor(R.color.new_color);
holder.mLikebtn.setColorFilter(newColor, Mode.SRC_ATOP);
mDatabaseTechRef.child(uploadCurrent.getNumber()).child(mAuth.getCurrentUser().getUid()).setValue("Like");
mProcessTechLike = false;
Toast.makeText(mContext, "Vote Counted", Toast.LENGTH_LONG).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});

Categories