32

I have implemented the spinner by populating the array list through database.I can get and show the array list in my spinner array adapter but if I select the item in spinner it does not shown in spinner?What I had mistake here?

Here is my code,

 Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
     ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);

  adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter1);

I get the selected item string by using this,

Spinner provid = (Spinner)findViewById(R.id.prospin);
String provider =provid.getSelectedItem().toString();

Can anyone help me out pls!!!

Jolly
  • 457
  • 1
  • 6
  • 11

27 Answers27

57

This answer may be a little stupid but try it. It worked for me.

  1. Check the background color of your spinner!
  2. And if it`s white change it
  3. Enjoy it!
Catluc
  • 1,775
  • 17
  • 25
24

I got same problem and solved by adding notifyDataSetChanged() after binding data in Spinner.

First of all I have bind adapter with Blank ArrayList then getting List of Items from Server and added to that List but forgot to notifyDataSetChanged() after updated List.

just add adapter.notifyDataSetChanged(); after updating list.

Hope it will helpful.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
12

Problem:

Spinner displays neither the default nor selected item value. But drop-down menu items are show when selected.

Cause:

Background and text color both being white!!!

Solutions:

xml(Preferable):

Write a custom layout for a spiner item and use it instead of the default,android.R.layout.simple_spinner_item.

How to change spinner text size and text color?

Code(Less reliable):

your_spinner_instance.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
    public void onItemSelected(AdapterView<?> parent, View view, int pos,
                               long id) {
        ((TextView) view).setTextColor(Color.RED);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }

});

Android needs some major update or maybe dart and flutter should take over...

Thanks Catluc

Community
  • 1
  • 1
TastyCatFood
  • 1,632
  • 1
  • 15
  • 27
  • you can use your custom simple spinner item. just add your textview to it: style="?android:attr/spinnerItemStyle" – elify Aug 18 '21 at 07:31
11

Use wrap_content for the height of Spinner.

Probably it does not have enough height to show text.

Pratik Butani
  • 60,504
  • 58
  • 273
  • 437
Mladen Rakonjac
  • 9,562
  • 7
  • 42
  • 55
5

Well this also happens if the context is not properly given. I was using getApplicationContext() where as it needs getBaseContext().

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
  • Can you please elaborate more Please answer this https://stackoverflow.com/questions/59451247/android-spinner-inside-dialog-which-is-inside-a-fragment-is-not-showing-selected – Priyanka Singhal Dec 23 '19 at 07:08
4

if you have a custom adapter you should change the TextView text color

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    TextView view = (TextView) super.getView(position, convertView, parent);
    view.setTextColor(Color.parseColor("#000000"));
    return view;
}

and if you don't have a custom adapter you should just change spinner background

Ali Salesi
  • 68
  • 1
  • 6
3

I was using hardcoded value for width and height. After changing to wrap_content it works.

Sayali Shinde
  • 311
  • 2
  • 6
2

For me the problem is that I was using getApplicationContext(). When I replace getApplicationContext() with this it works fine.

ArrayAdapter<*> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, documentsCategories);
Irfan Yaqub
  • 140
  • 10
Puni
  • 1,214
  • 2
  • 18
  • 34
1

use android:spinnerMode="dropdown" attribute in your declared Spinner element's xml

Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66
1

I just had this problem and after trying all of the solutions listed found out that the issue was that I had set the spinner layout_width to 60dp.

Changed it to fill_parent and problem solved.

Obsidian
  • 3,719
  • 8
  • 17
  • 30
  • The layout was the problem for me as well: it seems the spinner gets clipped when not enough horizontal room and shows only the caret symbol at a minimum. –  May 16 '20 at 14:30
1

add background color white and the details will display

for example

<Spinner
    android:id="@+id/size_spinner"
   style="@style/FormTextStyle"
    android:drawSelectorOnTop="true"
    android:layout_marginStart="@dimen/default_gap"
    android:background="@android:color/white"
    />
wafaa hilmy
  • 61
  • 1
  • 3
  • Could please add a more complete answer. The user might not know where to make the changes you've suggested and your sentence is constructed in a way that is not very easy to understand. – J. S. Jan 02 '20 at 22:05
1

This happens occasionally, I guess it's a bug but there's a workaround which is funny but just do it,

In the property bar of the spinner set the background to a different color,

In your .xml where you have your spinner, set:

android:background="@android:drawable/spinner_background_material"

run the code it will generate an error saying the background is private

delete the line of the android:background in the .xml and run the code again,your spinner should work fine showing all the values, if it doesn't take the extra step of setting background tint to a different color preferably black.

Run it again.

Muhammad Dyas Yaskur
  • 6,914
  • 10
  • 48
  • 73
Kenart
  • 285
  • 3
  • 14
  • Indeed generates the error: AAPT: error: resource android:drawable/spinner_background_material is private. But removing the line again and building doesn't fix it for me. – Harmen May 26 '21 at 19:40
1

I had the same problem, and none of the solutions were working for me. Finally found the problem was that the spinner was being populated from firestore db via an async task. Rearranged the code so that the adapter is set after the async task completion, and voila!!

Biplab Das
  • 33
  • 5
0

Check these links:

  1. http://www.technotalkative.com/android-spinner-example/
  2. http://www.mkyong.com/android/android-spinner-drop-down-list-example/

Else, try to store it on selecting the item:

spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapter, View v,
                    int position, long id) {
                // On selecting a spinner item
                String item = adapter.getItemAtPosition(position).toString();

                // Showing selected spinner item
                Toast.makeText(getApplicationContext(),
                        "Selected Country : " + item, Toast.LENGTH_LONG).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                // TODO Auto-generated method stub

            }
        });
Chintan Soni
  • 24,761
  • 25
  • 106
  • 174
  • It doesnt ask to get value of selected item. It says selected item is not drawn on layout. I have the same problem and I couldnt find an answer. Only background of spinner is shown and when you select an item from dropdown list nothing happens. – Arda Kara Jul 04 '16 at 23:09
0

Try this.

 final ArrayList<String> providerlist= new ArrayList<String>();
    Spinner spinner1 = (Spinner) findViewById(R.id.prospin);
    ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item, providerlist);

    adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter1);
    spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                            // On selecting a spinner item
            String item = providerlist.get(position);

            // Showing selected spinner item
            Toast.makeText(this,
                    "Selected Country : " + item, Toast.LENGTH_LONG).show();
        }

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

        }
    });
Quang Doan
  • 632
  • 4
  • 12
  • 1
    This does not display the selected item in the spinner. It only shows a toast containing the text of the selected item. The spinner remains blank. – dinosaur May 09 '16 at 05:42
0

Generally spinners gets selected by default when they are used ,so try to set blank,or any other data to first position that is zero position, you will get exact position of you selected item .

0

The issue from what I found was with the style sheet.Use this

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
  <!-- Customize your theme here. -->
  <item name="windowNoTitle">false</item>
  <item name="windowActionBar">true</item>
  <item name="colorPrimary">@color/colorPrimary</item>
  <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
  <item name="colorAccent">@color/colorAccent</item>
</style> 

For the xml layout use this

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:fitsSystemWindows="true"
    android:paddingBottom="5dp"
    style="@style/AppTheme">

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="5dp"
        android:paddingLeft="24dp"
        android:paddingRight="24dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Spinner"
            android:layout_marginTop="10dp"
            android:textColor="@color/colorBlack"/>

        <Spinner
            android:id="@+id/Spinner"
            android:layout_width="fill_parent"
            android:layout_height="50dp"
            android:backgroundTint="@color/colorPrimary"
            android:textColorHint="#05ab9a"
            android:padding="15dp"
            style="@style/Base.Widget.AppCompat.Spinner.Underlined"
            tools:targetApi="lollipop" />
    </LinearLayout>
</ScrollView>

And finally for the class

String [] NUMBERS= {"3 ","6 ","13 "};

Spinner s_spinner = (Spinner) findViewById(R.id.Spinner);

ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_dropdown_item_1line, NUMBERS);

// Specify the layout to use when the list of choices appears 
           spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

// attaching data adapter to spinner
s_spinner.setAdapter(spinnerAdapter );
RodneyO
  • 125
  • 1
  • 7
0

try this code==>

ArrayAdapter<String> stateNameAdaptor = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, stateNameList);  
     stateNameAdaptor.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

spnState.setAdapter(stateNameAdaptor);
Diego Venâncio
  • 5,698
  • 2
  • 49
  • 68
0

This answer may be a little stupid but if you do the same mistake then try... set values to your ArrayList first and then assign that arrayList to spinner. I declared a global arrayList and set it to spinner first and then add values to it from another method... at that time i faced the same problem. Otherwise you can do notifyDataSetChanged() to your arrayList.

0

Wierd. I had the same problem. What I did to make it work : 1. Add some initial data to the list ( ex.--- please select - -) 2. Load the rest of data and add it to the list 3. Call adapter.notifyDatasetChaged()

bashizip
  • 562
  • 5
  • 14
0

In my case the list is populated from firestore before supplied to the adapter construction. The list is already populated and is displayed in spinner. but the size of the list was returned zero. So I only can select the item from the list, but there is no display in the spinner text and unable to call the onitemselected part. I previously made a callback of the querysnapshot and from the snapshot I populated the list. it caused only adding the items to the spinner but cannot be selected. I resolved this by taking a callback of the list instead of the querysnapshot from a repository class and after this my list is populated well and its size is correct and the spinner works fine..my code is attached here.. hope this helps someone...

//interface
 public interface SprRbaCallback{
        void onSprRbaCallback(List<String> list);
    }
//Repository class
 public void getRBA(final SprRbaCallback sprRbaCallback){

        rbaCollection.get().addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
            @Override
            public void onSuccess(QuerySnapshot queryDocumentSnapshots) {

                for(DocumentSnapshot snapshot : queryDocumentSnapshots){
                    String item = (String) snapshot.get("dealerName");
                    assert item != null;
                    Log.d(TAG, item);

                    list.add(item);
                }
                Log.d(TAG, String.valueOf(list.size()));
                sprRbaCallback.onSprRbaCallback(list);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.d(TAG, e.toString());
            }
        });
} 

// calling method..

 private void addItemsToRBASpinner() {
        firebaseRepository.getRBA(new FirebaseRepository.SprRbaCallback() {
            @Override
            public void onSprRbaCallback(List<String> list) {
                int size = list.size();
                Log.d(TAG + "listsize", String.valueOf(size));


                ArrayAdapter<String> sprAdaptSelectRBA = new ArrayAdapter<String>(CreateAccountActivity.this,
                        R.layout.spinneritem, list);

                sprAdaptSelectRBA.setDropDownViewResource(R.layout.rbaspinner_dropdown);
                spr_rbaSelect.setAdapter(sprAdaptSelectRBA);

                sprAdaptSelectRBA.notifyDataSetChanged();

                spr_rbaSelect.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                    @Override
                    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                        Log.d("NOBY", "ENTERED ON ITEMSELETED");

                        txt_selectedRBA = (String) parent.getItemAtPosition(position);
                        Toast.makeText(parent.getContext(), "Selected RBA: " + txt_selectedRBA, Toast.LENGTH_LONG).show();

                        Log.d("NOBY", txt_selectedRBA);

                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> parent) {
                        Log.d("NOBY", "ENTERED NOTHING SELECTED");
                        txt_selectedRBA = "Dixon";
                    }
                });
            }
        });
    }

This code works fine for me...hope this help someone...:)

Noby Ali
  • 63
  • 1
  • 7
0

In my case I was using ViewModel to take data from repository which further takes data from room database. I was querying a list of string and then observing that to fill the spinner.

My mistake: I was making an adapter outside the ViewModel. Though I was getting the list inside the viewmodel.

My old code :

val machineNameList: MutableList<String> = mutableListOf()

createMachineViewModel.allMachineNames.observe(viewLifecycleOwner, Observer {
     machineNameList.addAll(it)
}

val spinnerAdapter = ArrayAdapter(
                requireActivity(),
                androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
                machineNameList
            )
spinnerAdapter.notifyDataSetChanged()
binding.spnMachine.adapter = spinnerAdapter

How did I solved this: Just inflate the spinner inside ViewModel only. Using Logs I was able to find that outside viewmodel the list is still empty. So you have to do like this :

val machineNameList: MutableList<String> = mutableListOf()

        createMachineViewModel.allMachineNames.observe(viewLifecycleOwner, Observer {
            val spinnerAdapter = ArrayAdapter(
                requireActivity(),
                androidx.appcompat.R.layout.support_simple_spinner_dropdown_item,
                machineNameList
            )

            machineNameList.addAll(it)
            Timber.d("All items are : $machineNameList")
            spinnerAdapter.notifyDataSetChanged()
            binding.spnMachine.adapter = spinnerAdapter
        })
oyeraghib
  • 878
  • 3
  • 8
  • 26
0

Changing the width and height to wrap_content worked for me. Surprisingly, the given width of some fixed value (60dp in my case) was working in normal mode, but it was showing blank for the landscape mode.

Suraj
  • 11
  • 1
0

It's because the setup of the spinner needs to be done inside a successful or completed task for example :-

collectionRef.get().addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        //Log.d(TAG, document.getId() + " => " + document.getData().get("myField")); // replace 'myField' with your field name
                        categories.add((String) document.getData().get("name"));
                    }
                    //Spinner setup inside the successful task
                    ArrayAdapter<CharSequence> adapter = new
                            ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, categories);
                    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                    //mySpinner.setSelection(0);
                    mySpinner.setAdapter(adapter);
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
                }
            });
-1

You should use the first Spinner to get the values.

Try the following code:

String provider = spinner1.getSelectedItem().toString();

What you are doing is getting the default value of the spinner.

-1

Try This code

ArrayAdapter<String> arrayAdapte=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,states);
    arrayAdapte.setDropDownViewResource(android.R.layout.simple_list_item_1 );
    spinnerState.setAdapter(arrayAdapte);

    String data=spinnerState.getSelectedItem().toString(); // this is select particular item from list;

    int position=spinnerState.getSelectedItemPosition(); // this return position of data selected in list; 
Shivam Sharma
  • 290
  • 2
  • 14
-1
out_marginLeft="50dp"
            android:layout_marginTop="50dp"
            android:layout_marginRight="50dp"
            android:gravity="center"
            android:orientation="vertical">

            <ProgressBar
                android:id="@+id/progressBar"
                style="?android:attr/progressBarStyleHorizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_above="@+id/txtProgress"
                android:layout_centerHorizontal="true"
                android:layout_marginLeft="16dp"
                android:layout_marginRight="16dp"
                android:progress="50"
                android:progressTint="@android:color/black" />

            <TextView
                android:id="@+id/txtProgress"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="8dp"
                android:text="Progress"
                android:textColor="@android:color/black" />
        </LinearLayout>  

Java