1

personTypes from database:

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

I need to select object from personTypes (which is fetch from database) that is shown in spinneradapter;

From 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);
}

I have a problem about displaying mPersonTypeList in the spinneradapter, this is the original code:

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

Which when i debug shows {ArrayList} size =17; as well as mPersonTypeList but It errors in displaying in the spinneradapter.

then i tried making the mPersonTypeList as shown below:

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");

which succeeds in displaying mPersonTypeList {Arrays$ArrayList} size=13, I think that making mPersonTypeList to Arrays.asList is the solution to display the personTypes but how do you convert it?

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: I tried doing the code below (without custom adapter) and still gives me error

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);
    });
Ina Yano
  • 75
  • 2
  • 10
  • you can use an adapter and set the values from the list into that adapter...https://stackoverflow.com/questions/47690279/how-to-set-the-value-and-text-in-a-spinner-from-a-string-list – letsCode Jun 27 '18 at 15:32
  • @DroiDev ive already done that which is the `mSpinnerPersonType.setAdapter(new NothingSelectedSpinnerAdapter(mPersonTypeAdapter, R.layout.spinner_row_nothing_selected, PERSON_TYPE_PROMPT, this));` – Ina Yano Jun 27 '18 at 15:47
  • whtas PERSON_TYPE_PROMPT? is this a final? – letsCode Jun 27 '18 at 15:52
  • what is NothingSelectedSpinnerAdapter... waht does that take in? your adapter is probably wrong. you dont need a custom adapter (for the most part). – letsCode Jun 27 '18 at 15:53
  • see the updated edits above @DroiDev. – Ina Yano Jun 27 '18 at 15:56
  • yeah.. without really seeing the entire picture, pretty sure your adapter is wrong. when i handle adapters, lets say for listviews, it takes in a List<> and that list is what populates my listview. you can take your logic to verify the spinner information outside of the adapter.... your adapter does not take in a list of objects (or strings) ... i dont see that in there in the constructor. – letsCode Jun 27 '18 at 16:01
  • @DroiDev but when i tried doing `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");` it displays the list in my adapter – Ina Yano Jun 27 '18 at 16:12
  • right. I believe (and i could be wrong without looking at the documentation) is the adapters takes an Array[] and not a List. If you wish to use an ADAPTER, you have to ADAPT a List<>. look up adapter examples for this case. – letsCode Jun 27 '18 at 16:14
  • check this out https://stackoverflow.com/a/11920785/8200290 – letsCode Jun 27 '18 at 16:15
  • @DroiDev i tried what you're saying with this: `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); });` and it still giving me error – Ina Yano Jun 28 '18 at 12:46

1 Answers1

0

This is working for me.

This is also with having an assumption that you have properly implemented a List that has String items in it.

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);


    }
}

This is the outcome for me.

You will have to style it... but this will get you started. enter image description here

From Firebase Docs.

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());
  }
});

Where System.out.println(post); if, you can do spinnerList.add(post.getTitle()); That will add the posts title to the list. Hopefully this makes sense....

letsCode
  • 2,774
  • 1
  • 13
  • 37
  • I get what you're trying to say but my problem is with firebase database, Im not sure if `mPersonTypeList` (which is equivalent with your `spinnerList`) is implemented right since the argument says it might be null but when I debug it, it shows that it has size=17 so i assume that it has items. – Ina Yano Jun 28 '18 at 14:37
  • why not iterate through that list and and print the values to console to see? Id image that you are getting string values from Firebase? I dont use firebase, so I can not help there, but I can probably look at the docs and figure it out. If – letsCode Jun 28 '18 at 14:58