Как вы делаете Arraylist из базы данных Firebase для заполнения в ArrayAdapter? - PullRequest
0 голосов
/ 27 июня 2018

человекТипы из базы данных:

{ 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} }

Мне нужно выбрать объект из personTypes (который извлекается из базы данных), который отображается в spinneradapter;

Из 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);
}

У меня проблема с отображением mPersonTypeList в spinneradapter, это оригинальный код:

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.
}

}

UPDATE: Я попытался сделать код ниже (без специального адаптера) и по-прежнему выдает ошибку

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 голосов
/ 28 июня 2018

Это работает для меня.

Это также связано с предположением, что вы правильно реализовали Список, в котором есть строковые элементы.

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); if, вы можете сделать spinnerList.add(post.getTitle()); Это добавит заголовок сообщения в список. Надеюсь, это имеет смысл ....

...