How to save data in Firebase?

UPDATED: 14 September 2016
Firebase + Google

Prerequisite


Source code (Item.java)
public class Item {

    private Long id;
    private String name;
    private Double price;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }
}

Source code (FirebaseSaveObject.java)
package com.javaquery.google.firebase;

import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.javaquery.bean.Item;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.concurrent.CountDownLatch;

/**
 * Example of Firebase save.
 *
 * @author javaQuery
 * @date 7th September, 2016
 * @Github: https://github.com/javaquery/Examples
 */
public class FirebaseSaveObject {

    public static void main(String[] args) {
        Item item = new Item();
        item.setId(1L);
        item.setName("MotoG");
        item.setPrice(100.12);

        // save item objec to firebase.
        new FirebaseSaveObject().save(item);
    }

    private FirebaseDatabase firebaseDatabase;

    /**
     * initialize firebase.
     */
    private void initFirebase() {
        try {
            // .setDatabaseUrl("https://fir-66f50.firebaseio.com") - Firebase project url.

            // Firebase private key(Generated while creating service account) file path.
            // .setServiceAccount(new FileInputStream(new File("filepath")))
            FirebaseOptions firebaseOptions = new FirebaseOptions.Builder()
                    .setDatabaseUrl("https://fir-66f50.firebaseio.com")
                    .setServiceAccount(new FileInputStream(new File("filepath\30f95674f4d5.json")))
                    .build();

            FirebaseApp.initializeApp(firebaseOptions);
            firebaseDatabase = FirebaseDatabase.getInstance();
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * Save item object in Firebase.
     * @param item 
     */
    private void save(Item item) {
        if (item != null) {
            initFirebase();
            
            /* Get database root reference */
            DatabaseReference databaseReference = firebaseDatabase.getReference("/");
            
            /* Get existing child or will be created new child. */
            DatabaseReference childReference = databaseReference.child("item");

            /**
             * The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting.
             * So we'll wait(countDownLatch.await()) until firebase saves record. Then decrement `countDownLatch` value
             * using `countDownLatch.countDown()` and application will continues its execution.
             */
            CountDownLatch countDownLatch = new CountDownLatch(1);
            childReference.setValue(item, new DatabaseReference.CompletionListener() {

                @Override
                public void onComplete(DatabaseError de, DatabaseReference dr) {
                    System.out.println("Record saved!");
                    // decrement countDownLatch value and application will be continues its execution.
                    countDownLatch.countDown();
                }
            });
            try {
                //wait for firebase to saves record.
                countDownLatch.await();
            } catch (InterruptedException ex) {
                ex.printStackTrace();
            }
        }
    }
}

Output
Record saved!
Check Database in Firebase console.

Non-Android Runtimes
https://www.firebase.com/docs/android/guide/saving-data.html#section-other-runtimes
The Firebase Java client does not require the Android Runtime and can be used in any Java Runtime, including server-side Java processes or Java desktop applications.

The Firebase Java client uses daemon threads, meaning it will not prevent a process from exiting. When running on a non-Android runtime we may need to take extra steps to make sure that data is written to the server before our process exits. We can attach a CompletionListener to write operations and use a Semaphore or CountDownLatch object to prevent the process from exiting, as shown in the example below.

Reference
If you have collection of data to save in Firebase then you might me interested in reading Firebase.push(). - Example of Firebase.push() in Java.

0 comments :