装有Firebase数据库的Android微调框未选择该项

时间:2018-08-04 14:50:19

标签: java android firebase firebase-realtime-database android-spinner

我通过从Firebase数据库填充final List<String> categories = new ArrayList<>();在Android微调器中动态添加了项目。 项目已成功加载,如屏幕截图所示:

screenshot of items loaded in spinner

但是,微调器没有将第一项显示为提示(下面的快照),也没有选择该项。

screenshot of spinner before selection

我添加了以下代码以供参考:

activity_select_category.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="100dp"
    tools:context=".SelectCategoryActivity">

    <Spinner
        android:id="@+id/spinner_select_category"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

</android.support.constraint.ConstraintLayout>

SelectCategoryActivity.java

package com.example.digicube;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;

import java.util.ArrayList;
import java.util.List;

public class SelectCategoryActivity extends AppCompatActivity {

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

        Spinner selectCategorySpinner = findViewById(R.id.spinner_select_category);
        final List<String> categories = new ArrayList<>();
        DatabaseReference mCategoriesDatabaseReference = FirebaseDatabase.getInstance().getReference().child("categories");
        mCategoriesDatabaseReference.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
                Category category = dataSnapshot.getValue(Category.class);
                category.setKey(dataSnapshot.getKey());
                categories.add(0, category.getCategoryName());
            }
            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
        ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(SelectCategoryActivity.this, android.R.layout.simple_spinner_item, categories){
            @Override
            public boolean isEnabled(int position) {
                return position != 0;
            }

            @Override
            public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
                View view =  super.getDropDownView(position, convertView, parent);
                TextView hintView = (TextView) view;
                if (position == 0) {
                    hintView.setText(R.string.select_category_spinner);
                }
                return view;
            }
        };
        categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        selectCategorySpinner.setAdapter(categoryAdapter);
        selectCategorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long l) {
                if (position > 0) {
                    String item = parent.getItemAtPosition(position).toString();
                    Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
                }
            }

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

            }
        });
    }
}

1 个答案:

答案 0 :(得分:0)

您无法将从数据库获得的categories列表传递到回调之外的适配器,因为它始终为空。这就是为什么您的屏幕空白。请注意,onChildAdded()方法具有异步行为。

此问题的快速解决方案是将适配器的声明移至onDataChange()方法内,然后仅通知适配器。有关更多详细信息,建议您从此 post 中查看我的答案,其中我解释了如何在回调之外获取对象。您也可以查看此 video 以获得更好的理解。