Linked list is empty after fetching data from Firebase realtime database

假装没事ソ 提交于 2019-12-10 11:49:30

问题


I fetch these department names (CSE, EEE) from firebase to a linked list and set that linked list as items of my drop down. When I click the drop down it shows the items but when I select an item it does not appears as selected item on the drop down bar.

If I use array then the drop down works fine. But the problem is when I try to convert the linked list into an array using String[] arr = linkedlist.toArray(new String[linkedlist.size()] it shows that the linked list is empty.


Normal drop down:

After clicking drop down:

After selecting an item:

Java Class:

public class RegistrationActivity extends AppCompatActivity {

    private static final String TAG = null;
    private Spinner sp1, sp2, sp3;
    private Button next;

    LinkedList<String> deptlist = new LinkedList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registration);

        sp1 = (Spinner) findViewById(R.id.spinner_dept);
        sp2 = (Spinner) findViewById(R.id.spinner_int);
        sp3 = (Spinner) findViewById(R.id.spinner_sec);
        next = (Button) findViewById(R.id.next);

        DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference().child("Intake-Sec");
        ValueEventListener valueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                for(DataSnapshot ds : dataSnapshot.getChildren()) {
                    String key = ds.getKey();
                    deptlist.add(key);
                    Log.d(TAG, key);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage());
            }
        };
        rootRef.addListenerForSingleValueEvent(valueEventListener);

        /*does not work. deptlist.size() returns 0 item

        String[] deptarr = deptlist.toArray(new String[deptlist.size()]);

        */

        ArrayAdapter ar = new ArrayAdapter(this, android.R.layout.simple_spinner_item,deptlist);
        ar.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        sp1.setAdapter(ar);

    }
}

来源:https://stackoverflow.com/questions/55049334/linked-list-is-empty-after-fetching-data-from-firebase-realtime-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!