如何从Firebase数据库制作arraylist以便在ArrayAdapter中填充?

时间:2018-06-27 15:21:34

标签: android firebase arraylist firebase-realtime-database android-arrayadapter

数据库中的

personTypes:

{ key = personTypes, value = {RESIDENT_HOMEOWNER=Resident Homeowner, RESIDENT_VISITOR=Resident Visitor, RESIDENT_RELATIVE=Resident Relative, RESIDENT_TENANT=Resident Tenant, HELPER_OUT=Helper Stay-out, PERSONNEL_1=Personnel 1, MAINTENANCE=Maintenance, PERSONNEL_2=Personnel 2, DRIVER_IN=Driver Stay-in, HELPER_IN=Helper Stay-in, PERSONNEL_3=Personnel 3, CONSTRUCTION=Construction Worker, PERSONNEL_4=Personnel 4, SECURITY=Security, RESIDENT_CHILD=Resident Child, ADMIN=Admin, DRIVER_OUT=Driver Stay-out} }

我需要从spinneradapter中显示的personTypes(从数据库中获取)中选择对象;

从DetailPresenter.java

    private MutableLiveData<List<String>> mPersonTypes = new MutableLiveData<>();
    public MutableLiveData<List<String>> observerPersonTypes() {
    return mPersonTypes;
}

private void setupPersonType() {
    List<String> personTypes = new ArrayList<>();
    for(String personType : personAccessor.getPersonTypes()) {
        personTypes.add(personAccessor.getPersonCategoryDisplay(personType));
    }
    mPersonTypes.postValue(personTypes);
}

我对在spinneradapter中显示mPersonTypeList有问题,这是原始代码:

DetailsActivity.java

private static final String PERSON_TYPE_PROMPT = "Select Person Type";
private DetailPresenter mPresenter;
private ArrayAdapter<String> mPersonTypeAdapter;
List<String> mPersonTypeList = new ArrayList<>();

mPresenter.observerPersonTypes().observe(this, personTypes -> {
        mPersonTypeAdapter = new ArrayAdapter<>(this, R.layout.spinner_item_textview);
        mPersonTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        mPersonTypeList = personTypes;
        mPersonTypeAdapter.addAll(mPersonTypeList);
        mSpinnerPersonType.setAdapter(new NothingSelectedSpinnerAdapter(mPersonTypeAdapter,
                R.layout.spinner_row_nothing_selected, PERSON_TYPE_PROMPT, this));
        mSpinnerPersonType.setOnItemSelectedListener(mSpinnerPersonTypeOnItemSelectedListener);
    });

当我调试时显示{ArrayList} size = 17;以及mPersonTypeList,但在spinneradapter中显示时出错。

然后我尝试制作mPersonTypeList,如下所示:

mPersonTypeList = Arrays.asList("DRIVER_IN", "DRIVER_OUT", "HELPER_IN","HELPER_OUT","CONSTRUCTION","ADMIN"
    ,"MAINTENANCE","SECURITY","RESIDENT_CHILD","RESIDENT_HOMEOWNER","RESIDENT_RELATIVE","RESIDENT_TENANT","RESIDENT_VISITOR");

成功显示mPersonTypeList {Arrays $ ArrayList} size = 13,我认为将mPersonTypeList设置为Arrays.asList是显示personTypes的解决方案,但是如何转换呢?

NothingSelectedSpinnerAdapter.java

public class NothingSelectedSpinnerAdapter implements SpinnerAdapter, ListAdapter {

protected static final int EXTRA = 1;
protected SpinnerAdapter adapter;
protected Context context;
protected int nothingSelectedLayout;
protected String nothingSelectedPrompt;
protected int nothingSelectedDropdownLayout;
protected LayoutInflater layoutInflater;

/**
 * Use this constructor to have NO 'Select One...' item, instead use
 * the standard prompt or nothing at all.
 * @param spinnerAdapter wrapped Adapter.
 * @param nothingSelectedLayout layout for nothing selected, perhaps
 * you want text grayed out like a prompt...
 * @param context
 */
public NothingSelectedSpinnerAdapter(
        SpinnerAdapter spinnerAdapter,
        int nothingSelectedLayout, String nothingSelectedPrompt, Context context) {

    this(spinnerAdapter, nothingSelectedLayout, nothingSelectedPrompt, -1, context);
}

/**
 * Use this constructor to Define your 'Select One...' layout as the first
 * row in the returned choices.
 * If you do this, you probably don't want a prompt on your spinner or it'll
 * have two 'Select' rows.
 * @param spinnerAdapter wrapped Adapter. Should probably return false for isEnabled(0)
 * @param nothingSelectedLayout layout for nothing selected, perhaps you want
 * text grayed out like a prompt...
 * @param nothingSelectedDropdownLayout layout for your 'Select an Item...' in
 * the dropdown.
 * @param context
 */
public NothingSelectedSpinnerAdapter(SpinnerAdapter spinnerAdapter,
                                     int nothingSelectedLayout, String nothingSelectedPrompt,
                                     int nothingSelectedDropdownLayout, Context context) {

    this.adapter = spinnerAdapter;
    this.context = context;
    this.nothingSelectedLayout = nothingSelectedLayout;
    this.nothingSelectedPrompt = nothingSelectedPrompt;
    this.nothingSelectedDropdownLayout = nothingSelectedDropdownLayout;
    layoutInflater = LayoutInflater.from(context);
}

@Override
public final View getView(int position, View convertView, ViewGroup parent) {
    // This provides the View for the Selected Item in the Spinner, not
    // the dropdown (unless dropdownView is not set).
    if (position == 0) {
        return getNothingSelectedView(parent);
    }
    return adapter.getView(position - EXTRA, null, parent); // Could re-use
    // the convertView if possible.
}

/**
 * View to show in Spinner with Nothing Selected
 * Override this to do something dynamic... e.g. "37 Options Found"
 * @param parent
 * @return
 */
protected View getNothingSelectedView(ViewGroup parent) {
    TextView textView = (TextView)layoutInflater.inflate(nothingSelectedLayout, parent, false);
    if(nothingSelectedPrompt !=null && nothingSelectedPrompt.length()>0) {
        textView.setText(nothingSelectedPrompt);
    }
    return textView;
}

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
    // Android BUG! http://code.google.com/p/android/issues/detail?id=17128 -
    // Spinner does not support multiple view types
    if (position == 0) {
        return nothingSelectedDropdownLayout == -1 ?
                new View(context) :
                getNothingSelectedDropdownView(parent);
    }

    // Could re-use the convertView if possible, use setTag...
    return adapter.getDropDownView(position - EXTRA, null, parent);
}

/**
 * Override this to do something dynamic... For example, "Pick your favorite
 * of these 37".
 * @param parent
 * @return
 */
protected View getNothingSelectedDropdownView(ViewGroup parent) {
    return layoutInflater.inflate(nothingSelectedDropdownLayout, parent, false);
}

@Override
public int getCount() {
    int count = adapter.getCount();
    return count == 0 ? 0 : count + EXTRA;
}

@Override
public Object getItem(int position) {
    return position == 0 ? null : adapter.getItem(position - EXTRA);
}

@Override
public int getItemViewType(int position) {
    return 0;
}

@Override
public int getViewTypeCount() {
    return 1;
}

@Override
public long getItemId(int position) {
    return position >= EXTRA ? adapter.getItemId(position - EXTRA) : position - EXTRA;
}

@Override
public boolean hasStableIds() {
    return adapter.hasStableIds();
}

@Override
public boolean isEmpty() {
    return adapter.isEmpty();
}

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    adapter.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    adapter.unregisterDataSetObserver(observer);
}

@Override
public boolean areAllItemsEnabled() {
    return false;
}

@Override
public boolean isEnabled(int position) {
    return position == 0 ? false : true; // Don't allow the 'nothing selected'
    // item to be picked.
}

}

更新: 我尝试执行以下代码(没有自定义适配器),但仍然给我错误

mPresenter.observerPersonTypes().observe(this, personTypes -> {

        mPersonTypeList.addAll(personTypes);
        mPersonTypeAdapter = new ArrayAdapter<>(this, R.layout.spinner_item_textview, mPersonTypeList);
        mPersonTypeAdapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
        mSpinnerPersonType.setAdapter(mPersonTypeAdapter);
        mSpinnerPersonType.setOnItemSelectedListener(mSpinnerPersonTypeOnItemSelectedListener);
    });

1 个答案:

答案 0 :(得分:0)

这对我有用。

这也是假设您已经正确实现了其中包含String项的List。

public class MainActivity extends AppCompatActivity {

    Spinner spinner;
    List<String> spinnerList;

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

        spinner = findViewById(R.id.spinner);
        spinnerList = new ArrayList<>();

        //For you, you may have a method that gets the information from Firebase. 
        //Either way, you need to make sure your list has items in it.    

        spinnerList.add("test 1");
        spinnerList.add("test 2");
        spinnerList.add("test 3");
        spinnerList.add("test 4");
        spinnerList.add("test 5");

        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
                (this, android.R.layout.simple_spinner_item, spinnerList);

        spinner.setAdapter(spinnerArrayAdapter);


    }
}

这是我的结果。

您将不得不对其进行样式设置...但这将使您入门。 enter image description here

来自Firebase文档。

public static class Post {

  public String author;
  public String title;

  public Post(String author, String title) {
    // ...
  }

}

// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-data/fireblog/posts");

// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot dataSnapshot) {
    Post post = dataSnapshot.getValue(Post.class);
    System.out.println(post);
  }

  @Override
  public void onCancelled(DatabaseError databaseError) {
    System.out.println("The read failed: " + databaseError.getCode());
  }
});

如果在System.out.println(post);处,您可以进行spinnerList.add(post.getTitle());,这会将帖子标题添加到列表中。希望这是有道理的。。。