Get spinner selected items text? - android

How to get spinner selected item's text?
I have to get the text on the item selected in my spinner when i click on the save button.
i need the text not the Index.

Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();

TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();

You have to use the index and the Adapter to find out the text you have
See this example of Spinner
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}

Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();

use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>

spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {
String selected_val=spinner_button.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), selected_val ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

After set the spinner adapter this code will help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "This is " +
adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
try {
//Your task here
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});

One line version:
String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();
UPDATE:
You can remove casting if you use SDK 26 (or newer) to compile your project.
String text = findViewById(R.id.spinner).getSelectedItem().toString();

TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
String subItem = textView.getText().toString();

It also can be achieved in a little safer way using String.valueOf() like so
Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());
without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.

For spinners based on a CursorAdapter:
get the selected item id: spinner.getSelectedItemId()
fetch the item name from your database, for example:
public String getCountryName(int pId){
Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
String ret = null;
if(cur.moveToFirst()){
ret = cur.getString(0);
}
cur.close();
return ret;
}

For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.

Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();

Related

How do I check if the data in the Spinner is selected? In Kotlin [duplicate]

How to get spinner selected item's text?
I have to get the text on the item selected in my spinner when i click on the save button.
i need the text not the Index.
Spinner spinner = (Spinner)findViewById(R.id.spinner);
String text = spinner.getSelectedItem().toString();
TextView textView = (TextView)mySpinner.getSelectedView();
String result = textView.getText().toString();
You have to use the index and the Adapter to find out the text you have
See this example of Spinner
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent,
View view, int pos, long id) {
Toast.makeText(parent.getContext()), "The planet is " +
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Spinner returns you the integer value for the array. You have to retrieve the string value based of the index.
Spinner MySpinner = (Spinner)findViewById(R.id.spinner);
Integer indexValue = MySpinner.getSelectedItemPosition();
use this
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;
public class dynamic_spinner_main extends Activity {
private Spinner m_myDynamicSpinner;
private EditText m_addItemText;
private ArrayAdapter<CharSequence> m_adapterForSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_spinner);
///////////////////////////////////////////////////////////////
//grab our UI elements so we can manipulate them (in the case of the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
////////////////////////////////////////////////////////////////
//create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
m_adapterForSpinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
m_adapterForSpinner.add("gr");
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
Intent mIntent=new Intent(dynamic_spinner_main.this,sampleLocalization.class);
mIntent.putExtra("lang", m_myDynamicSpinner.getItemIdAtPosition(position));
System.out.println("Spinner value...."+m_myDynamicSpinner.getSelectedItem().toString());
startActivity(mIntent);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
addButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
////////////////////////////////////////////////////////////////
//add listener for addButton
clearButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
private void addNewSpinnerItem() {
CharSequence textHolder = "" + m_addItemText.getText();
m_adapterForSpinner.add(textHolder);
}
private void clearSpinnerItems() {
m_adapterForSpinner.clear();
m_adapterForSpinner.add("dummy item");
}
}
main_spinner.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<EditText android:layout_height="wrap_content"
android:layout_margin="4px"
android:id="#+id/newSpinnerItemText"
android:layout_width="fill_parent"></EditText>
<Button android:layout_height="wrap_content"
android:id="#+id/AddBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Add To Spinner"></Button>
<Button android:layout_height="wrap_content"
android:id="#+id/ClearBtn"
android:layout_margin="4px"
android:layout_width="fill_parent"
android:text="Clear Spinner Items"></Button>
<Spinner android:layout_height="wrap_content"
android:id="#+id/dynamicSpinner"
android:layout_margin="4px"
android:layout_width="fill_parent"></Spinner>
</LinearLayout>
spinner_button.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?>arg0, View view, int arg2, long arg3) {
String selected_val=spinner_button.getSelectedItem().toString();
Toast.makeText(getApplicationContext(), selected_val ,
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
After set the spinner adapter this code will help
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(), "This is " +
adapterView.getItemAtPosition(i).toString(), Toast.LENGTH_LONG).show();
try {
//Your task here
}catch (Exception e)
{
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
One line version:
String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();
UPDATE:
You can remove casting if you use SDK 26 (or newer) to compile your project.
String text = findViewById(R.id.spinner).getSelectedItem().toString();
TextView textView = (TextView) spinActSubTask.getSelectedView().findViewById(R.id.tvProduct);
String subItem = textView.getText().toString();
It also can be achieved in a little safer way using String.valueOf() like so
Spinner sp = (Spinner) findViewById(R.id.sp_id);
String selectedText = String.valueOf(sp.getSelectedItem());
without crashing the app when all hell breaks loose.
The reason behind its safeness is having the capability of dealing with null objects as the argument. The documentation says
if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.
So, some insurance there in case of having an empty Spinner for example, which the currently selected item has to be converted to String.
For spinners based on a CursorAdapter:
get the selected item id: spinner.getSelectedItemId()
fetch the item name from your database, for example:
public String getCountryName(int pId){
Cursor cur = mDb.query(TABLE, new String[]{COL_NAME}, COL_ID+"=?", new String[]{pId+""}, null, null, null);
String ret = null;
if(cur.moveToFirst()){
ret = cur.getString(0);
}
cur.close();
return ret;
}
For those have HashMap based spinner :
((HashMap)((Spinner)findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
If you are in a Fragment, an Adaptor or a Class other than main activities , use this:
((HashMap)((Spinner)YourInflatedLayoutOrView.findViewById(R.id.YourSpinnerId)).getSelectedItem()).values().toArray()[0].toString();
It's just for guidance; you should find your view's id before onClick method.
Spinner spinner = (Spinner) findViewById(R.id.yourspinnerid);
String text = spinner.getSelectedItem().toString();

Why not set the value of Spinner Android. i use Cursor?

I have a table in the database called PrimaryData Which includes fields are PrimaryDataId and PrimaryDataCode .My problem is,When the cursor returns data from database ,Spinner does not set the values of the cursor.
xml spinner file
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="14sp"
android:textColor= "#000000"
android:spinnerMode="dialog" />
PrimaryData class in which to put PrimaryDataId and PrimaryDataCode. This class is the equivalent of a database table.
package com.example.proposaldashborad;
public class PrimeryData {
private int primeryDataId;
private String primeryDataCode;
#Override
public String toString() {
return this.primeryDataCode; // What to display in the Spinner list.
}
public int getPrimaryDataId() {
return primeryDataId;
}
public void setPrimaryDataId(int value) {
this.primeryDataId = value;
}
public int getPrimaryDataCode() {
return primeryDataId;
}
public void setPrimaryDataCode(String value) {
this.primeryDataCode = value;
}
}
this code fill Spinner
private void GetPrimaryDataForSpinner(String primaryDataName, Cursor cr) {
cr.moveToFirst();
//array_spinner = new String[cr.getCount()];
ArrayList<PrimeryData> pds = new ArrayList<PrimeryData>() ;
do {
//array_spinner[i] = cr.getString(cr.getColumnIndex("PrimeryDataCode"));
PrimeryData pd = new PrimeryData() ;
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("PrimeryDataId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("PrimeryDataCode")));
pds.add(pd) ;
} while (cr.moveToNext());
cr.close();
if (primaryDataName == "Admin") {
adapterAdmin = new ArrayAdapter<PrimeryData>(this,R.layout.spinner, pds);
sAdmin = (Spinner) findViewById(R.id.spinnerAdmin);
sAdmin.setAdapter(adapterAdmin);
}
}
And this is my code when data is returned from the database.
private Spinner sAdmin;
private ArrayAdapter<PrimeryData> adapterAdmin;
db = new DBAdapter(getApplicationContext());
db.open();
cr = db.getViewMT26(entityID);
cr.moveToFirst();
if(cr.getCount()>0) {
PrimeryData pd = new PrimeryData();
pd.setPrimaryDataId(cr.getInt(cr.getColumnIndex("AdminId")));
pd.setPrimaryDataCode(cr.getString(cr.getColumnIndex("Admin")));
sAdmin.setSelection(adapterAdmin.getPosition(pd));
}
cr.close();
db.close();
My main question is why
adapterAdmin.getPosition (pd));
Returns -1?
You have to initialize your adapterAdmin, and set this to your spinner by setAdapter method.
Furthermore, if you only using a list of PrimeryData, then the text which is displayed on each spinner item will be PrimeryData (instance) toString().
Follow this code to set value in Spinner
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinnerOsversions;
TextView selVersion;
private String[] state = { "Cupcake", "Donut", "Eclair", "Froyo",
"Gingerbread", "HoneyComb", "IceCream Sandwich", "Jellybean",
"kitkat" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
System.out.println(state.length);
selVersion = (TextView) findViewById(R.id.selVersion);
spinnerOsversions = (Spinner) findViewById(R.id.osversions);
ArrayAdapter<String> adapter_state = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, state);
adapter_state
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOsversions.setAdapter(adapter_state);
spinnerOsversions.setOnItemSelectedListener(this);
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
spinnerOsversions.setSelection(position);
String selState = (String) spinnerOsversions.getSelectedItem();
selVersion.setText("Selected Android OS:" + selState);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}

Extracting 2 strings from 2 listviews in adroidstudio

I have 2 listviews in 1 activity (1 on the left 1 on the right of screen). I want 2 strings extracted from both list views and use them else where in the code (either in the same activity but different class or different activity). I have tried assigning clicked items to a public variable and then posting them on a text view bit I see nothing. Please help or suggest another better way. Here is a sample of my code:
public class Tabs extends Activity {
String CF =""; //Convert To
String CT =""; //Convert From
populateListView(); //function that populates my listview (not shown here)
ListView listMassFrom = (ListView) findViewById(R.id.ListViewMassFrom);
ListView listMassTo = (ListView) findViewById(R.id.ListViewMassTo);
listMassFrom.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
String convFrom = ((TextView) viewClicked).getText().toString();
CF = convFrom;
}
});
listMassTo.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
String convTo = ((TextView) viewClicked).getText().toString();
CT = convTo;
}
});
//Test to see if the two string were extracted from the onItemClick method:
TextView t1 = (TextView) findViewById(R.id.test1);
t1.setText(CT);
TextView t2 = (TextView) findViewById(R.id.test2);
t2.setText(CF);
}
}
You should access items via adapters using the parameter position.
Supposing your adapter contains Strings (Otherwise adapt it to your data model):
public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id) {
CF = <listMassFrom_adapter>.getItem(position);
}
EDIT:
Example tested and working. You can see a toast when items are selected.
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.example.testbutton.R;
public class Tabs extends Activity {
final static String[] MassUnits = { "kg", "g", "mg", "lb", "lbm", "slug" };
String CF = ""; // Convert To
String CT = ""; // Convert From
ListView listMassFrom, listMassTo;
ListAdapter adapterFrom, adapterTo;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabs);
// Find views
listMassFrom = (ListView) findViewById(R.id.lvFrom);
listMassTo = (ListView) findViewById(R.id.lvTo);
// Create list of items
adapterFrom = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MassUnits);
listMassFrom.setAdapter(adapterFrom);
adapterTo = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, MassUnits);
listMassTo.setAdapter(adapterTo);
listMassFrom
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View viewClicked, int position, long id) {
String convFrom = (String) adapterFrom
.getItem(position);
Toast.makeText(getApplicationContext(),
"From: " + convFrom, Toast.LENGTH_SHORT).show();
}
});
listMassTo
.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View viewClicked, int position, long id) {
String convTo = (String) adapterTo.getItem(position);
Toast.makeText(getApplicationContext(),
"To: " + convTo, Toast.LENGTH_SHORT).show();
}
});
}
}
Layout tabs.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lvFrom"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<ListView
android:id="#+id/lvTo"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>
I think it is better to use spinners, but you can adapt the code if that's the case.

How to get value from spinner in android ?

How to get values from drop down menu and use them in body of new message to be send.
Following is my code,
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
String phoneNo = editPhoneNum.getText().toString();
String sms = editSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// On selecting a spinner item
String label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,Toast.LENGTH_LONG).show();
}
}
try this
ArrayList<String> list = new ArrayList<String>(); //make this as field atribute
list.add("A");
list.add("B");
list.add("C");
Spinner s = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
list.get(position);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
Declare your String label and String phoneNo variables globally and then pass it in your message body.
Append your spinner item in your sms string.
Supposing your class code
public class MainActivity extends Activity {
private String phoneNo,sms,label;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.............................
phoneNo = editPhoneNum.getText().toString();
sms = editSMS.getText().toString() + label;
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
String label = parent.getItemAtPosition(position).getvalue();
getvalue().. according to location ur going getting only position. you have to get value yes use what value u want to get insted of getvalue() function name
Hi please have a look how we can do this i am sending example to you.
please look here
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
the full example is shown here as follows.
AndroidSpinnerExampleActivity.java
import java.util.ArrayList;
import java.util.List;
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.Toast;
import android.widget.AdapterView.OnItemSelectedListener;
public class AndroidSpinnerExampleActivity extends Activity implements OnItemSelectedListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinner);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Spinner Drop down elements
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
// Drop down layout style - list view with radio button
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinner.setAdapter(dataAdapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// On selecting a spinner item
String item = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " + item, Toast.LENGTH_LONG).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:padding="10dip"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Text Label -->
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip"
android:text="Category:"
android:layout_marginBottom="5dp"
/>
<!-- Spinner Element -->
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:prompt="#string/spinner_title"
/>
</LinearLayout>

How can I use onItemSelected in Android?

package org.example.mbtiapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
public class MBTITest extends Activity implements OnItemSelectedListener {
private Spinner firstSpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mbtitest);
Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.spinnerarraybool, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
firstSpinner.setAdapter(adapter);
}
#Override
public void onItemSelected(AdapterView<?> parent, View v, int position,
long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
XML Layout:
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="120dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:text="I like to go out more than staying home." />
<Spinner
android:id="#+id/spinner1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="120dp"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:gravity="center_vertical"
android:textSize="10.5dp"
android:text="Sensing v Intuition" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</TableRow>
</TableLayout>
I'm a new Android programmer and having trouble with using Spinner, i've tried multiple tutorials and still am confused. I'd like to know what my next step is here, as far as I know I have set up my spinner in XML, in Java I have identified that spinner, created an ArrayAdapter for said spinner, and specified some options. I'm not to sure if I have populated the spinner yet or how to manuever with the spinner object. I'd like to be able to use the spinner object to select one of three options and then keep that value inside of the textview inside of the spinner.
You're almost there. As you can see, the onItemSelected will give you a position parameter, you can use this to retrieve the object from your adapter, as in getItemAtPosition(position).
Example:
spinner.setOnItemSelectedListener(this);
...
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
This will put a message on screen, with the selected item printed by its toString() method.
If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});
Another thing:
When you have more than one spinner in your layout, you have to implement a switch selection in the onItemSlected() method to know which widget was clicked. Something like this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (parent.getId()){
case R.id.sp_alarmSelection:
//Do something
Toast.makeText(this, "Alarm Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
case R.id.sp_optionSelection:
//Do another thing
Toast.makeText(this, "Option Selected: " + parent.getSelectedItem().toString(), Toast.LENGTH_SHORT).show();
break;
}
}
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
Joseph:
spinner.setOnItemSelectedListener(this)
should be below
Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1);
on onCreate
I think this will benefit you
Try this I'm using to change the language in my application
String[] districts;
Spinner sp;
......
sp = (Spinner) findViewById(R.id.sp);
districts = getResources().getStringArray(R.array.lang_array);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,districts);
sp.setAdapter(adapter);
sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long arg3) {
// TODO Auto-generated method stub
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You select "+districts[index]+" id "+position, Toast.LENGTH_LONG).show();
switch(position){
case 0:
setLocal("fr");
//recreate();
break;
case 1:
setLocal("ar");
//recreate();
break;
case 2:
setLocal("en");
//recreate();
break;
default: //For all other cases, do this
setLocal("en");
//recreate();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
and this is my String Array
<string-array name="lang_array">
<item>french</item>
<item>arabic</item>
<item>english</item>
</string-array>
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if spinner2 has a selected item and show the value in edittext
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//check if spinner1 has a selected item and show the value in edittext
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// sometimes you need nothing here
}
});

Categories

Resources