Listview with key field - android

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 ?

Related

How to get array index of selected item from AutoCompleteTextView?

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.

Android - control list of 2nd Spinner item select based on 1st spinner selection

I am using 2 spinners in my app, 1st spinner is an array of lecturer, and 2nd spinner is an array of courses,
and this is an output of json in 1st spiner:
ardi halim, fanny, indah, [...]
and for 2nd spinner output look like:
mobile development, object-oriented programming, [...]
my question is how to control the 2nd spinner list when 1st spinner already select the `lecturer?
for the example :
when 1st spinner choose ardi halim, the 2nd spinner giving a list
of mobile development and OOP
when 1st spinner choose fanny, the 2nd spinner giving a list of mobile development only
i just can control the 2nd spinner using setSelected with this code :
if(text.equals("Fanny")){
Toast.makeText(MainActivity.this,"Anda Memilih Dosen Fanny", Toast.LENGTH_SHORT).show();
sp2.setAdapter(adapter2);
sp2.setSelection(1);
sp2.setEnabled(false);
}
but how to add more than 1 list in 2nd spinner when someone choose ardi halim?
I've tried searching for a posting someone who has the same problem but I have not found the answer
You have to make class like this for handling 2nd spinner according to your 1st spinner result
public class Lecturer{
String name;
ArrayList course;
Lecturer(String name,Arraylist course){
this.name= name;
this.course = course;
}
public String toString(){
return name;
}
}
In Activity
ArrayList<Lecturer> lecturerList = new ArrayList<>();
list.add(new Lecturer("ardi halim",<courses list for ardi halim>));
list.add(new Lecturer("fanny",<courses list for fanny>));
set lecturerList for 1st spinner
then
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ArrayList courselist = ((Lecturer)spinner1.getSelectedItem()).course;
set courselist for spinner2 adapter
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
You can try like this,
Make 2 different array of lectures or fixed the position of lectures,
then on basis of selection of first spinner you can set the array to the next spinner or set the position to next spinner.

Filtering list view and getting correct onclick item

I have a list view and I've implemente filtering.
Lets say I have items A, B and C. If I type B in the filter box, only item B will be displayed and it is the position 0 of the list (before it was in position 1). So when I call the onClick item, I get the the id/position 0, which leads to displaying details about A instead of B.
This is the onclick code:
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Poi poi = pois.get((int)id);
goPOIDETAIL(poi);
}
});
id and position have the same value.
is there a way to get the original position, or get some other value indicating the real item that I clicked?
Thanks
flashsearchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Integer temp=flashSearchNameMap.get(adapter.getItem(position));
navigateSearch(temp);
}
});
(adapter.getItem(position) will return you the exact list name and in flashSearchNameMap i have stored names and position at beginning from oncreate before applying filtering.So you can get exact position by this
I think the problem is in the way you manage your filter. You should get the object with selected id not from the original List (or array) but from the filtered one.
I used something like it in this post from my blog. Hope this help you
ID and Index are not the same. Of course, you can return item index in getItemId() method of your adapter, but don't expect your items to be identified correctly by this method if you do.
Try providing unique ID for each of your items. The idea is somewhat similar to ID of each record in the database, which never changes (and lets you reliably identify each record), and it is easily implemented when you get your data from database.
But if your items don't have unique IDs, and you don't want to bother providing them, there's another approach (see this example code for Adapter below):
public MyAdapter extends BaseAdapter {
private List<Item> items;
private List<Item> displayedItems;
public MyAdapter(List<Item> items) {
this.items=items;
this.displayedItems=items;
}
public filter(String query) {
if(query.isEmpty()) {
displayedItems=items;
} else {
displayedItems=new ArrayList<Item>();
for (Item item : items) {
displayedItems.add(...) //add items matching your query
}
}
notifyDataSetChanged();
}
//...
//NOTE: we use displayedItems in getSize(), getView() and other callbacks
}
You can try:
#Override
public boolean hasStableIds() {
return false;
}
in your adapter
if you are using datbase you have the _id key that you can load in a filtered list as invisible field. Once you click on the item you can query data with _id key.
If you aren't using a database you could add a hidden id element in your row element as well.

displaying objects in a spinner rather than just strings

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

Setting ID for Spinner items

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

Categories

Resources