Setting ID for Spinner items - android

I have an array of Strings I'm populating a Spinner object with. However, I'd like to attach an ID to each element of the Spinner, so when the user selects an item, I have its ID to use to save to some other piece of data. How can I do this?

Create a class StringWithTag and use in place of the string name in the list like so :-
public class StringWithTag {
public String string;
public Object tag;
public StringWithTag(String stringPart, Object tagPart) {
string = stringPart;
tag = tagPart;
}
#Override
public String toString() {
return string;
}
}
in the add items to spinner part :-
List<StringWithTag> list = new ArrayList<StringWithTag>();
list.add(new StringWithTag("Oldman", "12345"));
list.add(new StringWithTag("Umpire", "987654"));
list.add(new StringWithTag("Squad", "ABCDEE"));
ArrayAdapter<StringWithTag> adap = new ArrayAdapter<StringWithTag> (this, android.R.layout.simple_spinner_item, list);
....
....
in the listener :-
public void onItemSelected(AdapterView<?> parant, View v, int pos, long id) {
StringWithTag s = (StringWithTag) parant.getItemAtPosition(pos);
Object tag = s.tag;
}
voila!
}

What do you mean by id. You can use ArrayAdapter to populate the Spinner. When item is selected just get the element from the adapter and save the data you want.
Spinner spinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<MyObject> adapter = ... // initialize the adapter
adapter.setDropDownViewResource(android.R.layout.some_view);
spinner.setAdapter(adapter);
and when item is selected
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
MyObject selected = parent.getItemAtPosition(pos);
// save any data relevant with selected item
}
If you are storing your data in db you can use CursorAdapter and in onItemSelected to fetch the selected item id from the cursor.

I don't think you can attach an arbitrary ID to elements of a text array resource, if that's what you're using.
I think the simplest way to attach such an ID would be to either hard-code (if you're using a static text resource) or dynamically build (if you get the strings at runtime) a mapping from (String position in array)->(primary key).
EDIT: On the other hand, Mojo Risin has a point - you should check to see if the CursorAdapter API already does what you need for you.

Andrew Hi, it's been a long time but it's worth to write.
You can set a tag for each row when you'r inflating spinnerLayout in SpinnerAdapter:
spinnerView = inflater.inflate(spinnerLayout, parent, false);
spinnerView.setTag("Your Tag");
And then you can get the tag with:
yourSpinner.getSelectedView().getTag();

I think The best solution is to add one more spinner and fill it with the ids but make the visibility of it to gone

Related

Check all of adapter elements in ListView

I have CustomAdapter which I am using for populating ListView with some data.
Each element in ListView has two variables. For each listview (in onItemClick method) I must check this variables and If they are the same - do some code and If they are different - do another code, for example Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
So I have tried this:
private List<SomeItem> items = new ArrayList();
//items were created
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0; i<=items.size(); i++) {
SomeItem item = items.get(position);
String tmpCI = item.getFirstVariable();
String tmpPCI = item.getecondVariable();
if (!tmpCI.equals(tmpPCI)) {
//some code
} else {
Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
}
}
}
});
But all of my listview elements have values of the first element in those two variables.
So how can I do something like item.next(); for validating all of items in listview?
UPD:
Sorry, I will provide more information about what I am doing after checking variables of listview items for understanding my issue.
I have one more adapter:
SomeAnotherAdapter adapterPr = new SomeAnotherAdapter(this, R.layout.list_tem_another, itemsAnother);
and one more listview:
listViewAnother.setAdapter(adapterPr);
First of all I understood, that first variable should be from first listview and the second variable from another listview.
In this listViewAnother I have many items, which has some "id". For example 1st, 5th and 20th elements have id 90 and other elements have id 100.
We can say, that items from the first listview also have "id".
So I must check if(first variable = second variable) and then show in listViewAnother only items that have id which equals ID from clicked item in listView.
I tried: adapterPr.remove(item2); but then I understood, that I need all of items because I can go back to listView and press another item which will need those removed elements.
Now, hope I provided full information and you will be able to help me improve my code.
Do you need to perform the check on every element of the adapter when you click on one element of the adapter? If not, you don't need a loop. If you do, your loop should be iterating over the original list, and does not need adapter position at all.
In general when using adapters and lists, you should use the adapter's position and the adapter's data set to perform any tasks. It's not good practice to use the adapter position to get an item from the original list.
Simply set one onItemClickListener which gets the corresponding item from the adapter, and do what you need to from there:
private List<SomeItem> items = new ArrayList();
//items were created
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SomeItem item = adapter.getItem(position);
String tmpCI = item.getFirstVariable();
String tmpPCI = item.getecondVariable();
if (!tmpCI.equals(tmpPCI)) {
//some code
} else {
Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
}
}
});

Custom ListView not getting updated

I'm developing a currency exchange app and I'm having some problems with updating my ListView after extracting the rates from an API.
Ignore the flags, I just put whatever files I had to test the solution
On the start of my activity, I am defining:
final ArrayList<ItemData> list = new ArrayList<ItemData>();
final String[] web = {
"EUR", "JPY", "USD", "GBP"
};
final Integer[] imageId = {R.drawable.austria, R.drawable.bangladesh, R.drawable.benin, R.drawable.uk};
private static String _spinnerData;
public static String test;
public static synchronized String getCurrentSpinner(){
if (_spinnerData == null) {
String _spinnerData;
}
return _spinnerData;
}
And onCreate() is defined as:
... not important ...
Spinner spin = (Spinner) findViewById(R.id.spinner_complist);
final SpinnerAdapter adapter1 = new SpinnerAdapter(this,
R.layout.spinner_layout, R.id.txt, list);
spin.setAdapter(adapter1);
spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
ItemData item = (ItemData) (parentView.getItemAtPosition(position));
Log.i("item_1", item.getText());
String spinnerData = getCurrentSpinner();
spinnerData = item.getText();
}
I then have a custom Adapter to put the flags+name, where the name is a textview.
Afterwards, I get my conversion rate from an API, through a function getRate() that is working.
On the custom adapter, I have overriden the getView method:
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.mylist, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.itemName);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
imageView.setImageResource(imageId[position]);
String currency;
txtTitle.setText(web[position]);
String spinnerData= getCurrentSpinner();
if (spinnerData!=null) {
currency=spinnerData;
getRate(currency, web[position], txtTitle);
}
return rowView;
}
So, in getRate I obtain a String from each row of the ListView and replace it by the value in another coin.
My problem is: If I write getRate("EUR",web[position],txtTitle), everything works as intended.
However, if I put the code as it is, it just doesn't update my ListView. I put a breakpoint and currency is "EUR", so it should be equivalent to what I had by hardcoding the string.
I think that probably the ListView isn't getting properly updated, or the function is making some callback that is replacing my TextViews with the original values.
Any ideas?
Thanks in advance,
Two things stand out to me.
First, this block:
public static synchronized String getCurrentSpinner(){
if (_spinnerData == null) {
String _spinnerData;
}
return _spinnerData;
}
This doesn't really make sense. It reads "if the static scoped _spinnerData is null, create another locally scoped String also called _spinnerData and do nothing with it, then return the statically scoped instance."
And second, this logic:
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
ItemData item = (ItemData) (parentView.getItemAtPosition(position));
Log.i("item_1", item.getText());
String spinnerData = getCurrentSpinner();
spinnerData = item.getText();
}
This reads "create a temporary string called spinnerData that is initialized with the return value of getCurrentSpinner() then immediately replace it with the value of item.getText() then throw the whole thing away (because it's never used thereafter)".
It appears to me you have a misunderstanding in how references work. I think what you are trying to do is save the current spinner selection and use that in your getView().
If that's the case, you would do something like this:
private String _spinnerData; // Does not need to be static
// In onItemSelected
ItemData item = (ItemData) (parentView.getItemAtPosition(position));
Log.i("item_1", item.getText());
_spinnerData = item.getText(); // Save the last item selected
// In getView()
// Call this method with the last known spinner selection
getRate(_spinnerData, web[position], txtTitle);
I would have to assume you are new to Java and don't fully understand how references and scope work. Is that a fair assumption? If so, I strongly suggest you take a step back from Android and work on getting more familiar and comfortable with Java before proceeding. Android is complicated enough without having to figure out the language as you go as well.
Hope that helps!
I think you have some problems with the flow of the data in your Activity.
The getView in the listview should return a view with the populated data from a data source that has the data.
I would advice changing to have something like:
Snippet position selected -> call web API to get any data that you need -> when is returned add it to a list of data that is being displayed on the listview -> then call in the adapter of the listview notifyDataSetChanged()
I would recommend this article for more information about using listviews: http://www.vogella.com/tutorials/AndroidListView/article.html

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) {
}
});

How to Disable the 2nd Spinner Item Which is selected Already in 1st Spinner in Android

I want to Convert the Languages. So i am using two Spinners one is "From Language" and Another one is for "To Language". If One Language is Selected in "From Language" Spinner, it shouldn't display (or it should be disabled) in 2nd spinner. how can i achieve it?
Ex. if i Select English in 1st Spinner, 2nd Spinner Shouldn't display English in its dropdown.
This is may not be the best way try this.
ArrayList<String> languages = new ArrayList<>();
languages.add("English");
languages.add("Hindi");
languages.add("Telugu");
languages.add("Tamil");
languages.add("Kannada");
languages.add("Malayalam");
// make a array list of languages
String option1 = null;
Spinner spinnerOption1 = (Spinner) findViewById(R.id.spinner1);
final ArrayAdapter<String> adapterOpton1 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages);
spinnerOption1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption1.setAdapter(adapterOpton1);
spinnerOption1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
option1 = adapterOpton1.getItem(position);
}
});
int selectedIndex;
for (String item : languages) {
if (item.equals(option1)) {
selectedIndex == languages.indexOf(item);
}
}
ArrayList<String> languages2 = languages;
languages2.remove(selectedIndex);
Spinner spinnerOption2 = (Spinner) findViewById(R.id.spinner2);
final ArrayAdapter<String> adapterOption2 = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, languages2);
spinnerOption2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerOption2.setAdapter(adapterOption2);
Explanation:
lets create a arraylist with languages
bind it to the adapter on the spinner, on selection to the spinner one keep a track of that selection, then find the index of the selection in the arraylist.
create second arraylist with the same languages and find and remove the user selected item, create an adapter and bind the data.
Hope it helps.
Use Hashmaps it will be easier. Create an Adapter that uses Key Values for populating adapter.
This is a snippet I found from another link on how to do that, in case you are not familiar
public class HashMapAdapter extends BaseAdapter {
private HashMap<String, String> mData = new HashMap<String, String>();
private String[] mKeys;
public HashMapAdapter(HashMap<String, String> data){
mData = data;
mKeys = mData.keySet().toArray(new String[data.size()]);
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int position) {
return mData.get(mKeys[position]);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
String key = mKeys[pos];
String Value = getItem(pos).toString();
//do your view stuff here
return convertView;
}
}
Credit What adapter shall I use to use HashMap in a ListView
Now for your management of the adapters.
LanguageOneMap.put (all your keys 0-whatever) value (english-whatever)
LanguageTwoMap.put (same as above)
LanguageAllMap.put (same as above)
Adapter 1 selects Language Callback(languageSelectedFromOneKey){
LanguageTwoMap.clearAll
LanguageTwoMap.put (all again)
LanguageTwoMap.remove(languageSelectedFromOneKey)
LanguageTwoAdapter.notifyDataSetChanged()
}
The above is just pseudo code meant to give the idea, not exact copy and paste. Hope that is enough to get you going. There are many ways to skin this cat, you could even use the same list for both adapters. Then when one is selected from one or the other, set a property of "selectedOtherLanguage" in the opposite adapter, then in the GetView method if data.get(pos) == selectedFromOtherListItem return, don't draw.
Many ways to do this, just a matter of how you want to do it. Goodluck.

Getting values from the spinner inside the list

I've create the android application program using list adapter that extends the list activity....Inside the list i am having the spinner.. how can i get the value from the spinner inside the list..tell some idea.Thanks in Advance..
try this ::
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String str = mSpinner.getSelectedItem().toString();
// getting item id by this
myId = parent.getItemAtPosition(position).toString();
}
I am assuming you only have one spinner in the list. In that case you can get the view by id of that spinner and fetch the value. If there are more than one then you need to add different tags to them while adding them to the list (in ListAdpater) and get these views from tag and get the value.

Categories

Resources