Android - OnClick handler for dynamic ListView data? - android

I have a ListView that is filled with a dynamic set of data each time the Activity is created. For simplicity's sake, lets say each ListView item is a employee's name. Under the hood, each employee has an employee_id number. This number is not visible anywhere in the interface.
When I click on an employee's name in the ListView, I want to launch another activity, passing the corresponding employee's employee_id to that Activity.
I understand how to implement the onClick handler for the ListView. My question is, where would I store and retrieve the employee_id for each employee? Would I simply store it in a hash/map along with the position in the list that the employee shows up at? And when I click, I just determine the position in the list I clicked at, and then get the employee_id from the hash using that position?

Use the ArrayAdapter with a list Employees - assuming you have Employee-object.
public class MyActivity extends ListActivity {
// list of employees
private List<Employee> employees = new ArrayList<Employee>();
Then use the position parameter in OnItemClick to get the employee-object.
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int employee_id = ((Employee) getListAdapter().getItem(position)).getId();
// ...
}
You can also extend the ArrayAdapter to tailor the list for employee-objects:
How to use ArrayAdapter<myClass>

You use an Adapter based on some set of data (for example, a List of Employee objects). When you set an onItemClickListener on your ListView, the onItemClick method gets an int parameter that is the position in the underlying data. Use that to pluck the Employee object out of your List, and there's the employee id.

I would suggest doing what you stated above. Or, I don't really think it's nice solution, I also think there aint any, but you could add a label with no content (maxHeight and maxWdith are both 0, or invisible? never tried that) and set the text. I don't know how it is resource wise. But you won't have to save the list anymore, which saves some memory if you have a big list.

Related

Android filter ListView with users options

I am creating an app in which a user can set some preferences in a PreferencesActivity and then I got a fragment with a ListView which is supposed to be filtered according to what the user has chosen. I already got a Filter which is filtering the list with users text input but I'm not sure how to filter according to preferences made in the PreferencesActivity.
The data class representing a single list item looks something like this:
public class MyData
{
private ArrayList<SomeEnumType> enumListMember;
private String forRegularStringFilter;
...
}
public enum SomeEnumType
{
VAL1,
VAL2,
VAL3
}
What the user sees in the preferences is a MultiSelectListPreference with entries VAL1, VAL2, VAL3, and the user can select several of them. After the user finishes his selection, the list is suppose to show only the items which its enumListMember contains all the enum values the user has chosen. for example, the list of the class can contain VAL1 and VAL3 so if the user is choosing VAL3, the item is supposed to show. If he chooses VAL2, it's supposed to be filtered.
How and where do I make this kind of filtering? in the Adapter's getView? somewhere else?
What I eventually did was simply creating a new adapter with the correct values and replacing the old one every time a filtering was needed.

Scrollable clickable items from JSON string in android

I want to create a clickable items from a scrollview or listview where items came from a JSON which is fetched from my online database. Now I don't even have an idea on how to work with this one since I don't know how to dynamically create an object through codes to insert the database items. Well the concept is simple I just need to display a list through codes then assign an ID per row, click one of the row then move to a new intent where details are displayed matched by ID assigned on the selected row. Can anyone give me an example or links on how can I work with this one?
You need to study ArrayAdapter and JSONParsing, there are many tutorials for that, I will try to explain these in a brief:
An AdapterView is the view, which items/childs are determined by some adapter. Like ListView, Spinner.
An Adapter is a bridge between AdapterView and underlying data.
See ArrayAdapter as it seems best according to your requirements.
To Understand JSONParsing, you need to understand JSONObject, and JSONArray:
A JsonObject is a key: value pair, where key need to be string and value might be a number, a boolean value, or some other datatype, or JSONOjbect, or A JSONArray. and its represented by {}. like {"key":"value", "key1":"value1", .....}
A JSONArray is an array of values, values might be a number, a boolean value, or some other datatype, or JSONOjbect, or A JSONArray, and it is represented by []. for example: ["value1", "value2"....]
There is no need to set item view's Id, because you can find which item is being clicked, by:
http://developer.android.com/reference/android/widget/AdapterView.OnItemClickListener.html, method
onItemClick(AdapterView parent, View view, int position, long id), you would have position of item being clicked. But If you still want to assign an id to item view, then do it in getView method of Adapter. by View.setId() method.
check the samples that can be downloaded with the SDK manager, there you'll find everything you're looking for.

onListItemClick, can I get the absolute position from 'id'?

I have
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, column));
getListView().setTextFilterEnabled(true);
and
public void onListItemClick(
ListView parent, View v, int position, long id)
I need to fine the position in column of the clicked item. Position is no good since the filter is on. Can I somehow derive the real position from 'id'?
One possible solution:
After you've set up a listview, do a once-through of the entire list, adding all the visible items indexes to an array. For instance, in a 5 element list, with the 2nd and 4th items not visible, it would look like this:
indexes[0] = 0
indexes[1] = -1
indexes[2] = 1
indexes[3] = -1
indexes[4] = 2
then when you get a position in the onListItemClick, that's just an index in the "indexes" array that returns the real position in the filtered ListView.
Then inside your onListItemClick, just use the position passed as a parameter as a key to look up the position in the filtered list.
EDIT: SparseArray is overkill. Offering reasonably easy solution.
I guess you can use .getChildCount() and .getChildAt() and then check .getVisibility() == View.VISIBLE on each to count the number of visible, and check if the clicked item is equal to the current iterrated. There's no straightforward way I'm afraid.
position in listview is the position of the element in generic object ie list you pass to an array adapter.
I haven't ever had good luck with ItemIDs.
Might want to instead pull the data from View v. This view might contain a TextView, which you could use to determine which row the user clicked on. This won't work if multiple rows can be displayed identically though...
So if that is the case, you are going to have to iterate through the dataset calling getItemID(int position) on every element in the adapter. Store these longs in an array the same size as the dataset, and use the same index on both your column dataset and this long ItemID array.

How to update non-bound child view for ALL items in a ListView?

I have a ListView that uses a custom layout that has 5 child View objects (4 TextView and 1 CheckBox) in the custom layout. Only the TextViews are bound, however - the CheckBox has no corresponding field in the database. The purpose of the CheckBox is simply to identify which of the items being displayed I would like to process in "the next step". I'm using a custom ViewBinder to assign the text values correctly (because some of the values from the DB are dates, etc).
Part of the user interface is three buttons - 'All', 'None', and 'Invert' that I use to toggle the status of each item in the list. For the 'All' button, for example, I do this with the following code (which I now know is NOT correct - I include it to show what I'm trying to do):
ListAdapter la = getListAdapter();
ListView lv = getListView();
int iCount = la.getCount();
for(int i=0; i<iCount; i++)
{
View vv = lv.getChildAt(i);
CheckBox cb = (CheckBox) vv.findViewById(R.id.ledgerItemCheckBox);
cb.setChecked(true);
}
This works fine as long as the number of items in the list doesn't exceed the list size so that all items are always visible. When I exceed that number, though, the 'getChildAt' function sometimes returns null because (if I understand correctly) it isn't meant to return all of the items in the list, only those items that are visible, which results in a NullPointerException.
How can I properly set the CheckBox on all views, even if they aren't visible?
Create a pseudo binding to one of your TextView data, create an ArrayList of Boolean objects as your back end for the checkboxes. Please note an ArrayList may not be the best data structure for your application. Fill the ArrayList with booleans set to the initial value of the corresponding position of your Cursor's data set. When you're binding use the ArrayList as the back end data. When you select all, none, or invert, update the Boolean objects in the ArrayList then call notifyDataSetChanged() on your SimpleCursorAdapter.
Addition ah, the other half of the problem, yes, use the onClickListener for the CheckBoxes but use the same listener, don't create a new object for each. Use the getPositionForView() method to get your position and update the underlying data.

how to generate dynamic data for an item in listview

I have created a list activity calles as Category List to show a list of category dynamically from web by parsing an XML file. The XML file contains values "ID"(id of the particular category) and "title"(category name). So what I've done is, I've parsed the XML file and collected the ID and title to an ArrayList called categries using SAX parser.
In the list activity, I have a created a new string array and added the title of each category to it. The thing I want to do is to assign the category id to each category shown in the list view and to use the id to get the appropriate view for that category. Is there any way to assign an id to the each of the list items.
regards
dj
Introduce a JavaBean, and fill it:
class YourBean {
private int id;
private String title;
// add get / set methods
}
Create the list and put it in a ArrayList ,then fill a Adapter with it.
Then, you can use an http://developer.android.com/reference/android/widget/ArrayAdapter.html and in your onClicked etc method use mAdapter.getItem(int). That's in very short words.
Take a look in the SDK examples.

Categories

Resources