0

I have set up a Firebase database that has 2 nodes. One node is called "ingredients" and the other is called "orders". I set up the nodes manually by using a JSON file and I just entered 1 entry in the node "orders" manually. You can see a screenshot of the structure of the database: enter image description here

Now I would like to add further entries in the table "orders" (so basically I would like to add a further row).

In my Android application I use the following code:

// in the class definition of the Fragment
public DatabaseReference firebase_DB; 
...
 // in the oneCreate Method of the Fragment
firebase_DB = FirebaseDatabase.getInstance().getReference("orders");
...
// when clicking on a button in the Fragment which calls the onClick method
String id =  firebase_DB.push().getKey();
DB_Object_Test currentOrder= new DB_Object_Test("testInfo_2", "testName", 2);
firebase_DB.child(id).setValue(currentOrder);

So basically the code runs without an error and the firebase_DB.child(id).setValue(currentOrder); is called. However, nothing changes in the Firebase console. I can't see any new entry there. The firebase database is properly connected to the app (at least Android Studio says that) and I have not specified any rules that would prohibit writing something on the database. The same data is stored without any problems in an SQLite database.

Can any one of you think about a possible reason for this problem? Why is the new row not written into the firebase database? I'll appreciate every comment.

EDIT: Here is the adjusted code that writes to the firebase database (by using 3 different approaches) after clicking a "Order" Button in the Fragment.

public void onClick(View view) {

        if(view.getId() == R.id.ordering_button) {
            

/*          Firebase approach 1


            final FirebaseDatabase database = FirebaseDatabase.getInstance();
            DatabaseReference ref = database.getReference("");
            DatabaseReference usersRef = ref.child("orders");
            Map<String, DB_Object_Test> order = new HashMap<>();
            order.put("order_2", new DB_Object_Test("1", "testInfo_2", "testName", "2"));
            usersRef.setValue(order);
 */


            /*
            Firebase approach 3 (by Alex)
             */

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
        DatabaseReference ordersRef = rootRef.child("orders");
        Map<String, Object> order = new HashMap<>();
        order.put("info", "No additional information");
        order.put("name", "Another Test Order");
        order.put("table", "15");
        Log.e("LogTag", "Before write firebase");
        ordersRef.child("order_2").setValue(order).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
    public void onComplete(@NonNull Task<Void> task) {
        Log.e("LogTag", "During on Complete firebase");
        if (task.isSuccessful()) {
        Log.e("dbTAG", "Data successfully written.");
        } else {
        Log.e("dbTAG", task.getException().getMessage());
        }
        }
        });
        Log.e("LogTag", "Afer write firebase");

            
            
            /* Firebase approach 2
            DatabaseReference firebase_DB = FirebaseDatabase.getInstance().getReference("orders");
            String id =  firebase_DB.push().getKey();
            DB_Object_Test currentOrder= new DB_Object_Test(id, "testInfo_2", "testName", "2");
            firebase_DB.child(id).setValue(currentOrder);
            //Option 2*
            //firebase_DB.setValue(currentOrder);
            Log.e("LogTag", "firebase_DB.child(id): " + firebase_DB.child(id));
            */

        Navigation.findNavController(getView()).navigate(...);

        } 
}
VanessaF
  • 515
  • 11
  • 36
  • Probably `firebase_DB = FirebaseDatabase.getInstance().getReference().getChild("orders");` could work – Zain Sep 24 '21 at 21:49

1 Answers1

2

To be able to add another object under your "orders" node, please use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ordersRef = rootRef.child("orders");
Map<String, Object> order = new HashMap<>();
order.put("info", "No additional information");
order.put("name", "Another Test Order");
order.put("table", "15");
ordersRef.child("order_2").setValue(order).addOnCompleteListener(new OnCompleteListener<Void>() {
    @Override
    public void onComplete(@NonNull Task<Void> task) {
        if (task.isSuccessful()) {
            Log.d("TAG", "Data successfully written.");
        } else {
            Log.d("TAG", task.getException().getMessage());
        }
    }
});

This code will work only if you set the proper security rules in your Firebase console:

{
  "rules": {
      ".read": true,
      ".write": true
  }
}

Remember to keep these rules only for testing purposes. Besides that, you can also attach a complete listener to see if something goes wrong.

If you want to use DatabaseReference#push() method, then you should use the following line of code:

ordersRef.push().setValue(order);

Edit:

According to your last comment:

Database location: Belgium (europe-west1)

You should check my answer from the following post and add the correct URL to the getInstance() method:

In your particular case it should be:

DatabaseReference rootRef = FirebaseDatabase.getInstance("https://drink-server-db-default-rtdb.europe-west1.firebasedatabase.app").getReference();
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/237516/discussion-on-answer-by-alex-mamo-data-is-not-written-into-the-firebase-database). – Samuel Liew Sep 26 '21 at 09:31
  • @Alex: Hey Alex it's me again. I found out that with your suggested answer I can't modify any variables inside your suggested code. But I need to do that. Any ideas how I can modify boolean variables in your suggested code? I'll appreciate any further comment from you. I asked a separate question here https://stackoverflow.com/questions/69360358/how-to-modify-an-external-boolean-value-in-a-newly-created-listener-in-java-for – VanessaF Oct 17 '21 at 07:56
  • @VanessaF Hey Vanessa. I'm not sure I understand what you mean. But please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Oct 17 '21 at 08:53
  • Thanks Alex for your comment. As mentioned in my last comment I have already asked a new question on StackOveflow about this issue that you can find here https://stackoverflow.com/questions/69360358/how-to-modify-an-external-boolean-value-in-a-newly-created-listener-in-java-for – VanessaF Oct 17 '21 at 09:11
  • 1
    @VanessaF Ok, I'll take a look and if I'll know the answer, I'll write to you. – Alex Mamo Oct 17 '21 at 09:13
  • @AlexMamo: Is there a way to write data into firebase without calling this asynchronously executed onComplete method? Due to the fact that the method is asychronously called some problems occur as you can't modify any external variables within the code. A solution would be to just store data in the firebase db by executing synchronous code which is not the case in your suggested example. Any idea whether this is possible or not? – VanessaF Oct 19 '21 at 18:00
  • No, there is not. All Firebase APIs are asynchronous. However, if you understand Kotlin, this article called [How to read data from Firebase Realtime Database using get()?](https://medium.com/firebase-tips-tricks/how-to-read-data-from-firebase-realtime-database-using-get-269ef3e179c5) might help. – Alex Mamo Oct 20 '21 at 05:42
  • Thanks Alex for your answer and effort. I really appreciate it. Actually the problem is not how to read data from Firebase. The problem is that in your suggested code I can't modify any external boolean variable as it will be executed asynchronously. But I would like to have a external boolean variable that indicates whether the writing into the firebase db was successfull nor not. If it was not successfull it should be tried again. For that purpose I wanted to use a loop with a boolean variable that indicates if the loop should stop or not. – VanessaF Oct 20 '21 at 16:42
  • Everything that is related to the Firebase APIs is asynchronous. Please also note, that you can have a global variable the way you want. You cannot force an asynchronous operation to be synchronous. Even if you could that, it wouldn't be a solution. – Alex Mamo Oct 20 '21 at 19:19
  • If you have a particular block of code that doesn't work the way you expect, please post a new question, here on StackOverflow, using its own [MCVE](https://stackoverflow.com/help/mcve), so I and other Firebase developers can help you. – Alex Mamo Oct 20 '21 at 19:20
  • @Thanks Alex for your answer. I have already posted a new question an I have given you the link to it twice. Here you can have it for the third time: https://stackoverflow.com/questions/69360358/how-to-modify-an-external-boolean-value-in-a-newly-created-listener-in-java-for?noredirect=1#comment123127837_69360358 – VanessaF Oct 21 '21 at 16:38