Realtime refresh after deleting data from firebase - android

I have a button to delete amounts, and I have a textview with total amount, but when I delete amounts the textview with the total does not update, it only does if I go to another activity and come back, why is it? any ideas?
public void onClick(View view) {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference().child("Expenses").child(FirebaseAuth.getInstance().getCurrentUser().getUid());
reference.child(postId).removeValue().addOnCompleteListener(new OnCompleteListener<Void>() {
Expense expenseBackUp = new Expense(item, category, date, postId, amount);
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Snackbar.make(rv, item + " has been deleted", Snackbar.LENGTH_LONG).setAction("UNDO", new View.OnClickListener() {
#Override
public void onClick(View view) {
reference.child(postId).setValue(expenseBackUp);
}
}).show();
} else {
Toast.makeText(ExpensesActivity.this, "Something went wrong, try again" + task.getException(), Toast.LENGTH_SHORT).show();
}
}
});
dialog.dismiss();
}

Related

how can i make error toast message if data is not inserted into firebase (this is my code)

this is my code qr code scanner
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
onBackPressed();
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
}
}
});
}
the successful task is working
In your code I see you are using wrong onBackPressed();
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
Toast.makeText(getApplicationContext(), "DATA INSERTED", Toast.LENGTH_SHORT).show();
} else {
// Error handling here
Toast.makeText(getApplicationContext(), "DATA INSERT ERROR", Toast.LENGTH_SHORT).show();
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
UPDATE:
I have updated the code, the best way to display toast for both Fragment and Activity. And I have added Log.d to check where the program runs and if it's working properly
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
public class BaseFragment extends Fragment {
private static final int MSG_SHOW_TOAST = 1;
void displayMessage(String message, boolean isLengthLong) {
requireActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(requireActivity(), message, longShow).show();
}
});
}
}
public class Demo extends BaseFragment {
private String TAG = getClass().getSimpleName();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayMessage("Ahihi", false);
}
public void yourMethod() {
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is " + task.isSuccessful());
if (task.isSuccessful()) {
displayMessage("DATA INSERTED", true);
} else {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
displayMessage("DATA INSERT ERROR", true);
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
//========================================= below code is for activity
public class BaseActivity extends AppCompatActivity {
void displayMessage(String message, boolean isLengthLong) {
runOnUiThread(new Runnable() {
#Override
public void run() {
int longShow = isLengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT;
Toast.makeText(getApplicationContext(), message, longShow).show();
}
});
}
}
public class Demo extends BaseActivity {
private String TAG = getClass().getSimpleName();
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
displayMessage("Ahihi", false);
}
public void yourMethod() {
databaseReference.child(id).setValue(data).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is " + task.isSuccessful());
if (task.isSuccessful()) {
displayMessage("DATA INSERTED", true);
} else {
// Put the log here, Check the log outputted from mobile on android studio to make sure this is working
Log.d(TAG, "yourMethod: onComplete: status task is ERROR ");
displayMessage("DATA INSERT ERROR", true);
}
onBackPressed(); //This will exit the screen, you should consider whether to use it
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
}
}

How can I delete this Specific node from Firebase Database?

I have created a Like button in the App. When user click on the Like Button a Node called "Like Posts" with a child (random Key) is created where the details of the posts are saved as you can see in the Image.
But, when i click on the Like button again, the node should get removed as per standards. But, that's not happening.
This is my code :
holder.fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = likesReference.push().getKey();
FirebaseDatabase.getInstance().getReference("Users").child(firebaseAuth.getUid()).child("Liked Posts").child(id).removeValue();
Toast.makeText(context, "Removed from Favorites !", Toast.LENGTH_SHORT).show();
} else {
likesReference = FirebaseDatabase.getInstance().getReference("Users").child(firebaseAuth.getUid()).child("Liked Posts");
Toast.makeText(context, "Added to Bookmarks", Toast.LENGTH_SHORT).show();
likesReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
HomeModel homeModel1 = new HomeModel(holder.newsTitleTextView.getText().toString().trim(), holder.newsDetailTextView.getText().toString().trim(),
holder.timesAgo.getText().toString().trim(), homeModel.getNewsImage(), homeModel.viewCounts);
String id = likesReference.push().getKey();
Log.e("KEY IS", id); //right one
likesReference.child(id).setValue(homeModel1);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
How to delete the "Liked Posts" ?

Fill spinner from EditText value

I managed to create the account and authentication when I click on the register button I redirect to login page after that I create a new activity (rdv_detail) which contains a spinner which recovers the values ​​entered names. the problem it is when I create a new account I click on register normally I have to redirect to login page but I redirect to the page (rdv_detail) the spinner managed to recover the value entered at the beginning in the edit text field but when I reconnect by the same user the spinner is empty and I want the spinner to keep all the values ​​entered (name) at the start by the form is there anyone who can help me because I don't know exactly where the error is but I don't have the result I want (account.java -> login.java-> click on a button-> rdv_detail.java (which contains the spinner)
account.java
public class account extends AppCompatActivity {
private EditText nameDoctor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
registerButton = findViewById(R.id.btt_register);
nameDoctor = findViewById(R.id.name_doc);
}
//code
private void registerDoctor() {
String name = nameDoctor.getText().toString();
//code
final Doctor doctor = new Doctor(name, city, adress, email, tel, speciality, code);
mAuth.createUserWithEmailAndPassword(doctor.email, password).addOnCompleteListener(new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isComplete()) {
Toast.makeText(account.this, "Error ...: " +
task.getException().getMessage(), Toast.LENGTH_LONG).show();
Log.e("doctor", "Error....: " +
task.getException().getMessage());
} else {
Log.e("Adddoctor", "user account created");
new Thread(new Runnable() {
#Override
public void run() {
SaveDoctorData(doctor);
Intent sendNameIntent = new Intent(account.this, rdv_detail.class);
String name=nameDoctor.getText().toString();
sendNameIntent.putExtra("nameDoctor",name);
startActivity(sendNameIntent);
}
}).start();
}
}
});
}
private void SaveDoctorData(Doctor doctor){
db.collection("doctor").add(doctor).addOnCompleteListener(new
OnCompleteListener<DocumentReference>() {
#Override
public void onComplete(#NonNull Task<DocumentReference> task) {
if (!task.isComplete()) {
Toast.makeText(Compte.this, "Error ...: " +
task.getException().getMessage(), Toast.LENGTH_LONG).show();
Log.e("doctor", "Error: " +
task.getException().getMessage());
}else{
Toast.makeText(account.this, " user account created",
Toast.LENGTH_LONG).show();
redirectToLoginPage();
}
}
});
}
private void redirectToLoginPage() {
Intent intent = new Intent(this, login.class);
startActivity(intent);
}
public void cancel(View view) {
redirectToLoginPage();
}
}
rdv_detail.java
//code
public class rdv_detail extends AppCompatActivity implements
DatePickerDialog.OnDateSetListener,TimePickerDialog.OnTimeSetListener,View.OnClickListener{
//code
Spinner spinner_doc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rdv_detail);
spinner_doc =findViewById(R.id.spinner_doctor);
String nameExtra = getIntent().getStringExtra("nameDoctor");
if(nameExtra !=null)
{
ArrayList<String> spinnerData = new ArrayList<String>();
spinnerData.add(nameExtra);
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(rdv_detail.this,
android.R.layout.simple_spinner_item, spinnerData);
spinner_doc.setAdapter(arrayAdapter);
}
}
}

I get duplicate data when I click on alert dialog in adapter class of fragment

I found a issue is that when I turn back the fragment , it will show duplicate data.
I try to clear the arrayList data to solve it.
But I want to know more smart way.
Is it possible to avoid this issue for duplicate data ?
Adapter Class
myHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
CharSequence options[] = new CharSequence[]{"Accept Request", "Cancel Request"};
final AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0){
acceptRequest(requestList.get(i).getId(),myHolder);
}
else if (which == 1){
cancelRequest(requestList.get(i).getId(),myHolder);
}
}
});
builder.show();
}
});
}
private void cancelRequest(final String uid, final MyHolder myHolder) {
friendReqDbRef
.child(current_uid)
.child(uid)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
friendReqDbRef
.child(uid)
.child(current_uid)
.removeValue()
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
requestList.remove(myHolder.getAdapterPosition());
notifyItemRemoved(myHolder.getAdapterPosition());
notifyItemRangeChanged(myHolder.getAdapterPosition(), requestList.size());
}
});
}
});
}

How to multiply in setValues in android studio

How do I multiply the value of quan (which is quantity) to price
I need to get the total of the price depending on the quantity that is ordered.
Thank you!!! :)
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
newForm.child("Food").setValue(food);
newForm.child("Quantity").setValue(quan);
newForm.child("Price").setValue(price);
newForm.child("Table").setValue(dataSnapshot.child("Name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>()
{
#Override
public void onComplete(#NonNull Task<Void> task)
{
Toast.makeText(FoodDetail.this, "Submitted", Toast.LENGTH_SHORT).show();
//startActivity(new Intent(FoodDetail.this, Menu.class));
}
});
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
add this line to calculate total price.
newForm.child("Total_Price").setValue(quan*price);

Categories

Resources