1

I am working on a MapActivity where I am getting supplier information from my database and storing it in Supplier object. I am calling two functions fetchSupplier() and FetchStationInfo() where first one fetch supplier info and stores into Object and second one uses it. So, the problem is when I run the fetchSupplier() alone the data gets fetched and stored in my object but, when I call both functions i.e FetchStationInfo() after fetchSupplier() it gives a null pointer exception in FetchStationInfo(). Here's how I am calling the functions:

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    fetchSupplier();
    fetchStationInfo();
}

Both of my functions:

private void fetchSupplier(){
    String uid = mAuth.getUid();
    mDatabase = FirebaseDatabase.getInstance().getReference()
            .child("SUPPLIERS").child(uid);

    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            supplier = dataSnapshot.getValue(Supplier.class);
            Log.i("USER FETCH COMPLETE ","["+supplier.getName()+"]");
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i("FETCHING USER [ERROR] ",databaseError.getMessage());
        }
    });
}

private void fetchStationInfo(){
    //Exception is here in this line where I am calling `getStation_id()`
    mDatabase = FirebaseDatabase.getInstance().getReference()
            .child("STATIONS").child(supplier.getStation_id());

    mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            station = dataSnapshot.getValue(Station.class);
            Log.i("STATION FETCH COMPLETE ","["+station.getName()+"]");
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
            Log.i("STATION FETCH [ERROR] ",databaseError.getMessage());
        }
    });
}

My objects are declared globally. Been working on it for hours but unable to fix it. My firebase structure: enter image description here

Hussam
  • 1,606
  • 9
  • 20
  • Please add your firebase structure too, so we can see if there is something going wrong with fetching the value from database – PradyumanDixit Nov 07 '18 at 15:29
  • @PradyumanDixit I don't think theres anything wrong with the structure but I just edited my answer. – Hussam Nov 07 '18 at 15:32
  • Just curious: Does any supplier have more than one "Station"? (From your data example your data structure looks pretty flat.) If each supplier does have only one station then there really is no reason to have the data separated into two tables. – Barns Nov 07 '18 at 15:48
  • @Barns It is like each supplier does have one station but each station will have multiple suppliers. So I am somehow using the concepts of reference keys and stuff here. Sorry if I am being stupid this is my first experience with a NoSql Database. Plus there's a lot to be added. – Hussam Nov 07 '18 at 15:56
  • Not at all! You are NOT being "stupid"! Coming from a Relational Database background moving to the concept of NoSQL is not easy! And my experience with NoSQL is quite limited. I just wanted to see if there was any potential advantage in combining the two "tables". Keep coding! Good Luck! – Barns Nov 07 '18 at 16:28
  • @Barns because I found this I thought why not share it with you. It explains why a firebase structure should be kept as flat as possible and not to be nested. https://firebase.google.com/docs/database/rest/structure-data – Hussam Nov 07 '18 at 20:59

1 Answers1

2

The problem is that fetchStationInfo() is trying to fetch supplier from fetchSupplier() .

Remember that Firebase calls are asynchronous and you are trying to fetch suppliers while it's being fetched.

So, if you do this

public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
    fetchSupplier();
    fetchStationInfo();
}

The two methods will fire and since they are asynchronous you don't know which one ends first, so, if fetchStationInfo ends first it will have suppliers with a null value since fetchSupplier did not finished fetching the result yet.

In order to fix this, you can make a simple interface after fetchSuppliers() that will notify when the job is done, after that job is done , in the callback of that interface you run fetchStationInfo() , in this order you will always have the suppliers info before trying to fetch it in fetchStationInfo().

This is know as a Race Condition.

Please visit these links in order to understand better how it works:

How to return dataSnapshot value as a result of a method?

android - Firebase return value from datasnapshot Why?

halfer
  • 19,824
  • 17
  • 99
  • 186
Gastón Saillén
  • 12,319
  • 5
  • 67
  • 77