Populating Spinner Directly in the Layout Xml

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
android:id="@+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="@array/array_name"
/>

I've heard this doesn't always work on the designer, but it compiles fine.

Set constant choices in Android Spinner from layout.xml

plug this into your spinner assuming that you have properly created you xml array...

    android:drawSelectorOnTop="true"
android:entries="@array/array_name"

Your String Resources you should add the array like so...

 <string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

Populate Spinner WITHOUT Strings.xml file

So everything I have found is using the strings.xml file to populate a spinner.

Here is a sample app that demonstrates populating a Spinner with the contents of a Java array.

The documentation happens to use an array resource for populating the Spinner, but you could swap in some other ArrayAdapter for the one their sample code creates using createFromResource().

Here is the code to populate the spinner

There is no code in there that populates a Spinner. You retrieve a Spinner from your layout. You then call setId() on it in a loop — I am not completely clear why. You have an ArrayAdapter named adapter that holds promise, but you never set it up.

Here is the activity from the sample app that I linked to above:

/***
Copyright (c) 2008-2012 CommonsWare, LLC
Licensed under the Apache License, Version 2.0 (the "License"); you may not
use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
by applicable law or agreed to in writing, software distributed under the
License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
OF ANY KIND, either express or implied. See the License for the specific
language governing permissions and limitations under the License.

From _The Busy Coder's Guide to Android Development_
https://commonsware.com/Android
*/

package com.commonsware.android.selection;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;

public class SpinnerDemo extends Activity
implements AdapterView.OnItemSelectedListener {
private TextView selection;
private static final String[] items={"lorem", "ipsum", "dolor",
"sit", "amet",
"consectetuer", "adipiscing", "elit", "morbi", "vel",
"ligula", "vitae", "arcu", "aliquet", "mollis",
"etiam", "vel", "erat", "placerat", "ante",
"porttitor", "sodales", "pellentesque", "augue", "purus"};

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
selection=(TextView)findViewById(R.id.selection);

Spinner spin=(Spinner)findViewById(R.id.spinner);
spin.setOnItemSelectedListener(this);

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

aa.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
spin.setAdapter(aa);
}

@Override
public void onItemSelected(AdapterView<?> parent,
View v, int position, long id) {
selection.setText(items[position]);
}

@Override
public void onNothingSelected(AdapterView<?> parent) {
selection.setText("");
}
}

It follow the same recipe as in the documentation. I happen to use a constructor to create the ArrayAdapter instance, wrapping it around the String[] that is my model data. It is unclear what you want to have in your Spinner, but you could have an ArrayAdapter<Integer> (as is shown in your code) or ArrayAdapter<Route> or whatever.

For more complex scenarios, look for ListView examples. Spinner works nearly identically, with only two substantial changes:

  • You need to provide two layout resources (see setDropDownViewResource() in the code above). And, if you override getView() in a custom subclass of ArrayAdapter, probably you also need to override getDropDownView().

  • Spinner fires selection events, not item click events

Getting java.lang.NullPointerException On simply populating spinner from string array or list or xml file(strings.xml)

The error says your adapter is null.

Try change your adapter initialise your adapter like this:

ArrayAdapter<CharSequence> adapter = 
new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, R.array.ans);

Edit

Actually you know what, why not do it in your xml file instead, like this:

<Spinner
android:id="@+id/sp1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:entries="@array/ans"
android:prompt="@string/select_one"/>

EDIT2

Since you prefer to do it programmatically, try:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.ans)); 
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp2.setAdapter(adapter);
  • R.array.ans changed to getResources().getStringArray(R.array.ans)

Hope this helps.

android: populate a spinner from strings.xml

super.onCreate(savedInstanceState);
setContentView(yourView);
day = (Spinner)findViewById(R.id.week_spinner);

You forgot to set view before getting spinner from xml. If you don't set view, findViewById returns null.

Any operation on null reference results in NullPointerException.

Use string array to populate Spinner

Simplest way to bind ListView and Spinner control with String Array is

android:entries = "@array/nameofarray"

<Spinner
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/MainSpinner"
tools:listitem="@layout/support_simple_spinner_dropdown_item"
android:entries="@array/Convert_Type"/>

If you want to change the theme of each item of Spinner then put below style into res/values/styles.xml

<style name="ItemTextAppearance">
<item name="android:textColor">#f00</item>
<item name="android:textStyle">bold</item>
<item name="android:typeface">monospace</item>
</style>

and the set

android:theme="@style/ItemTextAppearance"

of spinner.

Populating spinner with custom object .how to set spinner hint in custom object

One easy way is to create a dummy Country object at beginning and add to array whose name is Select Country and fill other dummy details which you might be needing and while tapping on any form button (assuming you have one) you can check the current selected index and if it is 0 then no country is selected. In that case you can show a Toast.

For example here is your updated try catch block:

try {
JSONObject object = new JSONObject(response.body().toString());
JSONObject jsonObj = new JSONObject(object.toString());
JSONArray jsonArray = jsonObj.getJSONArray("data");

if (jsonArray.length() > 0) {

Country country = new Country();
country.setId(0);
country.setName("Select Country");
country.setCode(0);
mCountryList.add(country);

for (int i = 0; i < jsonArray.length(); i++) {

JSONObject jsonObject = jsonArray.getJSONObject(i);

Country country = new Country();
country.setId(jsonObject.getInt("id"));
country.setName(jsonObject.getString("name"));
country.setCode(jsonObject.getString("code"));
mCountryList.add(country);

}
ArrayAdapter < Country > arrayAdapter = new ArrayAdapter < Country > (getApplicationContext(), R.layout.spinner_layout, country);
arrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerCountry.setAdapter(arrayAdapter);

}
} catch (Exception e) {
e.printStackTrace();
}

1st element is your hint and make sure you check the index when you are actually want to take any action i.e. if index is 0 show user a Toast to select a Country.

Setting Spinner to the same layout as the XML version

You can customize it with the ArrayAdapter.setDropDownViewResource() method:

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


Related Topics



Leave a reply



Submit