Retrieving the bound value of a spinner - android

I want to get Selected Value of a spinner.
First, I created a STRING-ARRAY in res/values/string
<string-array name="location">
<item name="AUH">ABU DHABI</item>
<item name="AAN">AL AIN</item>
<item name="DMM">DAMMAM</item>
</string-array>
Spinner Definition in Layout:
<Spinner
android:id="#+id/spnOrigin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/location"/>
Now I need to complete the button click body, if user selects ABU DHABHI, he should return AUH.
GETSELECTITEM returns ABU DHABI, not the value behind this. If I try something like this, can this approach allow me to get NAME attribute?
String[] _location =getResources().getStringArray(R.array.location);
Button Handler:
bttProcess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
});

I don't believe the name attribute is valid on items of a string array.
I think your best bet is to set up another array to have the values in it. You can do ((AdapterView)getViewById(R.id.spnOrigin)).getSelectedItemPosition() then look up the relevant name from that other array.

Try to follow the exemple in the android developer website to get started using spinner
First your activity have to implement AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.
public class SpinnerActivity extends Activity implements OnItemSelectedListener
Second you need to register for the interface implementation by calling:
spinner.setOnItemSelectedListener(this);
Finally within "onItemSelected" method of that class, you can get the selected item:
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
use your string array like this
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="locations">
<item>ABU DHABI</item>
<item>AL AIN</item>
<item>DAMMAM</item>
</string-array>
</resources>

In this scenario where Spinner need to bind by KEY - VALUE PAIR List,
The spinner can be get values from
1. DATABASE
2. An static String Array.
3. By creating Bi- Resource String Array.
FOR 3rd Point:
If you need to bind spinner by resource String Array, u need to create two array. One which will hold KEY [NAMES Of Countries], Second Will contains VALUES [Short Code of Countries].
Than on Click Button,
bttProcess.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int position = spinner.getSelectedItemPosition();
Log.i("Code:","Selected Country Code: "+
getStringFromArray(R.array.locations_code, position ));
});
private String getStringFromArray(int id, int index) {
try {
String[] bases = getResources().getStringArray(id);
return bases[index];
}
catch (Exception e) {
return "";
}
}
RESOURCES would look like,
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="locations">
<item>ABU DHABI</item>
<item>AL AIN</item>
<item>DAMMAM</item>
</string-array>
<string-array name="locations_code">
<item>ABU</item>
<item>AL</item>
<item>DAM</item>
</string-array>
</resources>

Related

How to send value to server based on user clicked in spinner item in android?

I have a spinner in my activity which contain Operators name ,what I want when user selected item from spinner I want to send another value to server,like
if user select "Airtel" from spinner I have to send "AR" to server same like other items .how can I do that.
code:-\
<string-array name="operators">
<item>Select Operator</item>
<item>Aircel</item>
<item>Airtel</item>
<item>BSNL</item>
<item>Idea</item>
<item>Vodafone</item>
<item>MTNL Delhi</item>
<item>MTNL Mumbai</item>
</string-array>
here when user select item from above list I have to send value from below list according to above items.
<string-array name="Operators_Code">
<item>AC</item>
<item>AT</item>
<item>BS</item>
<item>ID</item>
<item>VD</item>
<item>MT</item>
</string-array>
A Spinner, similar to ListView, RecyclerView, etc., is an "adapter backed" View. That is, it gets the items to be displayed from an Adapter.
When you set the entries to be shown using android:entries="#array/operators, Spinner internally creates an Adapter with the supplied array items. This simple solution, however, doesn't support complex objects.
For your use case, you'll have to create a custom Adapter for your Spinner.
public class Operator {
String name;
String code;
#Override
public String toString() {
return name;
}
}
final List<Operator> operators = new ArrayList(7);
operators.add(new Operator("Select operator", null));
operators.add(new Operator("Aircel", "AC"));
operators.add(new Operator("Airtel", "AC"));
....
Next, set the adapter on your spinner:
final ArrayAdapter<String> operatorsAdapter = new ArrayAdapter<>(context, android.R.layout.simple_dropdown_item_1line, operators);
spinner.setAdapter(operatorsAdapter);
That's it. Now if you want to listen to user's selections, add a listener to your Spinner by:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
final Operator selectedOperator = operatorsAdapter.getItem(position);
final String selectedOperatorCode = selectedOperator.code;
// TODO: Send the selected operator to the server.
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});

Spinner Value not working

I am running into some trouble with my spinners. When every I select a value from them the spinner only takes the first value in the list.
For example I have a spinner with vales 1,2,3,4,5. When I select 4 the value taken from the spinner 1, this is the same if I select any of the other values.
Am I implementing the Spinner wrong? Or taking the values from the spinner wrong?
Spinner
<Spinner
android:id="#+id/heatSpinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/heat_title"
android:entries="#array/heat"/>
Array/Heat
<string-array name="heat">
<item>1</item>
<item>2</item>
<item>3</item>
<item>4</item>
<item>5</item>
</string-array>
Taking Values from Spinner
Spinner heat = (Spinner) dialog.findViewById(R.id.heatSpinner);
final String heatValue = heat.getSelectedItem().toString();
final int finalHeat = Integer.parseInt(heatValue);
I had a similar problem, I dunno if this way is the best way to do it but it worked for me.
You need to set a setOnItemSelectedListener for each spinner, inside this you will be then able to set the value of your variable to the items of the spinner.
So your spinner might look something like this, again this may not be the nicest looking approach but it worked for me anyway, hope it helps
final Spinner heat = (Spinner) dialog.findViewById(R.id.heatSpinner);
heat.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
final String heatValue = heat.getSelectedItem().toString();
int finalHeat = Integer.parseInt(heatValue);
db1.updateHeat(finalHeat, recipe_number);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Let's look at the 4ยบ block of code in your question.
Are you sure that
int servingSize = servings.getInt(0);
Is getting the value that you want?
And in
seekBar.setProgress(size);
what is this 'size' parameter? Are you sure that you are passing the right value to the setProgress() method? I didn't see this 'size' variable in your code.

get id of an item in spinner

I have this in my values xml file:
<string-array name="ben_country_list">
<item id="103">India</item>
<item id="210">Sri Lanka</item>
<item id="235">United Kingdom</item>
<item id="76">France</item>
<item id="216">Switzerland</item>
<item id="200">Singapore</item>
<item id="234">United Arab Emirates</item>
</string-array>
I want to get country's ID. I tried with below code:
final Spinner mBenCountry = (Spinner) findViewById(R.id.country_spinner);
mBenCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
final long ben_country = mBenCountry.getSelectedItemPosition();
final long ben_country2 = parentView.getSelectedItemId();
System.out.println(ben_country); // This one gives me position like 0,1,2...
System.out.println(ben_country2); // Output: same as above...
}
});
I want to get actual IDs of the selected item. For example, if user selects united kingdom then it should print 235. I don't want name of that item.
Thanks for any help.
Make a separate integer-array in XML for the ids:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer-array name="ben_country_ids">
<item>103</item>
<item>210</item>
<item>235</item>
<item>76</item>
<item>216</item>
<item>200</item>
<item>234</item>
</integer-array>
</resources>
Get the int array in code:
final int[] benCountryIds = getResources().getIntArray(R.array.ben_country_ids);
Using the position get the correct id from the array in onItemSelected:
int countryId = benCountryIds[position];
Once you have the selected item position, you can do this:
mBenCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
switch (id) {
case 103 :
System.out.println("India");
break;
case 210:
System.out.println("Sri Lanka");
break;
.
.
.
}
First of all, android string-array XML structure doesn't support key/value pairs for item entries. So, you have to use other data source etc.: database table, CSV file or whatever else. Then load data into some collection and then pass it to custom adapter.

Setting TextView with string from string array chosen in a ListView in Android

Alright, a quick summary. The app opens with a listView (populated by a string array), when you tap one of the items in the list it takes you to another listView (populated by a string array) with items associated with the first item you tapped. In the second listView, i'd like to tap on an item and have it display a textView with associated items from another string array. I have the first two listViews working so far, but can't get the textView to work. I've banged my head over this for two days now and am getting very frustrated. Could you please help?!
Here is my strings xml file:
<string-array name="topics">
<item>Idioms</item>
<item>Travel</item>
<item>Small Talk</item>
<item>Tips</item>
<item>App Data</item>
</string-array>
<string-array name="idioms">
<item>Cash Chow</item>
<item>No Spring chicken</item>
</string-array>
<string-array name="travel">
<item>Asking for Change</item>
<item>Bus and Train Schedule</item>
</string-array>
<string-array name="idioms_description">
<item>A cash cow is a blah blah blah</item>
<item>No spring chicken means blah blah blah</item>
</string-array>
<string-array name="travel_description">
<item>This is a test for Asking for change</item>
<item>This is a test for Bus and train schedules</item>
</string-array>
And here is my getIntent and place where I should setText. I left it blank because everything I have tried until now has failed miserably, I just don't know how to get the proper string from the array that was selected.
public class DetailLanguagePoints extends Activity{
private int position;
private TextView mLanguagePoint;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_view);
mLanguagePoint = (TextView) findViewById(R.detail.languagepoints);
Bundle extras = getIntent().getExtras();
//int[] arrayIds = new int[]{R.array.idioms, R.array.travel};
position = extras.getInt("listposition");
int[] stringarrayIds = new int[]{R.array.idioms_description, R.array.travel_description};
String[] subTopics = getResources().getStringArray(stringarrayIds[position]);
String description = subTopics[position];
final String TAG = "MyActivity";
Log.d(TAG,description);
mLanguagePoint.setText(description);
}
}
I found what the problem was with the null exception error, I didn't call findViewById() after setcontentView(). I did that and it solved the problem, it is now working!! Thank you to all those who provided suggestions!!
use this code mPosition = i.getIntExtra("listposition");
instead of this mPosition = i.getIntExtra("listposition", 0);
So you only want to set subTopics into a ListView?
ListView listView = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, subTopics);
listView.setAdapter(adapter);
Otherwise please post how you are failing with any logcat errors.
What do you want to display in the TextView? The two sub-items separated by a new line? If so then just change mLanguagePoint.setText() to mLanguagePoint.setText(subTopics[0] + "\n" + subTopics[1])
first initialize mLanguagePoint. try something like
then on second listview add onItemClickListener()
public void onItemClick(AdapterView<?> arg, View view, int position,long id) {
mLanguagePoint.setText(subTopics[position]);
}

spinner adding string array on item selection how can get item related value in android

i am developing one spinner this spinner i am string array
spinner = (Spinner)this.findViewById(R.id.mlg);
final CharSequence[] itemArray =getResources().getTextArray(R.array.RectBeam);
final List<CharSequence> itemList =new ArrayList<CharSequence>(Arrays.asList(itemArray));
adapter = new ArrayAdapter(this,android.R.layout.simple_spinner_item,itemList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new 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();
}
............................
<string-array name="RectBeam">
<item value="3000000" > Steel</item></string-array>
this is the spinner related string array i am get the spinner item i am using parent.getItemAtPosition(pos).toString(),done my problem is particular item value how can get
example : steel----------->3000000
I am not sure either Spinner allow that attribute value in XML String or not but your problem can be solved like this.
Create two arrays in your array.xml file like:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="items">
<item>Nokia 1200</item>
<item>Nokia 1600</item>
<item>Nokia 5130</item>
</string-array>
<string-array name="values">
<item>1000</item>
<item>2000</item>
<item>5000</item>
</string-array>
</resources>
Now load first array in your adapter and store the second one in other Array to hold values of items as:
String items [] = getResources().getStringArray(R.array.items);
String values [] = getResources().getStringArray(R.array.values);
And you can simply get the respective item name and value in your onItemSelected() method like this:
String item = parent.getItemAtPosition(pos).toString();
String value = values [pos];

Categories

Resources