How to copy data from one table to another table in Firebase? - java

I have two tables - cartOrders and placedOrders. cartOrders is used to add products to cart, and placedOrders is activated when the user presses "Place Order" button.
I need to copy data from cartOrders to placedOrders when the user clicks the "Place Order" button, but I'm not able to do so.
cartDatabase = FirebaseDatabase.getInstance().getReference("cartOrders");
cartQuery = cartDatabase.child(orderID).orderByChild("productQuantity").startAt(1);
placedOrdersDatabase = FirebaseDatabase.getInstance().getReference("placedOrders");
placedOrderQuery = placedOrdersDatabase.child("orderID");
placeOrderButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartDatabase.child(orderID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
//Logic to add data to data to placedOrders.
String name = dataSnapshot.child("productName").getValue(String.class);
System.out.println("ProductName: " + name);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Intent intent = new Intent(getApplicationContext(), OrderPlacedActivity.class);
intent.putExtra("ORDER_ID", orderID);
startActivity(intent);
}
});
In the code, I was checking if the code is picking up the data from the database, but it wasn't. The output is null. Both the tables have the same structure.
Any help will be appreciated.
Thanks!
My cartOrders table structure:
cartOrders:
----------OrderID:
-----------------ProductID:
---------------------------ProductID:
---------------------------ProductName:
---------------------------ProductPrice:
---------------------------ProductQty:

#Alex Mamo answered this question on a different question.
private void copyRecord(Query fromPath, final DatabaseReference toPath) {
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
toPath.setValue(dataSnapshot.getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isComplete()) {
System.out.println("Complete");
} else {
System.out.println("Failed");
}
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
fromPath.addListenerForSingleValueEvent(valueEventListener);
}
The code works fine.
Link:Moving or copying data from one node to another in firebase database

Related

Realtime database add value from dropdown all item at the same time

I already done one by one add value to realtime database from the dropdown with add button.
here my code for adding a single value
private void SaveStudent() {
Query query = databaseReference.orderByChild("lrn").equalTo(StudentLRN);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
databaseReference = firebaseDatabase.getReference("Class");
Query query = databaseReference.child(className).child("StudentLRN")
.child(StudentLRN);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()) {
autoCompleteSelectStudent.setText("");
autoCompleteSelectSection.setText("");
textInputLayoutStudent.setVisibility(View.GONE);
Toast.makeText(TeacherClassroomActivity.this, StudentName + " Already Added!", Toast.LENGTH_SHORT).show();
} else {
databaseReference = firebaseDatabase.getReference("Class");
databaseReference.child(className)
.child("StudentLRN").child(StudentLRN)
.child("LRN").setValue(StudentLRN);
databaseReference.child(className)
.child("StudentLRN").child(StudentLRN)
.child("StudentName").setValue(StudentName);
autoCompleteSelectStudent.setText("");
autoCompleteSelectSection.setText("");
Toast.makeText(TeacherClassroomActivity.this, StudentName + " Added Successfully!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
query.addListenerForSingleValueEvent(eventListener);
} else {
Toast.makeText(TeacherClassroomActivity.this, "No Student Exist in this LRN!!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
};
query.addListenerForSingleValueEvent(eventListener);
}
Student list
and from the image above i want to add all student from dropdown list in one submit button.

User ID not detecting in my Forum App using Android Studio Firebase

Currently developing a Forum App where user who post question will get a notification if someone respond to them. Right now the coding has logical error where the notification does not go into the original poster attribute in the User table inside Firebase
Below is the code to add notification
private void addToHisNotification(String hisUid,String Post_Key,String notification){
String timestamp = ""+System.currentTimeMillis();
HashMap<Object, String> hashMap = new HashMap<>();
hashMap.put("timestamp",timestamp);
hashMap.put("Postkey",Post_Key);
hashMap.put("uid",hisUid);
hashMap.put("notification",notification);
hashMap.put("sUid",current_user_id);
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
ref.child(hisUid).child("Notifications").child(timestamp).setValue(hashMap)
.addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
}
});
}
And this is the function to add Answer and will call function Notification
PostAnsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Userref.child(current_user_id).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()){
String userName = dataSnapshot.child("Username").getValue().toString();
String profileImg = dataSnapshot.child("profileImage").getValue().toString();
String department = dataSnapshot.child("Department").getValue().toString();
ValidateAnswer(userName,profileImg, department);
addToHisNotification("" + hisUid,"" + Post_Key, "Commented on your post");
AnswerInputText.setText("");
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
The Null in the image is supposed to be the original poster UID but instead it becomes null. How do I solve this so that the Null becomes the UID of the OP?

Firebase not retrieve last data when data changes and not execute conditions inside addValueEventListener in the right way

I'm trying to execute some code in my addValueEventListener based on conditions of values in database, but when data changes, listener execute conditions based on old data, and at the second try listener perform data which I want to use. however data change listener perform listenr(-1) data. To be more clear, if "disable" or "stop" child exist I don't want to execute the code, but after data are updated and these children not existing, conditions when I call AddMessage method not executing again, but it execute method when I call for the second time, it perform correctly till next update of the data where it start again same issue.
sendMessage.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View v) {
AddMessage();
}
});
private void AddMessage() {
nListener = RootRef.child("List Ref").child(messageReceiverID).child(messageSenderID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
if (!dataSnapshot.hasChild("disable") && !dataSnapshot.hasChild("stop")) {
HashMap <String,String> chatMessageMap = new HashMap <>();
chatMessageMap.put("from", messageSenderID);
chatMessageMap.put("type", "check");
chatMessageMap.put("content", messageText);
MessagesRef.child(messageReceiverID).push().setValue(chatMessageMap);
RootRef.child("List Ref").child(messageReceiverID).child(messageSenderID).removeEventListener(nListener);
} else {
RootRef.child("List Ref").child(messageReceiverID).child(messageSenderID).removeEventListener(nListener);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stoppedUser;
myDbref = FirebaseDatabase.getInstance().getReference().child("List Ref").child(<UID_OF_RECEIVER_OF_MESSAGE>);
myDbref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
try {
stoppedUser = dataSnapshot.child(<UID_OF_SENDER>).child("stop").getValue().toString();
//Now use if-else statement
if(<UID_OF_RECEIVER> == stoppedUser){
Toast.makeText(getApplicationContext(), "You are blocked.", Toast.LENGTH_LONG).show();
} else {
AddMessage();
}
}catch (Throwable e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Though you can get <UID_OF_SENDER> by using FirebaseUser currentUserUID = FirebaseAuth.getInstance().getCurrentUser();
Make sure you put the value of <UID_OF_RECEIVER> correctly and also correct the database path if needed.

Firebase query logic not working in android

I want to make a query that checks whether a certain name (President or Secretary) exists inside a database.
The structure of the database is as follows.
I have this code, but its not working. Is there something I'm doing wrong?
mDatabase = FirebaseDatabase.getInstance().getReference();
Query presidentquery = mDatabase.child("validate").child(uid).equalTo("President");
presidentquery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
Candidate p = dataSnapshot1.getValue(Candidate.class);
president.setEnabled(false);
president.setText("Voted Already");
}
}
else{
president.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Home.this, AllCandidates.class));
finish();
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
It seems you know the exact node you want to load, in which case you don't need an equalTo. Instead you can look up the node with:
Query presidentquery = mDatabase.child("validate").child(uid).child("President");
The rest of your code can stay the same.

Firebase Data Keep Looping

I am trying to update my mcustDelivery status, from "Accept" to "Enroute" in Firebase after user press enroute button.
but whenever, I press enroute button, the firebase change to "Enroute" and immediately changes back to "Accept".
This is my setOnClickListener for enroute button.
OrderStatus.Java
enroute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.child(key).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("mcustDeliveryStatus").setValue("Enroute");
enroute.setImageResource(R.drawable.greenenroute);
deliver.setImageResource(R.drawable.bluedeliver);
enroute.setMaxWidth(266);
enroute.setMaxHeight(150);
deliver.setMaxWidth(266);
deliver.setMaxHeight(150);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
});
this below code is where i get the the Accepted status on ViewNewOrder.java
accept.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDatabase.child(getKey()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
dataSnapshot.getRef().child("mcustDeliveryStatus").setValue("Accepted");
Intent orderStatus = new Intent(ViewOrderRequest.this, orderStatus.class);
startActivity(orderStatus);
Toast.makeText(getApplicationContext(),"notification sent to customers",Toast.LENGTH_LONG).show();
//start new activity show root map
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getApplicationContext(),"not updates",Toast.LENGTH_LONG).show();
}
});
}
});
It's simple you have used addValueEventListener for accepting the request you are changing the value in the same reference. So the addValueEventListener triggered up and again change the value to accept. For writing, data refer firebase docs for read and write
private DatabaseReference mDatabase;
mDatabase = FirebaseDatabase.getInstance().getReference();
mDatabase.child(getKey()).child("mcustDeliveryStatus").setValue("Accepted")
or simple fix change that addValueEventListener to addListenerForSingleValueEvent

Categories

Resources