Cleaven
Cleaven

Reputation: 974

Fragment OnResume not updating spinner

I have a fragment with a spinner in it but when I select the tab to display that fragment it does not update the spinner it contains. So I'm assuming its the onResume that does not trigger?

I'm trying to update the spinner whenever the fragment is selected.

Fragment code:

public class AddFacultyFragment extends Fragment {
@BindView(R.id.spinner_search_UniFac)
Spinner spinner_search_UniFac;
ArrayList<University> listUni = new ArrayList<>();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_add_faculty,
            container,
            false);
    ButterKnife.bind(this, view);
    updateSpinner();
    return view;
}
@Override
public void onResume() {
    updateSpinner();
    super.onResume();
}
private void updateSpinner() {
    FirebaseFirestore db = FirebaseFirestore.getInstance();
    final CollectionReference[] colRef = {db.collection("university")};
    colRef[0].get().addOnCompleteListener((OnCompleteListener<QuerySnapshot>) task -> {
        if (task.isSuccessful()) {
            listUni.clear();
            for(DocumentSnapshot a : task.getResult()){
                University u = new University();
                u.setID(a.getId());
                u.setDesc(a.get("Desc").toString());
                listUni.add(u);
            }
        }
    });
    ArrayAdapter<University> spinnerArrayAdapter = new ArrayAdapter<>
            (getContext(), android.R.layout.simple_spinner_item,
                    listUni);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout
            .simple_spinner_dropdown_item);
    spinner_search_UniFac.setAdapter(spinnerArrayAdapter);
}
public AddFacultyFragment() {
    // Required empty public constructor
}
}

It might be worthwhile to mention this fragment is adjacent to the one updating the firestore collection which the spinner is pulling from.

Upvotes: 0

Views: 97

Answers (1)

Steve Bergamini
Steve Bergamini

Reputation: 14600

Try moving the code that assigns the adapter to the spinner out of the updateSpinner method so that you're only initializing the spinner with the adapter 1 time. Keep a reference to the adapter in your class - e.g. mSpinnerArrayAdapter

Then, in the updateSpinner method, once you update the adapter's data, make sure to call mSpinnerArrayAdapter.notifyDataSetChanged() on the adapter.

Upvotes: 1

Related Questions