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>
Related
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();
I was trying to create a spinner which display a list of data from array list.
When I clicked on the dropdown it displays the list, but when I clicked on an item inside the dropdown list it doesn't show up the value on the spinner.
Am I missing something here?
Note: Yesterday I have tried to check using Log.d() and System.out.println, itemOnSelected() doesn't but today it works fine. Maybe I rebuilding the project or I have changed something in the code but the value on the spinner still doesn't show up after I clicked on the item inside the spinner.
Spinner spnSubjectIDInfo;
ArrayList<String> subjectList;
ArrayAdapter<String> adpSubj;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
spnSubjectIDInfo = (Spinner) v.findViewById(R.id.spnSubjectIDInfo);
adpSubj = new ArrayAdapter<String>(MyActivity.this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spnSubjectIDInfo.setAdapter(adpSubj);
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
XML
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />
Try this
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this, subjectList.get(position).toString() " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
You are passing the wrong context to Toast instance:
If your code is in Activity then replace this by YourActivity.this or if it's in Fragment then use getActivity() or use Application context getApplicationContext(). Because currently, this is representing Spinner's onItemSelected listener context.
Do :
Toast.makeText(/*Your activity/application context*/, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
instead of:
Toast.makeText(this, parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
Change the "this" to "ActvityName.this" or use "getApplicationContext()" in the Toast, you are passing anonymous class context in the toast.
Like below:
spnSubjectIDInfo.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ActivityName.this,parent.getItemAtPosition(position)+ " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Hope this will help you.
public class SpinnerTest extends AppCompatActivity {
private ArrayList<String> subjectList;
private ArrayAdapter<String> adpSubj;
private Spinner spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner= (Spinner) findViewById(R.id.spnSubjectIDInfo);
subjectList = new ArrayList<String>();
subjectList .add("John");
subjectList .add("Maxi");
subjectList .add("Jeni");
adpSubj = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, subjectList);
adpSubj.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adpSubj);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), spinner.getItemAtPosition(position).toString() + " selected", Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
in Spinner setOnItemSelectedListener methord not work. if you want to get selected value show in toast use this line
String Text = mySpinner.getSelectedItem().toString();
Toast.makeText(this,Text,Toast.LENGTH_LONG).show();
it will return the selected value and will be displayed on Toast.
After few more searching I realized that I have to set the width size of the spinner to wrap_content as the length of the value doesn't support to display it on the spinner after the item being clicked at.
<Spinner
android:id="#+id/spnSubjectIDInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="54dp"
android:layout_centerHorizontal="true" />
I want to insert my drop down menu selected item in the edit text of body of new message so that i can edit the text and made necessary updates if required. My xml code for edit text is:
<EditText
android:id="#+id/editSMS"
android:layout_width="fill_parent"
android:layout_height="132dp"
android:gravity="top"
android:inputType="textMultiLine"
android:lines="9" />
code to select item from drop down menu
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
label = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
and code for new message
editSMS = (EditText) findViewById(R.id.editSMS);
public void onClick(View v) {
String phoneNo = editPhoneNum.getText().toString();
String sms = label + editSMS.getText().toString();
try {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
Code to load spinner data
private void loadSpinnerData() {
// database handler
DbHelper db = new DbHelper(getApplicationContext());
// Spinner Drop down elements
List<String> lables = db.getAllNames();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// 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);
}
Add do your drop down item selected listener. Cast parent to appropriate view class first, and then get selected item
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
label = ((Spinner) parent).getSelectedItem().toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + label,
Toast.LENGTH_LONG).show();
EditText etSMS= (EditText) findViewById(R.id.editSMS);
etSMS.setText(label);
}
I am new to Android Development so the query may seem novice.
I was trying to make an app where there are a couple of spinners and after the user selects one spinner the other spinner gets filled up with the data based on the selection in spinner1.
ie. First user selects Country. Based on country the spinner 2 gets filled up with states and based on the state the spinner 3 gets filled up with cities.
I have created all the countries as a string arrays in strings.xml like -
<string-array name="Country">
<item >USA</item> etc...
Similarly states have been created in the string.xml as - (Each Country is a separate entry with a naming convention as (country name)_(States)
<string-array name="USA_state">
<item >New York</item> etc...
Now I want the second spinner to populate based in country selection. Hence the formula used by me is to the get the second spinner is -
String getstate = country[index]+"_"+"state";
state=getResources()
.getStringArray(getResources().
getIdentifier(getstate,null,getPackageName()));
When I run this app the Manactivity just shows a blank screen and I donot get any Debug info and get an error "the jar file android.jar has no source attached".
Please help. The complete mainActivity is given below -
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import android.view.View;
public class MainActivity extends Activity {
String[] country;
String[] state;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
country = getResources().getStringArray(R.array.country);
Spinner country_spinner =(Spinner) findViewById(R.id.country);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+"country", Toast.LENGTH_SHORT).show();
Fill (index);
}
public void onNothingSelected(AdapterView<?> arg0) {}
});
}
protected void Fill(int index) {
// TODO Auto-generated method stub
//Field resField=R.array.getField(country[index]);
//int getstate = resField.getInt(null);
String getstate = country[index]+"_"+"state";
state=getResources().getStringArray(getResources().getIdentifier(getstate,null,getPackageName()));
Spinner state_spinner = (Spinner) findViewById(R.id.state);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, state);
state_spinner.setAdapter(adapter);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index2 = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(),"You Have Selected "+state[index2] + " statet",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0){}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
I was able to solve the problem. The final code is given below. This is a nested approach so if there are 3 spinners (like city after state) do we again nest the code for that spinner? Is there any simpler method?
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, country);
country_spinner.setAdapter(adapter);
country_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+country[index]+" County", Toast.LENGTH_SHORT).show();
final CharSequence[] state_array = state.getTextArray(index);
final Spinner state_spinner =(Spinner) findViewById(R.id.state);
ArrayAdapter<CharSequence> adapter1 = new ArrayAdapter<CharSequence>(MainActivity.this, android.R.layout.simple_spinner_item, state_array);
state_spinner.setAdapter(adapter1);
state_spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected (AdapterView<?> arg0, View arg1, int arg2, long arg3){
final int index = arg0.getSelectedItemPosition();
Toast.makeText(getBaseContext(), "You have Selected"+state_array[index]+" State", Toast.LENGTH_SHORT).show();
});
}
public void onNothingSelected(AdapterView<?> arg0) {
state_spinner.setAdapter(null);
}
});
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();