Reputation: 25
I am trying to get a list of String from Firebase and after all the data is retrieved only then I will update my UI. Currently I am using the following code in a fragment class to achieve this.
taskList = new ArrayList<>();
mDatabase.child("users").child(mUserId).child("items").orderByChild("id").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot){
for(DataSnapshot childSnapshot : dataSnapshot.getChildren() ){
taskList.add(new Pair<>((long) childSnapshot.child("id").getValue(),(String) childSnapshot.child("title").getValue()));
}
//update UI
setupListRecyclerView();
}
@Override
public void onCancelled(DatabaseError firebaseError){
throw firebaseError.toException();
}
});
The setupListRecyclerView works if placed outside of the valueEventListener, but if placed in it I get "Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference"
error. However, if I put it outside of the listener it will update the UI before the data from Firebase is retrieved so I'm lost here.
Here is how setupListRecyclerView looks like:
private void setupListRecyclerView() {
mDragListView.setLayoutManager(new LinearLayoutManager(getContext()));
ItemAdapter listAdapter = new ItemAdapter(taskList, R.layout.list_item, R.id.image, false);
mDragListView.setAdapter(listAdapter, true);
mDragListView.setCanDragHorizontally(false);
mDragListView.setCustomDragItem(new MyDragItem(getContext(), R.layout.list_item));
}
private static class MyDragItem extends DragItem {
MyDragItem(Context context, int layoutId) {
super(context, layoutId);
}
@Override
public void onBindDragView(View clickedView, View dragView) {
CharSequence text = ((TextView) clickedView.findViewById(R.id.text)).getText();
((TextView) dragView.findViewById(R.id.text)).setText(text);
dragView.findViewById(R.id.item_layout).setBackgroundColor(dragView.getResources().getColor(R.color.list_item_background));
}
}
Upvotes: 0
Views: 861
Reputation: 5339
if you put it outside declare ItemAdapter listAdapter
as globale variable and add listAdapter.notifyDataSetChanged()
to onDataChange()
method or if you put in inside try
mDragListView.setLayoutManager(new LinearLayoutManager(getActivity()));
Upvotes: 1