add ArrayList<object> to listview -android - android

in my android project,
i am getting a list of data in arraylist
ArrayList<Items> item = db.getAllMenu();
but now i want to add this data into listview,
i tried as,
ListView lv=(ListView)findViewById(R.id.list_view_inside_nav);
String[] lv_arr = {};
lv_arr = (String[]) item.toArray();
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, lv_arr));
but its giving error.because i am trying to convert arratlist to string..
anyone plz help me, how to convert the arraylist to string[]
here are my some files...
items.java (getter and setter methods)
public class Items {
//private variables
String _name;
// Empty constructor
public Items(){
}
// constructor
public Items(String name){
this._name = name;
}
// getting name
public String getName(){
return this._name;
}
// setting name
public void setName(String name){
this._name = name;
}
}
and i am using this code to get data from database
public ArrayList<Items> getAllMenu() {
ArrayList<Items> passList = new ArrayList<Items>();
// Select All Query
String selectQuery = "SELECT * FROM " + CATEGOTY_TABLE_NAME;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Items menu = new Items();
menu.setName(cursor.getString(0));
// Adding category to list
passList.add(menu);
} while (cursor.moveToNext());
}
// return category list
return passList;
}

Your problem here is that you are trying to convert a List into an Array, this can't be done with a cast but methods exist.
The easiest would be to convert the list into an Array using the methods List.toArray(E[]).
ArrayList<Items> items = db.getAllMenu();
Items[] itemsArray = new Items[items.size()]; //Create the array to the correct size,
itemsArray = items.toArray(itemsArray); //Fill the array with the list data
//you could cast into Item[] directly but this is cleaner
Help to use here : Convert ArrayList<String> to String[] array
The array need to be an array of Items
Then, if you have override the toString methods of your Item class to return the String like you want.
public class Items {
...
#Override
public String toString(){
this.getName() //Just an example ;)
}
...
}
This will work like a charm. The adapter use this method to get the String to print.
EDIT :
After some research, you don't even need to create an array. ArrayAdapter accept an List so you only need to override Items.toString()
https://developer.android.com/reference/android/widget/ArrayAdapter.html
You can see here the need to override the toString
However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.
And here is the constructor to use
ArrayAdapter (Context context,
int resource,
List objects)
So just create your adapter like this :
new ArrayAdapter<Items>(MainActivity.this,
android.R.layout.simple_list_item_1, item);

You have to make arraylist of object to do such thing here is a piece of my code that i use
My ArrayList
private ArrayList<Mediafileinfo> songList = new ArrayList<Mediafileinfo>();
Adding data in the arraylist object.
Mediafileinfo info = new Mediafileinfo();
info.setFile_uri(Uri.parse(audioCursor.getString(audiodata)));
info.setName(audioCursor.getString(audioTitle));
info.setDuration(audioCursor.getLong(audioduration));
info.setAlbum(audioCursor.getString(audioalbum));
info.setAlbum_Art_uri(ContentUris.withAppendedId(albumArtUri, audioCursor.getLong(audioalbumid)));
songList.add(info);
Make a class with getter and setter
public class Mediafileinfo {
private String name,album,artist;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAlbum() {
return album;
}
public void setAlbum(String album) {
this.album = album;
}
public String getArtist() {
return artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
}
And call in your arraylist adapter like this
Mediafileinfo mediafileinfo = (Mediafileinfo) getItem(position);
TextView textView = (TextView) view.findViewById(R.id.textView);
textView.setText(mediafileinfo.getAlbum());
and rest will be the same
you can set the arraylist in your adapter like this
new CustomAdapter(this,songlist)
Hope this will help you.For more info

Wrong.
Items class cannot convert to a String class.
You need to convert each Items to String object.
Example :
Say your class Item
class Items{
public String itemName;
}
In your code change
String[] lv_arr = new String[items.size()];
for(int i=0;i<items.size();i++){
lv_arr[i]=item.get(i);
}
lv.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, lv_arr));

let listobj be a list of object you want toset for your listView and Lv be your listview
use following code:
LV.setAdapter(new ArrayAdapter<>(getContext(),android.R.layout.simple_list_item_1 ,sensors));
update
if you want each item of your LisView represent a specific object you could also populate it with a custom adaptor like this :
first in your java files define new javaclass that extends BaseAdaptor
public class SensorAdaptor extends BaseAdapter{
private final Context context;
private final List<Sensor> sensors;
public SensorAdaptor(Context context , List<Sensor> sensors){
this.context = context;
this.sensors = sensors;
}
#Override
public int getCount() {
return sensors.size();
}
#Override
public Object getItem(int position) {
return sensors.get(position);
}
#Override
public long getItemId(int position) {
return sensors.get(position).getType();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.list_sensors, null);
} else {
view = convertView;
}
TextView listName = view.findViewById(R.id.txtSensorList);
listName.setText(sensors.get(position).getName());
return view;
}
}
attention in my case i want each item of listView represent a Sensor object
then in layout file in res/layout define a layout for this adaptor to use
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/**txtSensorList**"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
and then in yor activity
List<Sensor> sensors = mgr.getSensorList(Sensor.TYPE_ALL);
LV.setAdapter(new SensorAdaptor(getContext(),sensors));
attention
in my case i want to show a list of sensor Object

Related

How to map json array elements to option selected in Spinner?

I have a json array like below and want to select corresponding id when an option is selected from spinner which is also dynamic i.e. also a json array which is displayed in Spinner
{
"DoctorName": ["0001 DR. Sameer", "0001 DR.Krishna murti", "110 Mr. Ram", "4 Mr. Yash Pathak.", "99 Dr. Varma"],
"DoctorId": [3,2,110,4,99]
};
and I have to do it into Android. Any help will be appreciated.
1.First Create a class
public class DoctorName
{
public String id = "";
public String name = "";
public void setId(String id)
{
this.id = id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String getId()
{
return id;
}
// A simple constructor for populating our member variables for this tutorial.
public DoctorName( String _id, String _name)
{
id = _id;
name = _name;
}
// The toString method is extremely important to making this class work with a Spinner
// (or ListView) object because this is the method called when it is trying to represent
// this object within the control. If you do not have a toString() method, you WILL
// get an exception.
public String toString()
{
return( name );
}
}
2.create another class
MainClass.java
ArrayList<DoctorName> doctList = new ArrayList<DoctorName>() ;
for(int i=0;i<arr_name.length;i++)
{
doctList.add(new DoctorName(arr_id[i],arr_name[i]));
}
//fill data in spinner
//ArrayAdapter<DoctorName> adapter = new ArrayAdapter<DoctorName>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, answers);
ArrayAdapter <DoctorName>adapter= new ArrayAdapter<DoctorName>
(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,doctList );
Doctor_selection.setAdapter(adapter);
Doctor_selection.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
DoctorName doctorName = (DoctorName) parent.getSelectedItem();
Log.i("SliderDemo", "getSelectedItemId" +doctorName.getId());
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
}
});
You have to use ArrayAdapter to show the json array values into spinner
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list_values); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);
//Set on item select Listener
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// here you can get your selected id
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
For more check here.
Create two arrays, that is DoctorName and DoctorId
Create dynamic HashMap using above arrays, put all the values in key - value form by using for loop. But for this the length of both above arrays should be same.
HashMap<String, String> hash;
for(int i = 0; i < DoctorName.size() ; i++) {
hash = new HashMap<String, String>();
hash.put(DoctorId.get(i), DoctorName.get(i));
}
For spinner send only doctor name list from Map (hash), and onclick of spinner gets its Id that is doctorId.
Write below code in Spinner onclick
String name = spinner.getSelectedItem().toString();
String id = hash.get(name);
In id you will get the corresponding id of selected name.
Hope It helps :)

Getting subItems in my list view

In my list view for ITEM I get the title of the feed but I want to get the description, image and link in the SUBITEM in that list view. Can you help me?
This is what I have:
1) The ListView in MainActivity
ArrayAdapter<RSSItem> adapter;
adapter = new ArrayAdapter<RSSItem>(
this,
android.R.layout.simple_list_item_1,
myRssFeed.getList()
);
setListAdapter(adapter);
2) RSSItem
public class RSSItem {
private String title = null;
private String description = null;
private String link = null;
private String pubdate = null;
RSSItem(){}
void setTitle(String value) {
title = value;
}
void setDescription(String value) {
description = value;
}
void setLink(String value) {
link = value;
}
void setPubdate(String value) {
pubdate = value;
}
String getTitle() {
return title;
}
String getDescription() {
return description;
}
String getLink() {
return link;
}
String getPubdate() {
return pubdate;
}
public String toString() {
//TODO Auto-generated method stub
return title;
}
}
Just use a custom ArrayAdapter. It's super simple:
1) Define your custom ArrayAdapter. Fill in the body of getView() to create a view based on each item your pass to the adapter;
public class YourArrayAdapter<YourDataObject> extends ArrayAdapter<T> {
public YourArrayAdapter(Context context) {
super(context, 0); // Pass in 0 because we will be overriding getView()
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// getView() gets called when this item becomes visible in the ListView
// All you have to do is build a view with your data object and return it.
YourDataObject yourDataObject = getItem(position);
YourView view = new YourView(yourDataObject);
}
}
2) Pass the adapter to your ListView, and add data.
YourArrayAdapter<RSSItem> adapter = new YourArrayAdapter<RSSItem>(this);
adapter.addAll(myRssFeed.getList());
setListAdapter(adapter);
The important thing to realize here is that Adapters turn lists of data into actual UI Views when the ListView requests a view via Adapter.getView(). In this case, you are creating a custom ArrayAdapter, and so you control everything about the View that it returns. You can return a view that has its own layout, and includes the many different pieces of data that RSSItem includes, and presents them in whatever format you desire. The cool thing is that by using ListView and a custom ArrayAdapter, you never have to worry about creating or destroying these views -- that's all taken care of for you. So if the items your return from ArrayAdapter.getView() include bitmaps, you don't need to really worry too much about running out of memory.

Android add items to arraylist using custom class

I'm trying to add items to an arraylist using this class template:
public class Template {
public String username;
public String email;
}
Here's the whole code:
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<Template> arrayAdapter = new ArrayAdapter<Template>(this,android.R.layout.simple_list_item_1, listItems);
lv.setAdapter(arrayAdapter);
}
The problem is, instead of filling my listview with nice username and email strings, it's filling up with items like this:
com.android.ninjaarchives.
Template#40585690
I think somewhere along the line I have become lost, but I've been trying all sorts for ages now and getting nowhere. Can anyone point me in the right direction?
Thanks for any help.
Note: not really sure what's going on with the code; it doesn't appear to be pasting correctly.
Use below code, it can be a solution for you
public void JsonToArrayList(JSONArray myJsonArray) throws JSONException
{
ArrayList<Template> listItems = new ArrayList<Template>();
JSONObject jo = new JSONObject();
Template tem = new Template();
ListView lv = (ListView) findViewById(R.id.listView1);
String listItemString[] = new String[myJsonArray.length];
for(int i = 0; i<myJsonArray.length(); i++)
{
jo = myJsonArray.getJSONObject(i);
tem.username = jo.getString("username");
tem.email = jo.getString("user_email");
listItemString[i] = tem.username +" - " + tem.email; // u can change it according to ur need.
listItems.add(tem);
Log.e("Ninja Archives", tem.username);
}
// This is the array adapter, it takes the context of the activity as a first // parameter, the type of list view as a second parameter and your array as a third parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, listItemString);
lv.setAdapter(arrayAdapter);
}
But better to write Custom adapter by extending BaseAdapter, and do listItem handling in getView method here is one simple tutorial
Take a class extending Base
private class CustomAdapter extends BaseAdapter
{
LayoutInflater inflater;
public CustomAdapter(Context context)
{
inflater = LayoutInflater.from(context);
}
public int getCount()
{
return listItems.size();
}
public Object getItem(int position)
{
return listItems.get(position);
}
public long getItemId(int position)
{
return position;
}
public View getView(final int position, View convertView,ViewGroup parent)
{
//if(convertView==null)
//convertView = inflater.inflate(R.layout.listlayout, parent, false);
Template data = (Template) getItem(position);
TextView v=new TextView(context);
v.setText(data.name);
return v;
}
}
and set adapter to your listview
lv.setAdapter(new CustomAdapter(this));
In this case you have to use a custom adapter (that extends from ArrayAdapter) and override the getView method to display in a custom layout the username and the email.

Android action listener to call a method in another class

I have a listview with a button in each row. I have made a custom Adapter class and a ItemModel class to hold the data for each row. Inside the ItemModel class I have defined an ActionListener for the button. How can I call a method in another class from inside my button's action listener?
Right now if i say Classname clsName = new Classname(); and inside the actionlistener do clsName.methodName(variableToPass); <--- this all compiles but crashes when I click the button..Anyone know how to get this to work?
MyListModel Class
public class MyListItemModel{ //that's our book
private String title; // the book's title
private String description; //the book's description
int id; //book owner id
String key; //book key
private Context context;
Shelf shelf = new Shelf(); //shelf class
public MyListItemModel(Context c){
this.context=c;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKey() {
return key;
}
public void setKey(String key){
this.key = key;
}
OnClickListener listener = new OnClickListener(){ // the book's action
#Override
public void onClick(View v) {
//code for the button action
//THIS DOESN'T WORK PROPERLY AND CRASHES ON CLICK. However if i use a Toast to print the key on each click - it will print the right key to screen.
shelf.downloadBook(new String(key));
}
};
int getBookId(){
return title.hashCode();
}
}
MyListAdapter class - method for getView
public class MyListAdapter extends BaseAdapter {
View renderer;
List<MyListItemModel> items;
ArrayList<HashMap<String, String>> mylist;
private LayoutInflater mInflater;
private Context context;
public MyListAdapter(Context c){
this.context=c;
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
....
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView==null){
//convertView = renderer;
convertView = mInflater.inflate(R.layout.shelfrow, null);
}
MyListItemModel item = items.get(position);
TextView label = (TextView)convertView.findViewById(R.id.item_title);
label.setText(item.getTitle());
TextView label2 = (TextView)convertView.findViewById(R.id.item_subtitle);
label2.setText(item.getDescription());
Button button = (Button)convertView.findViewById(R.id.btn_download);
button.setOnClickListener(item.listener);
return convertView;
}
My Shelf class has a method called downloadBook(String bookKey) <-- this is what I want to call with each button click and pass this method the appropriate book key. I also have 2 xml files (shelfrow.xml and shelflist.xml). One contains the textfields and button and the other contains the listview.
Some of the code from Shelf.java class
List<MyListItemModel> myListModel = new ArrayList<MyListItemModel>();
try{
JSONArray entries = json.getJSONArray("entries");
for(int i=0;i<entries.length();i++){
MyListItemModel item = new MyListItemModel(this);
JSONObject e = entries.getJSONObject(i);
item.id = i; //user ID
bookKey = (e.getString("key"));
item.setTitle(e.getString("title"));
item.setDescription(e.getString("description"));
myListModel.add(item);
}
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
MyListAdapter adapter = new MyListAdapter(this);
adapter.setModel(myListModel);
setListAdapter(adapter);
lv = getListView();
lv.setTextFilterEnabled(true);
….
public void downloadBook(String theKey) {
//take theKey and append it to a url address to d/l
}
Stacktrace from logcat
05-23 02:34:59.439: INFO/wpa_supplicant(14819): Reset vh_switch_counter due to receive LINKSPEED cmd 05-23 02:34:59.439: DEBUG/ConnectivityService(1346): getMobileDataEnabled returning true 05-23 02:36:39.269: DEBUG/StatusBarPolicy(6068): onSignalStrengthsChange
also this came up zygoteinit methodandargscaller.run
I am going to go out on a limb here, but I think I know what the issue is.
In the last snippet of code, you are not setting the key field on the MyListItemModel. You are instead setting some variable called 'bookKey' (I do not see where it is defined).
I bet if you change this line:
bookKey = (e.getString("key"));
to be this:
item.setKey(e.getString("key"));
//or item.key = e.getString("key"));
everything will work just fine for you. If you pass in a null String to the String(String) constructor, you will get a NullPointerException, as that constructor expects a non-null String.
I will mention that it is not necessary for you use the String(String) constructor, you should be fine just doing this in the fist snippet:
shelf.downloadBook(key);

Android Spinner databind using array list

I have a array list like this:
private ArrayList<Locations> Artist_Result = new ArrayList<Location>();
This Location class has two properties: id and location.
I need to bind my ArrayList to a spinner. I have tried it this way:
Spinner s = (Spinner) findViewById(R.id.SpinnerSpcial);
ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item, Artist_Result);
s.setAdapter(adapter);
However, it shows the object's hexadecimal value. So I think I have to set display the text and value for that spinner controller.
The ArrayAdapter tries to display your Location-objects as strings (which causes the Hex-values), by calling the Object.toString()-method. It's default implementation returns:
[...] a string consisting of the name of the class of which the object
is an instance, the at-sign character `#', and the unsigned
hexadecimal representation of the hash code of the object.
To make the ArrayAdadpter show something actually useful in the item list, you can override the toString()-method to return something meaningful:
#Override
public String toString(){
return "Something meaningful here...";
}
Another way to do this is, to extend BaseAdapter and implement SpinnerAdapter to create your own Adapter, which knows that the elements in your ArrayList are objects and how to use the properties of those objects.
[Revised] Implementation Example
I was playing around a bit and I managed to get something to work:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create and display a Spinner:
Spinner s = new Spinner(this);
AbsListView.LayoutParams params = new AbsListView.LayoutParams(
ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT
);
this.setContentView(s, params);
// fill the ArrayList:
List<Guy> guys = new ArrayList<Guy>();
guys.add(new Guy("Lukas", 18));
guys.add(new Guy("Steve", 20));
guys.add(new Guy("Forest", 50));
MyAdapter adapter = new MyAdapter(guys);
// apply the Adapter:
s.setAdapter(adapter);
// onClickListener:
s.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item was selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Guy g = (Guy) parent.getItemAtPosition(pos);
Toast.makeText(
getApplicationContext(),
g.getName()+" is "+g.getAge()+" years old.",
Toast.LENGTH_LONG
).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
});
}
/**
* This is your own Adapter implementation which displays
* the ArrayList of "Guy"-Objects.
*/
private class MyAdapter extends BaseAdapter implements SpinnerAdapter {
/**
* The internal data (the ArrayList with the Objects).
*/
private final List<Guy> data;
public MyAdapter(List<Guy> data){
this.data = data;
}
/**
* Returns the Size of the ArrayList
*/
#Override
public int getCount() {
return data.size();
}
/**
* Returns one Element of the ArrayList
* at the specified position.
*/
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int i) {
return i;
}
/**
* Returns the View that is shown when a element was
* selected.
*/
#Override
public View getView(int position, View recycle, ViewGroup parent) {
TextView text;
if (recycle != null){
// Re-use the recycled view here!
text = (TextView) recycle;
} else {
// No recycled view, inflate the "original" from the platform:
text = (TextView) getLayoutInflater().inflate(
android.R.layout.simple_dropdown_item_1line, parent, false
);
}
text.setTextColor(Color.BLACK);
text.setText(data.get(position).name);
return text;
}
}
/**
* A simple class which holds some information-fields
* about some Guys.
*/
private class Guy{
private final String name;
private final int age;
public Guy(String name, int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
}
I fully commented the code, if you have any questions, don't hesitate to ask them.
Simplest Solution
After scouring different solutions on SO, I found the following to be the simplest and cleanest solution for populating a Spinner with custom Objects. Here's the full implementation:
Location.java
public class Location{
public int id;
public String location;
#Override
public String toString() {
return this.location; // What to display in the Spinner list.
}
}
res/layout/spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor="#FFFFFF"
android:spinnerMode="dialog" />
res/layout/your_activity_view.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<Spinner
android:id="#+id/location" />
</LinearLayout>
In Your Activity
// In this case, it's a List of Locations, but it can be a List of anything.
List<Location> locations = Location.all();
ArrayAdapter locationAdapter = new ArrayAdapter(this, R.layout.spinner, locations);
Spinner locationSpinner = (Spinner) findViewById(R.id.location);
locationSpinner.setAdapter(locationAdapter);
// And to get the actual Location object that was selected, you can do this.
Location location = (Location) ( (Spinner) findViewById(R.id.location) ).getSelectedItem();
Thanks to Lukas' answer above (below?) I was able to get started on this, but my problem was that his implementation of the getDropDownView made the dropdown items just a plain text - so no padding and no nice green radio button like you get when using the android.R.layout.simple_spinner_dropdown_item.
So as above, except the getDropDownView method would be:
#Override
public View getDropDownView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(android.R.layout.simple_spinner_dropdown_item, null);
}
TextView textView = (TextView) convertView.findViewById(android.R.id.text1);
textView.setText(items.get(position).getName());
return convertView;
}
Well, am not gonna confuse with more details.
Just create your ArrayList and bind your values like this.
ArrayList tExp = new ArrayList();
for(int i=1;i<=50;i++)
{
tExp.add(i);
}
Assuming that you have already a spinner control on your layout say with id, spinner1. Add this code below.
Spinner sp = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adp1=new ArrayAdapter<String>this,android.R.layout.simple_list_item_1,tExp);
adp1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sp.setAdapter(adp1);
All the above code goes under your onCreate function.
Thank Lukas, you help me a lot.
I d'like to improve your answer.
If you just want to access the selected item later, you can use this :
Spinner spn = (Spinner) this.findViewById(R.id.spinner);
Guy oGuy = (Guy) spn.getSelectedItem();
So you don't have to use the setOnItemSelectedListener() in your initialisation :)

Categories

Resources