Search code examples
androidfirebasefirebase-realtime-databasespinnerhint

How to add Hint in Spinner widget populated with data from FireBase Database?


My xml code is :

<Spinner
    android:id="@+id/destination"
    android:layout_width="344dp"
    android:layout_height="30dp"
    android:autofillHints="Choose destination"
    android:spinnerMode="dropdown" />

I want to add hint (without using dummy entry) as to be shown to user when the activity starts. The inbuilt xml hint feature is not working after using FireBase.

MainActivity :

myRef.child("Stations").addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            final List<String> stationname = new ArrayList<String>();

            for (DataSnapshot stationSnapshot : dataSnapshot.getChildren()) {

                 String stationName = stationSnapshot.child("Name").getValue(String.class);
                 stationname.add(stationName);
            }

            Spinner sp2= findViewById(R.id.destination);

            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(FairPage.this, android.R.layout.simple_spinner_item, stationname);
            arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            sp2.setAdapter(arrayAdapter);

Solution

  • Try this

    myRef.child("Stations").addListenerForSingleValueEvent(new 
    ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            final List<String> stationname = new ArrayList<String>();
            stationname.add("Select Station");
            for (DataSnapshot stationSnapshot : dataSnapshot.getChildren()) {
    
                 String stationName = stationSnapshot.child("Name").getValue(String.class);
                 stationname.add(stationName);
            }
    
            Spinner sp2= findViewById(R.id.destination);
    
            ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(FairPage.this, android.R.layout.simple_spinner_item, stationname);
            arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    
            sp2.setAdapter(arrayAdapter);
    

    and also check when spinner item selected

    if (stationname.get(postion).equals("Select Station"){
    //Toast please  select station 
    }