Adding custom data to ListView & ArrayAdapter items - java

I'm creating an Android application. Inside a Fragment I have a ListView that is populated using an ArrayAdapter and an ArrayList. I'm using android.R.layout.simple_list_item_1 for the layout for the list items. I want to have an OnItemClickListener, so that when an item is clicked it will show another Activity based on its data.
The problem is, there may be items with the same name. I'd like to attach an ID value to each of the elements, so that my code can distinguish them from each other.
My items that I use to populate the list are of a custom class to hold their data, but the important fields here are the ID and the name (which is shown in the ListView).
My code for populating the ListView:
List<String> items;
ArrayAdapter<String> adapter;
List<MyCustomDataObject> listOfDataObjects;
...
// Get the ListView
ListView list = (ListView) layoutRootView.findViewById(R.id.listView1);
// Create the item List and the ArrayAdapter for it
items = new ArrayList<String>();
adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_1, items);
// Set the list adapter
list.setAdapter(adapter);
// Add the data items
for (MyCustomDataObject obj : listOfDataObjects) {
items.add(obj.name);
}
items.add(getResources().getString(R.string.no_items));
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Open the Activity based on the item
}
});
How could I add an ID to the list items for identifying each item?

The solution is quite simple actually.
You're populating the ListView from a List. The List is an ordered collection of items, so when adding it as the datasource for the ListView you will always know the index of each item.
So when selecting an item from the ListView you get the position of the View clicked. This position will correspond to the position in your List.
You won't really need the id field of your MyCustomDataObject, but of course when you populate the List of MyCustomDataObject you could use a normal for-loop (not enhanced) and use the index to set the id of each MyCustomDataObject.

Lookup the position in listOfDataObjects to find the ID:
// Create the item click listener
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position==listOfDataObjects.size()) { .... no_items clicked ... }
else {
MyCustomDataObject obj = listOfDataObjects.get(position);
... // Open the Activity based on the item
}
}
});

Related

How to get the item's text from the adapter

How can I get the item's text from an adapter's listview?
In my adapter I have this code:
final ArrayList> userList = controller.getAllUsers();
if (userList.size() != 0) {
//Set the User Array list in ListView
ListAdapter adapter = new SimpleAdapter(PoliceSmsRegisterReceiver.this, userList, R.layout.view_user_entry_register,
new String[]{"userId", "sender", "fullname", "homeaddress", "emailaddress", "phonenumber", "password", "deviceid"},
new int[]{R.id.userId, R.id.viewSender, R.id.viewFName, R.id.viewHAddress, R.id.viewEAddress, R.id.viewPNumber, R.id.viewPassword, R.id.viewA_ID});
ListView myList = (ListView) findViewById(android.R.id.list);
myList.setAdapter(adapter);
(p.s ; controller is my sqlite db)
then this is my onclick:
myList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
});
What I want to know is how I can toast the specific string in the adapter when clicking the specific item in the list. Example, I want to toast the viewSender.
You can use AdapterView and position provided by setOnItemClickListener to get any information about clicked item :
Toast.maketext(context,(ModelClass)parent.getItemAtPosition(position).getSpecificText(),Toast.LENGTH_SHORT).show();
You can use int position like this.
Toast.maketext(context,String.valueof(position),Toast.LENGTH_SHORT).show();
An OnItemClickListener handles clicking a list item.
You have to use a custom adapter in which you grab hold of all the Views in the row in getView() and set onClickListeners on them there.

Android calculate ListView Items

Lately I have been working on my Shopping App. It's used commercially in the AppStore.
So a few of users asked for a function to directly add an article price and finally a total price of all list items. So I tried to realise this in my app.
So I have build my listview
items = new ArrayList<String>();
adapter = new ArrayAdapter(this, R.layout.item_layout, R.id.txt, items);
listView.setAdapter(adapter);
And my listview works super. Now I want to get the position of an item in the ListView.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
String value = (String)adapter.getItem(position);
Toast.makeText(getApplicationContext(), value, Toast.LENGTH_LONG).show();
}
});
So and now I want to add a function to override my listview item and set a new 'Price'.
And last but not least my question. How can i get a total of all prices in the ListView?
I mean
(Position 1 1,99),
(Position 2 1,05),
(Position 3 4,50),
(Total 7,54),
Thx for all of your help :D
Rather than items = new ArrayList<String>();, you should have a class Item with item's name and price

Android Development - Is it possible to convert a ListView back into an ArrayList?

I am having a problem with ListViews and ArrayLists.
I have an ArrayList of items. Each item has info such as ID, Title, Price etc. I also have another ArrayList of allocations. These allocations contain an "ItemId" variable - so I plan to link this to item. (Without the use of a database.)
This is how I think I will do it. First of all I will convert my ArrayList of items into a ListView using AndroidStudio. When the user clicks on a specific item on this ListView, I will run an if statement (e.g if the Id of the selected item is 2, display the allocation with that itemId)
However there is a problem with this. I can't check the Id in this if statement because my ArrayList has already been converted to a ListView, which I can not search for specific data. Can anyone help me?
Here is the code I have at the moment:
public class ViewItems extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_items_layout);
ListAdapter itemAdapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1, Item.itemArrayList);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(itemAdapter);
itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String itemPicked = ????;
IF STATEMENT GOES HERE;
}});
}
}
You don't 'convert' your ArrayList into a ListView. The ListView merely uses the ArrayList to show your items - the ArrayList is still valid.
More precise, you add your items to the ArrayAdapter, which uses your exact ArrayList. You can use:
itemAdapter.getItem(i);
Complete example:
final ArrayAdapter<Item> itemAdapter = new ArrayAdapter<Item>(this, android.R.layout.simple_list_item_1, Item.itemArrayList);
ListView itemListView = (ListView) findViewById(R.id.itemListView);
itemListView.setAdapter(itemAdapter);
itemListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Item itemPicked = itemAdapter.getItem(i);
IF STATEMENT GOES HERE;
}
});
Note that since you're putting instances of Item in your ArrayList, itemAdapter.getItem(i) will return an Item, not a String.
Use getItem of your ArrayAdapter
itemAdapter.getItem (i);

Get data from Listview? How?

I have a database (db) from I get values (name, email address, phone number. etc) which I put in a list and displayed in a ListView. If I click on an item can I get the whole data from clicked item? Because I need ex. email address to send email. Can I extract from the item the data, because when get data from database is in a "Client" type.
List list = db.getAllClients();
final ListView listview = (ListView) findViewById(R.id.listView_ID);
listview.setClickable(true);
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
registerForContextMenu(listview);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id) {
// some code
}
});
You don't need to extract your data from your ListView per se, only the Array that you used to populate your list.
Since onItemClick(...) gives you the position of the clicked item, you can either...
Use your ArrayAdapter to get the item:
adapter.getItem(position)
Get your data from your original list:
list.get(position)
In either of these cases, since you are retrieving your data from an anonymous inner class (your OnItemClickListener), the adapter or list in question needs to be an instance variable and not a local variable (i.e. define the adapter or list as part of your class, above all of your methods).
You can get data from ArrayAdapter by position in your AdapterView.OnItemClickListener:
((ArrayAdapter) listview.getAdapter()).getItem(position);
As i can see your code , you get List of object List<Client> so
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view,
int position, long id) {
Client client = list.get(position) ;
}
});
because the position refer to the selected index of your list

How to show results in a listview layout?

I have a search functionality in my application. I am fetching the results based on keywords submitted by user. How do I use listview to show results of the search query in a listview? This is my first time in using listview, any pointers, tutorials will be helpful.
I think searchable dictionary example is where you should start from. Code and other details are at http://developer.android.com/resources/samples/SearchableDictionary/index.html
Try to use AutoCompleteTextView.This will filter the list of items at the time of entering the text in to the AutoCompleteTextView field.
or
Use this.This will help you to add the listview in the LinearLayout.When the user press the any one of the alphabet this will filter the List items
ListView lv = new ListView(this);
lv.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, Your_array));
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String str_item = Your_array[position];
Toast.makeText(Your_Class_Name.this,str_item, 10).show();
}
});

Categories