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
}
});
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 have searched for this over the internet and haven't found appropriate answers. I am loading a spinner drop down menu on my toolbar which contains items that open different activities after being selected. So far I have been able to create a toast which returns the name of the selected item. But I would like to open different activities for each item on the menu. I know this might be a duplicate somewhere but their answers haven't worked for mine yet.
This is my spinner:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="2dp"
android:background="#color/primaryColor"
android:theme="#style/ThemeOverlay.AppCompat.Dark">
<Spinner
android:id="#+id/spinner_nav"
android:layout_width="wrap_content"
android:gravity="bottom"
android:layout_height="wrap_content"></Spinner>
</android.support.v7.widget.Toolbar>
And this is my MainActivity.java
public class MainActivity extends ActionBarActivity {
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.app_bar);
setSupportActionBar(toolbar);
final Spinner spinner_navs = (Spinner) findViewById(R.id.spinner_nav);
SpinnerAdapter mSpinner = ArrayAdapter.createFromResource
(this, R.array.action_bar_spinner, android.R.layout.simple_spinner_dropdown_item);
spinner_navs.setAdapter(mSpinner);
spinner_navs.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
I know I am a newbie, but any help on this I would appreciate it. Thanks in advance.
Use this
spinner_nav.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
if(position==0){
// open activity 1
}else if(position==1){
// open activity 2
}
else if(position==2){
// open activity 3
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
Use a Switch statement
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString();
switch (position) {
case 1:
Intent intent = new Intent(this, ResultActivity.class);
intent.putExtra("yourkeyone", string);
break;
case 2:
Intent i = new Intent(this, ResultActivity.class);
i.putExtra("yourkeytwo", string);
break;
//ect...
}
return true;
}
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 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();