I have a user data lie names etc. coming from database which is being populated to AutoCompleteTextView but the position in ItemCLickListener is of the position as displayed in the auto complete list.
I want the array index, and getting string from the adapter won't work because the same names can be there too.
Update
eg. In the database I have 4 entries abc, xyz, abc, pqrq along with some other data in other fields. These names are stored in an array.
So when I click abc, I want the other data to be fetched as well which could be done only if I know the array index of selected item.
Help!
Solution :
Customise the auto_complete_tv_adapter for its items.
Adapter list items will be model wich will hold the name with others data.
Any selected item you will have data model with all other values handy.
sample : https://www.androidcode.ninja/android-autocompletetextview-custom-arrayadapter-sqlite/
Instead of using an array of Strings, you should create an array with custom objects in it.
First, create a new class like this:
class CustomObject {
public long id;
public String name;
public CustomObject(long id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Then, you get data from your database, which will be Strings, instead of storing only a String you can also add a unique id to the array which we will we use later.
So, for example, you can fill the array like this:
// this array should contain the items from your database, and a unique id
final CustomObject[] items = { new CustomObject(0, "test"), new CustomObject(1, "test"),
new CustomObject(2123123, "another name")};
Then make your AutoCompleteTextview click detector look like this:
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject customObject = (CustomObject) parent.getItemAtPosition(position);
int index = -1;
for (int i = 0; i < items.length; i++) {
if (items[i].id == customObject.id) {
index = i;
break;
}
}
// now we have your index :)
Toast.makeText(MainActivity.this, "Your index = " + index,
Toast.LENGTH_SHORT).show();
}
});
And that's it, there is the index you need. Note that for large arrays, this method will be slow.
Related
I have a CardView containing a spinner. The spinner contains number from 0 to 5 for user to choose. Each CardView itself has a unique ID associated with it. For example say that now I have two cards, card A with ID of 1 and card B with ID of 2. Depending on the value selected from the spinner I will create an array. For example card A has value of 3 and card B has value of 2, the final array will then look like [1,1,1,2,2], and if the spinner of the value of card A is changed to 0, then the array will be updated to [2,2].
I can now create separated array for each cards, but I am not sure how to add the arrays together or update the arrays based on the final values in each spinners
What I have now:
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final ChooseServiceList chooseServiceList1 = chooseServiceList.get(position);
// Spinner Drop down elements
List<Integer> categories = new ArrayList<Integer>();
categories.add(0);
categories.add(1);
categories.add(2);
categories.add(3);
categories.add(4);
categories.add(5);
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<Integer>(context, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.spinnerServiceNum.setAdapter(dataAdapter);
holder.spinnerServiceNum.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
Integer serviceCount = Integer.parseInt(item);//spinner value
Integer serviceId = chooseServiceList1.getServiceId();//ID associated with card
List<Integer> list = new ArrayList<Integer>();
for(int service = 1; service<=serviceCount; service++) {
list.add(serviceId);
if(service == serviceCount){
//final numbers of each ID that should be add into array
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//do nothing
}
});
}
I can print out the separate arrays now e.g. [1,1,1], [2,2], but how should I update and combine them after spinner is selected? I tried putting them in a shared preference but this will only make the final array [2,2] the shared preference.
Make the list definition final and move it to the outer class. So remove this line...
List<Integer> list = new ArrayList<Integer>();
And instead, at the top of your code, write...
final ChooseServiceList chooseServiceList1 = chooseServiceList.get(position);
final List<Integer> list = new ArrayList<Integer>();
How to get the checked item id (custom id, not the position or name of the selected item -in my case order id i need to retrieve) in a custom list view with multiple selections in android.
I have Order name and Order id from json and its populated in custom list view ,In the custom list view i have text view and check box but how to get the Orderid's of the selected/checked Orders.
I have a button when i click the button i need to retrieve the id not the name or position , in my case i need order id to be retrieved
You just need to call ListView.getCheckedItemIds(). It will return a long[] with all checked ids.
There is also ListView.getCheckedItemPositions() which will give you all checked positions.
Make sure you set ListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE) in onCreate() or whereever you set up your views (or in layout xml).
To get the checked values you just need to do this:
SparseBooleanArray checked = mListView.getCheckedItemPositions();
for (int i = 0; i < checked.size(); i++) {
if (checked.valueAt(i)) {
int pos = checked.keyAt(i);
Object o = mListView.getAdapter().getItem(pos);
// do something with your item. print it, cast it, add it to a list, whatever..
}
Jerry, set your order object as tag to the view which has selection event [CheckBox, TextView, Row view], when user select item you can get selected order object from tag and you can get any member of that object(order). for ex.
Order Object
Order {
int id;
String name;
boolean isSelected;
//add getters and setters
}
void getview(...) {
View v = //inflate view
CheckBox cb = (CheckBox) v.findViewById(..);
cb.setTag(yourlist.get(position));
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
((Order) buttonView.getTag()).setSelected(isChecked);
}
});
}
I Solved and got the OrderId by using below code , this worked for me and i could retrieve the custom ORDERID which i passed to the list
int isSelectedOrderNumber=0;
mOpenOrdersSelected = new ArrayList<OpenOrders>();
StringBuffer sb = new StringBuffer();
Iterator<OpenOrders> it = mOpenOrders.iterator();
while(it.hasNext())
{
OpenOrders objOpenOrders = it.next();
//Do something with objOpenOrders
if (objOpenOrders.isSelected()) {
isSelectedOrderNumber++;
mOpenOrdersSelected.add(new OpenOrders(objOpenOrders.getOrderID(),objOpenOrders.getOrderName()));
sb.append(objOpenOrders.getOrderID());
sb.append(",");
}
}
//Below Condition Will Check the selected Items With parameter passed "mMAX_ORDERS_TOBEPICKED"
if(isSelectedOrderNumber<1){
ShowErrorDialog("Please Select atleast One order");
return;
}
if(isSelectedOrderNumber>mMAX_ORDERS_TOBEPICKED){
ShowErrorDialog(" Select Maximum of "+mMAX_ORDERS_TOBEPICKED+ " Orders only to process");
return;
}
Log.d(MainActivity.class.getSimpleName(), "cheked Order Items: " +sb);
Toast.makeText(getApplicationContext(), "cheked Order Items id:" +sb, Toast.LENGTH_LONG).show();
I'm building a dialog with a spinner. When the dialog is done, it calls a method of the parent activity with a string argument - the argument being the string value that was selected.
My current approach:
I'm setting up the spinner's array adapter like so:
ArrayAdapter<String> adapter =
new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item,
categoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mySpinner.setAdapter(adapter);
categoryNames is a string array. When the dialog is done, the selected categoryName is used as the parameter to the method call on the parent activity.
What I really want to do:
What I actually want is to display a list of Category objects. The Category class has 2 properties - categoryId and categoryName. The spinner should still display the categoryNames in the drop-down view, but when the dialog is done, it should be able to unambiguously tell which Category was selected, and call the parent activity's callback method with the categoryId of the category that was selected.
There can be multiple Categoryies with the same categoryName.
Question: How to do the above?
There are a couple different way to do what you want:
Store the extra data in the adapter, like a SimpleAdapter, SimpleCursorAdapter, or custom one.
Use a Collection of custom objects instead of Strings, simply override the toString() method to present user readable Strings in the Spinner.
You seem to want to do the second option, so here's a generic example:
class Category {
int id;
String name;
public Category(int id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}
Your ArrayAdapter is almost the same:
List<Category> categories = new ArrayList<Category>();
// Add new items with: categories.add(new Category(0, "Stack");
ArrayAdapter<Category> adapter =
new ArrayAdapter<Category>(getActivity(), android.R.layout.simple_spinner_item,
categories);
...
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Category category = parent.getItemAtPosition(position);
Log.v("Example", "Item Selected id: " + category.id + ", name: " + category.name);
}
public void onNothingSelected(AdapterView<?> parent) {}
});
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
I want to display a listview when clicked be able to get the items key value. How would I go about that.
thanks,
Dean
The way you would go about doing what you're talking about is to use an ArrayAdapter with a simple class for creating the objects you'd like to use.
For instance, if you'd like to make a listview of People including their name and their age, and want to display just their names in a listview, you would first create a Person class as follows:
public class Person {
int age;
String name;
public Person(int age, String name) {
this.age = age;
this.name = name;
}
#Override
public String toString() {
return this.name; //what you want displayed for each row in the listview
}
}
Then, in your java file that's utilizing the listview (say it's called PersonTracker.java), you would call:
setListAdapter(new ArrayAdapter<Person>(PersonTracker.this, R.layout.list_people, people);
lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View currView, int position, long id) {
Person selected = (Person)lv.getItemAtPosition(position);
String selectedName = selected.name; //ideally this would probably be done with accessors
int selectedHeight = selected.height;
//Do whatever you need to with the name and height here
//such as passing via intents to the next activity...
}
});
where list_people is just a generic xml layout with just a textview that controls how each row looks, and people is the xml layout that contains the listview.
As you can see above, in your onItemClick function you can get whatever you want from the Person associated with the list item that's clicked on.
Anyway, hope that helps someone out and saves the time I spent figuring it out...i need some sleep...
The items key value of a listview ? Are you looking for onListItemClick from ListActivity ?