简体   繁体   中英

How do I get a list from my ViewModel to display in my spinner and be selectable?

Currently, my spinner can get the list of instructors and accurately displays it in the spinner drop down menu, but the spinner has no default value and even after selecting a value in the drop down menu it stays blank. Trying to get the value in onItemSelected reveals that selecting any value in the drop down still returns null. The thing that is confusing me is that my custom adapter can clearly see that the list is properly saved outside the ViewModel, otherwise the spinner dropdown wouldn't show the correct values at all, but the println just below the adapter declaration always returns the size of the list as 0.

Fixes I've tried ~

Changed sizing of the spinner and it's contents

Changed the color of the text

Created a custom spinner_item.xml

<?xml version="1.0" encoding="utf-8"?>

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:gravity="start"
    android:textColor="#000000"
    android:padding="10dp"
    />
termViewModel = new ViewModelProvider(this).get(TermViewModel.class);

        List<Entities.Instructor> allInstructor = new ArrayList<>();
        termViewModel.getAllInstructor().observe(getViewLifecycleOwner(), instructors ->{
            allInstructor.addAll(instructors);
            System.out.println("allInstructor size in the termViewModel is: " + allInstructor.size());
        });
        ArrayAdapter<Entities.Instructor> adapter = new ArrayAdapter<>(getActivity(), R.layout.spinner_item,
                allInstructor);
        System.out.println("outside of termViewModel: " + allInstructor.size());
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        instructorSpinner.setAdapter(adapter);
        adapter.notifyDataSetChanged();


        instructorSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                spinnerText = instructorSpinner.getSelectedItem().toString();
                System.out.println(spinnerText);
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

SOLVED I've moved all of the spinner and adapter related code between the {} after termViewModel.getAllInstructor() and now it works, but I swear it should be letting me copy a list from my ViewModel and assign it to a list in my onCreateView() method. If I'm missing something obvious please point it out 😅

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM