get id of an item in spinner - android

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.

Related

How to create an edit delete dialog when long clicking on a listview item. Android

So I have a custom list view which is populated with Name and phone number. I want to be able to long click on an item in the list view which will then popup a dialog which will allow me to edit the fields or delete the row. How can I do this? Currently I have the code below which just deletes the row if you longClick. I presume I have to create a Dialog class and then call it within the OnLongItemClickLister? I have no idea how to do this however, any help would be great ty.
lvCustomList.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
ContactListItems contactListItems = (ContactListItems)arg0.getItemAtPosition(arg2);
String id = contactListItems.getID();
String delQuery = "DELETE FROM PHONE_CONTACTS WHERE id='"+id+"' ";
sqlHandler.executeQuery(delQuery);
showlist();
return false;
}
});
First you have to create new XML file at folder menu under the folder res at your project. Name it as main_popup_menu and add this code:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/delete"
android:title="#string/delete"
android:onClick="doDelete"/>
</menu>
And then, add this to your onItemLongClickListener:
PopupMenu p = new PopupMenu(ViewDiaryActivity.this, view);
p.getMenuInflater().inflate(R.menu.main_popup_menu, p.getMenu());
p.show();
I've tried it, and it showed the popup delete button. :D

Retrieving the bound value of a spinner

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>

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];

Populating spinner directly in the layout xml

Is it possible to populate the options of a Spinner right in the layout xml? This page suggests I should use an ArrayAdapter? It seems awkward not being able to do it..
I'm not sure about this, but give it a shot.
In your strings.xml define:
<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>
In your layout:
<Spinner
android:id="#+id/spinner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:drawSelectorOnTop="true"
android:entries="#array/array_name"
/>
I've heard this doesn't always work on the designer, but it compiles fine.
Define this in your String.xml file and name the array what you want, such as "Weight"
<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>
and this code in your layout.xml
<Spinner
android:id="#+id/fromspin"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:entries="#array/Weight"
/>
In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.
a = (Spinner) findViewById(R.id.fromspin);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
R.array.weight, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
a.setAdapter(adapter);
a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
if (!b.getText().toString().isEmpty()) {
float value1 = Float.parseFloat(b.getText().toString());
float kg = value1;
c.setText(Float.toString(kg));
float gram = value1 * 1000;
d.setText(Float.toString(gram));
float carat = value1 * 5000;
e.setText(Float.toString(carat));
float ton = value1 / 908;
f.setText(Float.toString(ton));
}
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
});
// Inflate the layout for this fragment
return v;
}
In regards to the first comment: If you do this you will get an error(in Android Studio). This is in regards to it being out of the Android namespace. If you don't know how to fix this error, check the example out below. Hope this helps!
Example -Before :
<string-array name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>
Example - After:
<string-array android:name="roomSize">
<item>Small(0-4)</item>
<item>Medium(4-8)</item>
<item>Large(9+)</item>
</string-array>

How to get Spinner value?

In Android, I am trying to get the selected Spinner value with a listener.
What is the best way to get the spinner's value?
Spinner mySpinner = (Spinner) findViewById(R.id.your_spinner);
String text = mySpinner.getSelectedItem().toString();
The Spinner should fire an "OnItemSelected" event when something is selected:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object item = parent.getItemAtPosition(pos);
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Say this is your xml with spinner entries (ie. titles) and values:
<resources>
<string-array name="size_entries">
<item>Small</item>
<item>Medium</item>
<item>Large</item>
</string-array>
<string-array name="size_values">
<item>12</item>
<item>16</item>
<item>20</item>
</string-array>
</resources>
and this is your spinner:
<Spinner
android:id="#+id/size_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:entries="#array/size_entries" />
Then in your code to get the entries:
Spinner spinner = (Spinner) findViewById(R.id.size_spinner);
String size = spinner.getSelectedItem().toString(); // Small, Medium, Large
and to get the values:
int spinner_pos = spinner.getSelectedItemPosition();
String[] size_values = getResources().getStringArray(R.array.size_values);
int size = Integer.valueOf(size_values[spinner_pos]); // 12, 16, 20
Yes, you can register a listener via setOnItemSelectedListener(), as is demonstrated here.
View view =(View) getActivity().findViewById(controlId);
Spinner spinner = (Spinner)view.findViewById(R.id.spinner1);
String valToSet = spinner.getSelectedItem().toString();
If you already know the item is a String, I prefer:
String itemText = (String) mySpinner.getSelectedItem();
Calling toString() on an Object that you know is a String seems like a more roundabout path than just casting the Object to String.
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();

Categories

Resources