Extracting 2 strings from 2 listviews in adroidstudio - android

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.

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();

Adding onClickListener to specific items in ListView

please I'm trying to add understand how to add onItemClickListener to the followng code such that when "Smartphone Plans" is clicked, its activity starts and so on. I've seen other questions on StackOverflow relating to this question but do not understand how to go about them.
I've already added an onItemClickListener but do not understand how to set it to specific list items.
here is the code
package devchuks.com.rechargeit;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.app.ListActivity;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class EtisalatData extends AppCompatActivity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_etisalat_data);
listView = (ListView) findViewById(R.id.list);
String[] values = new String[] {
"Smartphone Plans",
"Internet Bundles",
"Weekend Plans",
};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
}
You can define your listView.setOnItemClickListener like this to go to different activity for clicking different element.
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String item = listView.getItemAtPosition(position);
Toast.makeText(this,"You selected : " + item,Toast.LENGTH_SHORT).show();
if(position==0) {
// Do your code for clicking "Smartphone Plans" example
// startActivity(new Intent(getApplicationContext(),SmartphonePlans.class));
}
else if(position==1) {
// Do your code for clicking "Internet Bundles". example
// startActivity(new Intent(getApplicationContext(),InternetBundles.class));
}
else if(position==2) {
// Do your code for clicking "Weekend Plans". example
//startActivity(new Intent(getApplicationContext(),WeekendPlans.class));*/
}
});
onItemClick will be called whenever any of the list items are clicked. The position will be the position of the view in the Adapter.
Please refer -
How to handle the click event in Listview in android?
Thanks
Sriram
try this:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = values[position];
if(text.equals("Smartphone Plans")){ //your specific list item text
Intent i = new Intent(MainActivity.this, AnotherActivity.class);
i.putExtra("TEXT", text);
startActivity(i);
}
}
}
If this helps and is your concern
`
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String data = values[position];
switch(data){
case "Smartphone Plans":
// do somwthing
break;
// similarly for other two values.
}
}
});`
Below method give you a position of a clicked row. Take advantage of that and value from your array.
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Move your values array to member array or make it final to use
// in Anonymous class
final String selectedValue = values[position];
Intent intent = null
// Now add case and start activity
if("Smartphone Plans".equals(selectedValue)) {
intent = new Intent(EtisalatData.this, SmartPhonePlan.class);
}
else if("other Plans".equals(selectedValue)){
// other action
}
//... more cases and at the end start your activity if its not null
startActivity(intent);
}

Click on item of customlist-view is not working

This is my code for click on a customlistview. When I click on the header, it works but after header its not working. CustomAdapter is another class in my App where I have defined header and all variables of listview. Please help me to resolve this problem.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class ProbabilityConditional extends Activity {
String htmlcodefor_root = "&#x221A", htmlcodefor_multiply = "&#xD7",
htmlcodefor_divide = "&#xF7", htmlcodefor_underroot = "&#00B3";
ListView listView1;
String htmlcodefor_space = "&#8194", htmlcodefor_pi = "&#928",
htmlcodefor_largespace = "&#8195";
String htmlcodefor_implies = "&#x21D2";
String htmlcodefor_i = "&#7522";
String htmlcodefor_angle = "&#952";
String htmlcodefor_overline = "&#x203E", htmlcodefor_plusminus = "&#177";
// TextView txtv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// txtv = (TextView)findViewById(R.id.txtTitle);
// txtv.setText(Html.fromHtml("1.(constant)<sup><small>0</></> = 1"));
listView1 = (ListView) findViewById(R.id.listView1);
CustomAdapter.formula_one_custom_adapter_class_var = Html.fromHtml("1 ");
CustomAdapter.formula_two_custom_adapter_class_var = Html.fromHtml("2 ");
CustomItemCall formula_data[] = new CustomItemCall[] {
new CustomItemCall(CustomAdapter.formula_one_custom_adapter_class_var),
new CustomItemCall(CustomAdapter.formula_two_custom_adapter_class_var),
};
CustomAdapter adapter = new CustomAdapter(this,R.layout.listview_item_row, formula_data);
View header = (View) getLayoutInflater().inflate(R.layout.listview_header_row, null);
listView1.addHeaderView(header);
listView1.setAdapter(adapter);
listView1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
Toast.makeText(ProbabilityConditional.this,position + " " , Toast.LENGTH_LONG).show();
// When clicked, show a toast with the TextView text
if (position == 1) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalDiscrete.class));
} if (position == 2) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalContinuous.class));
}
}
});
}
}
make your listview focusable true add these line in your xml android:focusable="true"
and make other item of list make false android:focusable="false "
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
System.out.println(position);
Toast.makeText(ProbabilityConditional.this,position + " " , Toast.LENGTH_LONG).show();
// When clicked, show a toast with the TextView text
if (position == 1) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalDiscrete.class));
} if (position == 2) {
startActivity(new Intent(ProbabilityConditional.this,ProbabilityConditionalContinuous.class));
}
}
});
write code like this, simple way:-
ListView list;
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id)
{
//if in future you need to start a new activity
//then add below line also in your activity
Intent in = new Intent(MainActivity.this, SecondActivity.class);
startActivity(in);
}
});

ListView within ListView in android application

I am doing a project that currently requires a list and when a particular item from the list is clicked another list activity appears. Is there any solution as to how to move from one listview activity to another. I am currently using http://www.androidhive.info/2012/02/android-custom-listview-with-image-and-text/ as a reference for my ListView.
One solution would be:
Create the second ListView activity and implement the first ListActivity with a OnItemClickListener that opens the second ListViewActivity by using an regular Intent.
listView = (ListView) findViewById(R.id.mylistview);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position,
long arg3) {
Intent intent = new Intent(FirstListActivity.this, SecondListActivity.class);
Bundle bundle = new Bundle();
bundle.putString("pos", position);
intent.putExtras(bundle);
startActivity(intent);
}
});
UPDATE:
I have wrote an simple example list application. You may use it for insperation. The code that could open the Second list activity is included, but commented out. If you get this example to run, you are getting closer. Then you can try comment out the Intent code.
package com.adpog.listviewexample;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.app.Activity;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Find the ListView resource.
ListView mainListView = (ListView) findViewById( R.id.my_list );
// Set the Adapter as the ListView's adapter.
mainListView.setAdapter( new BaseAdapter(){
// Create and populate a List of planet names.
String[] planets = new String[] {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" };
#Override
public int getCount() {
return planets.length;
}
#Override
public Object getItem(int pos) {
return planets[pos-1];
}
#Override
public long getItemId(int pos) {
return 0;
}
#Override
public View getView(int pos, View view, ViewGroup viewgroup) {
if(view == null){
/**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/item_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text not set" />
</LinearLayout>
*/
view = View.inflate(getApplicationContext(), R.layout.row, null);
}
return view;
}
});
mainListView.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView< ? > arg0, View arg1, int arg2, long arg3) {
Log.d("ListView", "Pos: " + arg2 + ", long : "+arg3);
Toast.makeText(getApplicationContext(), "Test " + arg2, Toast.LENGTH_SHORT).show();
/* Alternative way; opens a new Activity
Intent intent = new Intent(this, SecondListViewActivity.class);
intent.putExtra("position", pos);
startActivity(intent);
*/
}
#Override
public void onNothingSelected(AdapterView< ? > arg0) {
}
});
/**
* Implement an action for each item click.
*/
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView< ? > arg0, View arg1, int arg2, long arg3) {
Log.d("ListView", "OnClickPos: " + arg2 + ", long : "+arg3);
Toast.makeText(getApplicationContext(), "Test " + arg2, Toast.LENGTH_SHORT).show();
}
});
}
}
api provides ExpandableListView . your requirement looks very close to it

Get spinner selected items text?

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();

Categories

Resources