Setting Singleton Property Value in Firebase Listener

Setting Singleton property value in Firebase Listener

Firebase loads and synchronizes data asynchronously. So your loadModelWithDataFromFirebase() doesn't wait for the loading to finish, it just starts loading the data from the database. By the time your loadModelWithDataFromFirebase() function returns, the loading hasn't finished yet.

You can easily test this for yourself with some well-placed log statements:

public void loadModelWithDataFromFirebase(){
Firebase db = new Firebase(//url);
Firebase bookmarksRef = fb.child(//access correct child);

Log.v("Async101", "Start loading bookmarks");
final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
bookmarksRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.v("Async101", "Done loading bookmarks");
//getting all properties from firebase...
Bookmark bookmark = new Bookmark(//properties here);
loadedBookmarks.add(bookmark);
}

@Override
public void onCancelled(FirebaseError error) { throw error.toException(); }
});
Log.v("Async101", "Returning loaded bookmarks");
setBookmarks(loadedBookmarks);
}

Contrary to what you likely expect, the order of the log statements will be:

Start loading bookmarks
Returning loaded bookmarks
Done loading bookmarks

You have two choice for dealing with the asynchronous nature of this loading:

  1. squash the asynchronous bug (usually accompanied by muttering of phrases like: "it was a mistake, these people don't know what they're doing")

  2. embrace the asynchronous beast (usually accompanied by quite some hours of cursing, but after a while by peace and better behaved applications)

Take the blue pill - make the asynchronous call behave synchronously

If you feel like picking the first option, a well placed synchronization primitive will do the trick:

public void loadModelWithDataFromFirebase() throws InterruptedException {
Firebase db = new Firebase(//url);
Firebase bookmarksRef = fb.child(//access correct child);

Semaphore semaphore = new Semaphore(0);

final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
bookmarksRef.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Bookmark bookmark = new Bookmark(//properties here);
loadedBookmarks.add(bookmark);
semaphore.release();
}

@Override
public void onCancelled(FirebaseError error) { throw error.toException(); }
});
semaphore.acquire();
setBookmarks(loadedBookmarks);
}

Update (20160303): when I just tested this on Android, it blocked my app. It works on a regular JVM fine, but Android is more finicky when it comes to threading. Feel free to try and make it work... or

Take the red pill - deal with the asynchronous nature of data synchronization in Firebase

If you instead choose to embrace asynchronous programming, you should rethink your application's logic.

You currently have "First load the bookmarks. Then load the sample data. And then load even more."

With an asynchronous loading model, you should think like "Whenever the bookmarks have loaded, I want to load the sample data. Whenever the sample data has loaded, I want to load even more."

The bonus of thinking this way is that it also works when the data may be constantly changing and thus synchronized multiple times: "Whenever the bookmarks change, I want to also load the sample data. Whenever the sample data changes, I want to load even more."

In code, this leads to nested calls or event chains:

public void synchronizeBookmarks(){
Firebase db = new Firebase(//url);
Firebase bookmarksRef = fb.child(//access correct child);

final ArrayList<Bookmark> loadedBookmarks = new ArrayList<Bookmark>();
bookmarksRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
Bookmark bookmark = new Bookmark(//properties here);
loadedBookmarks.add(bookmark);
setBookmarks(loadedBookmarks);
loadSampleData();
}

@Override
public void onCancelled(FirebaseError error) { throw error.toException(); }
});
}

In the above code we don't just wait for a single value event, we instead deal with all of them. This means that whenever the bookmarks are changed, the onDataChange is executed and we (re)load the sample data (or whatever other action fits your application's needs).

To make the code more reusable, you may want to define your own callback interface, instead of calling the precise code in onDataChange. Have a look at this answer for a good example of that.

Is there a way to save data from a firebase Realtime Database without getting a null variable?

When you add a Listener to Query, you don't immediately get the data back in the array list. The meaning of what you have written is:

  • Make a query on Realtime Database,
  • When a data change event is received (or when the listener is added) call the onDataChanged(DataSnapshot) function

So what you need is a callback when you get the data in the future.

That means you won't be getting the data immediately where you did:

itemsList = itemsArray; // itemsArray is null

Instead do something like:

class MyActivity extends AppCompatActivity {
private final List<Item> itemsArrayList = new ArrayList<>();

@Override

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shop);

shopRef = FirebaseDatabase.getInstance().getReference();

Query query = shopRef.child("shop");

query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
List<Item> snapshotItems = new ArrayList<>();
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Item item = new Item();
item.setLogo(snapshot.child("Logo").getValue().toString());
item.setName(snapshot.child("Name").getValue().toString());
item.setDescription(snapshot.child("Description").getValue().toString());

snapshotItems.add(item);
}
// Calling this function will add the data back to the list
MyActivity.this.onItemsObtained(snapshotItems);
}

@Override
public void onCancelled(@NonNull DatabaseError error) {
}
});
}

public void onItemsObtained(List<Item> items) {
itemsArrayList.clear(); // To remove old Data
itemsArrayList.addAll(items);

// Continue your own logic...
}

}


Related Topics



Leave a reply



Submit