I have a custom spinner in my Android app;
public void onDataChange(DataSnapshot dataSnapshot) {
resultList.clear();
listSpinner.clear();
listSpinner.add("All teams");
for(DataSnapshot matchSnapshot : dataSnapshot.getChildren()) {
matches match = matchSnapshot.getValue(matches.class);
resultList.add(match);
listSpinner.add(matchSnapshot.child("homeTeam").getValue().toString());
listSpinner.add(matchSnapshot.child("awayTeam").getValue().toString());
}
listSpinner = new ArrayList<String>(new LinkedHashSet<String>(listSpinner));
spinnerTitles = listSpinner.toArray(new String[0]);
CustomAdapter adapterSpin = new CustomAdapter(getContext(), spinnerTitles, spinnerImages, spinnerPopulation);
spinner.setAdapter(adapterSpin);
resultList.sort(Comparator.comparing(matches::getDateFormatted).thenComparing(matches::getTime));
resultList adapter = new resultList (getActivity(), resultList);
listViewResult.setAdapter(adapter);
}
This works great for populating the spinner, but when I then attempt to use the spinner, and select a item in the list I keep getting;
IndexOutOfBoundsException: Index: 2, Size: 0
The error is pointing to the forth line below;
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position,long id ) {
if(++check > 1) {
String getSpinTeam =(String)parent.getSelectedItem();
....
}
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
When I debug and check the values of what is being returned I can still see 2 records in the array, so I'm confused as to why it errors saying that the Size is 0 when it clearly is telling me something in the debugger.
My question is, this is the first custom spinner I've built, how I have handled the setOnItemSelectedListener is that the common way of handling returned data from the spinner (it is for the built in non-custom version) or have I missed something?
Any help appreciated.
I think the error is here:
String getSpinTeam =(String)parent.getSelectedItem();
It must be:
String getSpinTeam =(String)parent.getItemAtPosition(position);
Maybe you should try this, replace:
String getSpinTeam =(String)parent.getSelectedItem();
By
String getSpinTeam = spinnerTitles.get(position);
Hope this help
Related
I have a form using spinner, the data spinner I get from database using retrofit 2 , I have a field id_fish and fish_name, I would like to show fish_name but id_fish that saved in database.
I success to show the fish_name in android spinner but when i want to save the form into database is fish_name ,
how to save id_fish while the displayed in spinner is fish_name
example as in html :
<select>
<option value="001">Tuna</option>
<option value="002">Shark</option>
<option value="003">Dolphin</option>
<select>
This is My Function:
private initSpinner()
{
List<DataFish> dataFish= response.body().getData();
List<String> idFish = new ArrayList<String>();
List<String> fishName = new ArrayList<String>();
for (int i = 0; i < dataFish.size(); i++){
idFish.add(dataFish.get(i).getId_fish());
nameFish.add(dataFish.get(i).getFish_name());
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(LelangActivity.this,
android.R.layout.simple_spinner_item, nameFish);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerFish.setAdapter(adapter);
}
This is spinner SetOnclickListener :
spinnerFish.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String fishName= parent.getItemAtPosition(position).toString();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
If the fish name is unique filed you can search on dataFish to get the equal id. I mean in onItemSelected write something like this:
for (DataFish data : dataFish) {
if (data.getFish_name().equls(fishName) {
data.getId_fish(); //here is your fish id
}
}
EDIT: If your fish name filed is not unique and it's possible that two fish with the same name has the different id, you must implement custom adapter for spinner and in getDropDownView method define which fish is selected. for implement custom adapter you can see here
I would like to run getKey() for the item User selected in the listview, so that I can use this key to determine where to take the User, I tried a lot of stackoverflow solutions but failed with many different errors...
Your help will be much appreciated, thank you so much!
Details as below:
Firebase data poplulate to Adapter Listview -- No error
UserId = FirebaseAuth.getInstance().getCurrentUser().getUid();
final DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference gameInfoRef = rootRef.child("user").child(UserId).child("gameInfo");
gameInfoRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ListView lv_SelectGame = findViewById(R.id.lv_SelectGame);
GameList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Game game = ds.getValue(Game.class);
GameList.add(game);
}
History_SelectGameAdapter adapter = new History_SelectGameAdapter(ida_History_SelectGame.this, GameList);
lv_SelectGame.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
// Getting Post failed, log a message
}
});
User clicks Listview item, return the key (generated by push() previously in other activity, stored in firebase) of that specific game -- Please advise for the solution, thanks!
Firebase Data: (each item in the listview is shown by date)
gameInfo
-LMIdDTDiUd3ajVVMdzC
gameDate: "2018-09-01"
gameMode: "SomeMode"
-LMOGEUbCTsaeywPICqi
gameDate: "2018-09-06"
gameMode: "SomeMode"
-LMQfCQ7TO21WP3qW7v3
gameDate: "2018-09-15"
gameMode: "SomeMode"
Now this is the part that I don't know how to wrtie, thanks!
(When I click the Listview item, the Toast is shown without any error, but I have no idea how to get the position and run getKey() based on it)
lv_SelectGame.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
ListView lv_SelectGame = findViewById(R.id.lv_SelectGame);
Toast.makeText(ida_History_SelectGame.this, "getKey() of this item", Toast.LENGTH_SHORT).show();
}
You want the ids like LMIdDTDiUd3ajVVMdzC, LMOGEUbCTsaeywPICqi... ?
Then what you have to do is add a new attribute to your object Game key (if you don't have it).
And when you get the data from Firebase, get the id and add it to the object Game:
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Game game = ds.getValue(Game.class);
String idYouWant = String.valueOf(ds.getKey());
//We add to the object game
game.setKey(idYouWant)
GameList.add(game);
}
Finally you just have to get it from your array GameList, something like this:
lv_SelectGame.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
Game game = GameList.get(position);
String key = game.getKey();
Toast.makeText(ida_History_SelectGame.this, "getKey() of this item", Toast.LENGTH_SHORT).show();
}
Here in this code i have added pincode numbers from 600000 to 600113 in the spinner but i want the first position to be just empty. When the user clicks only then the item should be shown. Please see my code -
final String[] myarray=new String[114];
for(int i=0;i<114;i++)
{
myarray[i]=String.valueOf(a);
a++;
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(MainActivity.this,
android.R.layout.simple_spinner_dropdown_item,myarray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
addnum_spinner.setAdapter(adapter);
lv.setOnItemClickListener(itemClickedListener);
//Spinner click
addnum_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// your code here
String value = myarray[position];
//
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
add this property to your spinner in xml and try if that works
android:prompt=""
I don't know if this is the right way but what about just adding the empty string before the for loop as the first item and then you just have to handle the user clicking on the empty item in your Listener. Something like
final String[] myarray=new String[115];
myarray[0] = ""
for(int i=1;i<115;i++)
{
myarray[i]=String.valueOf(a);
a++;
}
I know this question is old, but I'm adding a solution. I found this out on accident, as I DIDN'T want a blank default value, but there was one.
If using an ArrayAdapter, I found that attaching the adapter to an empty ArrayList, and THEN filling it left a blank initial value.
Filling the ArrayList first, then attaching the ArrayAdapter removed the blank default value.
Obviously, if not using an ArrayAdapter, using the prompt, or setting the first Spinner item as <item></item> with nothing in between in the XML should work.
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
Newbie question. I'm using a SimleCursorAdapter to populate a spinner from an SQLite table, as shown in the Android dev docs:
Spinner list=(Spinner)findViewById(R.id.cboModel);
SimpleCursorAdapter ModelAdapter = new SimpleCursorAdapter(this,
android.R.layout.simple_spinner_item, model,
new String[] {"Drug"},
new int[] {android.R.id.text1});
ModelAdapter.setDropDownViewResource(
android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(ModelAdapter);
list.setOnItemSelectedListener(onModelSelect);
I've set up a listener, but I can't figure out how to get the selected item text, it pulls up the SQLiteCursor, not the actual text in the spinner.
private AdapterView.OnItemSelectedListener
onModelSelect= new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?>
parent, View view, int position, long id) {
ModelName = parent.getSelectedItem().toString();
android.util.Log.w("OnItemSelect.cboModel", ModelName);
}
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
};
Google turns up the question on several message boards, but no answers, so it appears to be a common newbie question. It may be painfully obvious to some, but if you could point me in the right direction I would appreciate it. Thank you.
Since the selected item is a Cursor, you can easily get the value by calling getString with the index of the column in the original database query that you used to populate the Spinner.
String spinnerString = null;
Cursor cc = (Cursor)(yourSpinner.getSelectedItem());
if (cc != null) {
spinnerString = cc.getString(
cc.getColumnIndex("Drug"));
}
This technique definitely works when the Spinner is populated from the database. I have not tried it with a resource array.
Figured it out... get the id, then make a DB query:
String id_string = String.valueOf(id);
thismodel=Pkmodel.getById(id_string, dbModel);
ModelName=thismodel.getDrug();