Reputation: 91
I have a class that extends Fragment
and that contains a query to Firebase in its onCreateView
method. After analyzing the program with the debugger, I realized that this query isn't executing until after the view has been returned.
The query returns information that will be loaded into a recyclerview. I also have created an adapter for the data itself. The code does not produce any errors but it's not functioning the way it should. Ideally, the query should execute first that way I can show the data on this recyclerview. Any idea why this is happening?
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable final ViewGroup container, @Nullable Bundle savedInstanceState)
{
final View view=inflater.inflate(R.layout.frag_events, container, false);
eventIds =new ArrayList<String>();
//executes after view has been returned
ValueEventListener eventIdValListener=new ValueEventListener()
{
@Override
public void onDataChange(@NonNull DataSnapshot snapshot)
{
eventIds.clear();
if(snapshot.exists())
{
for (DataSnapshot e : snapshot.getChildren())
{
String event = e.getValue(String.class);
eventIds.add(event);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError error)
{
}
};
//returns data for current user
Query query=FirebaseDbSingleton.getInstance().dbRef.child("User").child(FirebaseDbSingleton.getInstance().user.getUid().toString()).child("events");
query.addValueEventListener(eventIdValListener);
return view;
}
I left out some lines for the recycler and adapter just to keep this code short. I have a feeling this might be due to the innerclass in eventIdValListener
but I am not entirely sure.
Upvotes: 0
Views: 93
Reputation: 317712
All Firebase APIs that query the database are asynchronous and complete some time later after they're invoked. You can't realistically make it finish before onCreateView
returns - it must return immediately with a View instance.
Since you don't know how long it will take for the query to complete, and there is no guarantee how long, you will need to add logic to show something before the query is complete (such as a waiting indicator). This is standard for any app that performs network or database operations.
Upvotes: 1