ListView Selected Position always resets - android

I am working with a ListView trying to add/delete items. The addition bit was fairly easy, the removing though is proving to be trickier.
I was thinking to use a multiple choice list, but to start with something simpler I chose a single choice mode just to test it out.
I have an array of strings containing the items, an array adapter to notify when Data has changed.
expenseAdapter=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_single_choice,
android.R.id.text1,
expenseList);
myListView.setAdapter(expenseAdapter);
myListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View item, int position,
long index) {
((ListView)parent).setItemChecked(position, true);
item.setSelected(true);
}
});
I have also added a listener for the item onClick Event. Visually the item gets selected/deselected the issue is when I click the button which triggers the deletion of the item the selected index in the list is always -1 although the item appears to be selected.
Delete button with onClick event
public boolean doDelete(View view)
{
ListView myListView= (ListView)findViewById(R.id.list);
String s=(String)myListView.getSelectedItem();
expenseList.remove(s);
expenseAdapter.notifyDataSetChanged();
return true;
}
Any ideas what is happening or what I'm doing wrong?

use this
xmlfile : https://www.dropbox.com/s/eky9zb275mgt4py/activity_list__addand_delete.xml
javaFile : https://www.dropbox.com/s/idqyyosbutgqqbs/List_AddandDelete.java
your selection ( focus ) is removed when ever you will shift your focus to button .

I have seen your code and understand that problem, you are getting -1 index when you are removing item from List because that item is not existing in that list so change your code please try this.
I changed getSelectedItem() to getSelectedItemId() here it will return selected item id instead of Item so you can remove that item from List based on item id which will be the Index of item in List.
public boolean doDelete(View view)
{
ListView myListView= (ListView)findViewById(R.id.list);
long id = myListView.getSelectedItemId();
expenseList.remove(id);
expenseAdapter.notifyDataSetChanged();
return true;
}
Hope it will help you.

Related

Changing background colour of listview item on click - and remembering it

I am populating a listview with strings from an ArrayList.
When a listview item is clicked i would like to change the background colour to green. <- Issue number one because I cannot change the item which is clicked.
After an item is clicked, I am adding its index to the list of items the user has selected, when the listview is first loaded I need it to set the background colour of all the listview items which have been selected to green too. <- Issue number 2 - I have been trying to do this with a for loop but do not know how to refer to a specific item in the listview to set the background colour!
Essentially, i think if someone can help me in how to change the colour of a selected listview item, i should be able to do the same thing but in a loop for all the userFoodPref which are saved?
animalsNameList = new ArrayList<String>();
userFoodPref = new ArrayList<Integer>();
getUserSelection();
getAnimalNames();
// Create The Adapter with passing ArrayList as 3rd parameter
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, animalsNameList);
// Set The Adapter
animalList.setAdapter(arrayAdapter);
// register onClickListener to handle click events on each item
animalList.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
// argument position gives the index of item which is clicked
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if(userFoodPref.contains(i)
){
userFoodPref.remove(i);}
else {
userFoodPref.add(i);
View item = animalList.getSelectedView();
item.setBackgroundColor(0x0000FF00);
}
String selectedAnimal=animalsNameList.get(i);
Toast.makeText(getApplicationContext(), "Animal Selected : "+selectedAnimal, Toast.LENGTH_LONG).show();
}
});
}
If I understand well, the problem is that when you set the backround of the item and then by example scroll the list and comeback to the previous position, it doens't remember that the backround is green for this specifix item.
I have faced this problem and to solve it easily :
Create a list a string for your name and a boolean (true = green, false = not green) and create an adapter for it and simply add
if (list.get(position).getBoolean) {
Currentitem.setBackgroundColor(0x0000FF00)}
And when you click on a item simply set the boolean of the item position to true and call notifydatasetchanged()

How to have a checkbox inside of a listview, to have a listener outside adapter activity?

So, I have menu items being displayed in listview, along with checkboxes, for the user to select which he likes. And I have an overhead cart icon which keeps track of no of checked items, by a function that is written in the adapter view.
My problem:
When I have implemented the cart increment function inside of OnItemClick listener, and then when I check a few items, it doesn't get updated unless I make a click outside of checkbox (anywhere else in the listview).
I have tried disabling descendant focusability and modifying focusability as per other SO answers. They haven't solved my issue.
My calling activity
adapter = new MenuAdapter(CreateOrder.this,itemslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
selecteditems = adapter.getSelectedList();
Log.e("Selected Items",selecteditems.toString());
size = selecteditems.size();
qo.setText(String.valueOf(size));
Log.e("No of main items ",String.valueOf(size));
}
});
checkBoxState = new boolean[linkedList.size()];
You have that in getView(). So for every call of getView() you throw away the former.
In getView() you use checkBoxState[position] which then of course is undefined or null.
So take it out and put it in the constructor of your adapter and initialise it as you do with that int array.
By the way: why did not you tell that your checkboxes did not hold state during scrolling?

How to know which list view item is being selected in android?

I have 2 listview in my activity and i want to highlight the item being selected using the adapter in adapter class(one item from the both the list at a time), So by default i want only one list view item to be selected i.e the first list view item and based on the clicks on the listview the highlight should also change,that on both the listview the first item is being highlighted in the beginning and on item click the highlight changes fine.
My problem is that when i click in the first listview the scond listview items should not be highlighted but it is being highlighted why??
Here is my implementation:
I have initialised two adapter variable of the same class for the two listview
ListView list1= (ListView)finViewById(R.id.list1);
CustomListview adapter= new CustomListview(this,item,"type(it is string)")
list1.setAdapter(adapter);
list1.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.notifyDataSetChanged();
adapter.setSelectedItem(position);
........
});
and in CustomListView adapter class i'm doing the following along with the rest of the code i.e
if (position == mSelectedItem && choice.equals("Strintype")) {
tv.setTextColor(getContext().getResources().getColor(R.color.primary_dark));
} else if (choice.equals("Stringtype")) {
tv.setTextColor(Color.BLACK);
}
You're using the item position to check what to highlight, if you do so you'll have highlighted also the item in the same position in list 2; try using the item id intstead of the position (obviously there's more work to do) or use two different adapters for the lists.
Can you post the entire code for the two lists, including the adapters?

How to disable all elements (also the ones not currently visible in the screen) in a listview?

I have a ListView with a set of elements. When I click one of the I would like to disable all the others. If I click again on the selected item all the other items are enabled again.
I tried the different proposed solution without success. I hope someone can help me.
This is my code:
//action to take when a presentation is selected
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
//disable the other items when one is selected
if(position!=selectedPresentation){
for(int i=0;i<parent.getCount();i++){
if(i!=position)//disable all the items except the select one
parent.getChildAt(i).setEnabled(false);
}
selectedPresentation=position;
}else if(selectedPresentation==position){
//enable again all the items
for(int i=0;i<parent.getCount();i++){
parent.getChildAt(i).setEnabled(true);
}
selectedPresentation=-1;
}
Where selectedPresentation is a global variable storing the selected item. If no item is selected its value is -1.
Thank you for your help!
Make your own subclass of ArrayAdapter that has AreAllItemsEnabled() return false, and define isEnabled(int position) to return false for a given item in your the ones you want to disable.
In your custom ArrayAdapter overide isEnabled method as following
#Override
public boolean isEnabled(int position) {
return false;
}
other option
Don't implement onItemclickListener. This will not give you any update of item click. Only register onClick listener to views.
You may take another object of the List(Arraylist) which is populating elements in listview then on click copy the corresponding position data to new arraylist you made and then notifyDataSet and when you click again you populate listview with original list so it will apear again....Just do this trick it might work for you
parent.getChildeAt() only work for visible Item.
you should change something in adapter.
if make custom adapter then you can do some thing like #ṁᾶƔƏň ツ answer, but if you use default adapter you can change adapter's arraylist that before you pass it to adapter.
put boolean in it (in arraylist) and in on item click true/false it for all item.
I wrote this solution and seems it works fine!
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
//disable the other items when one is selected
Toast.makeText(context, "onClick called",Toast.LENGTH_SHORT).show(); // this will flash up twice
if(position!=selectedPresentation){
selectedPresentation=position;
for(int i=0;i<adapter.getCount();i++){
if(i!=position)//disable all the items except the select one
adapter.isEnabled(i);
}
}else if(selectedPresentation==position){
//enable again all the items
selectedPresentation=-1;
for(int i=0;i<adapter.getCount();i++){
adapter.isEnabled(i);
}
}
And in my adapter I wrote:
public boolean isEnabled(int position) {
if(selectedPresentation==-1 || selectedPresentation==position)
return true;
return false;
Now my concern is how to show the items in the listView as disabled

Find out an item is clicked in listView in android

I have approx 150 items in my custom listview. I am trying to implement the following:
list.setOnItemClickListener(new OnItemClickListener()
{
1. I get position of the item
2. Get the data from an ArrayList
3. Add the data to database.
This part is working fine.
But if I want to remove a particular item from the database by clicking on the item I am not able to achieve this part?
Reason because I am not sure if the item is clicked or not? I have this problem mainly when I want to implement search in the listView and add the selected item to database and remove selected item from database.
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id)
{
if (notfromsearch == true)
{
String profile_ID = profileList.get(position).get(KEY_ID);
String profile_DISPLAY_NAME = profileList.get(position).get(KEY_DISPLAY_NAME);
//add to database now
}
elseif (notfromsearch == false)
{
String SearchResult_profile_ID = searchProfileResults.get(position).get(KEY_ID);
String SearchRResult_profile_DISPLAY_NAME = searchProfileResults.get(position).get(KEY_DISPLAY_NAME);
//add to database now
}
}
});
But how to implement remove from database? I am not able to differentiate if the item is clicked before or not to remove from database.
Can somebody help me out with this?
Thanks!
On your list view, use
setOnItemClickListener
and you can do what you want next .
use context menu for deleting items from the database
on long press display delete/edit option and perform further operation as needed.
check here for context menu sample
EDIT
You can also put button/image in the listview to delete item and then implement your delete operation in the click method.
For Checkbox selection
model class
class CustomClass
{
boolean checked;
//other fields
}
in your custom adapter class
ArrayList<CustomClass> data = new ArrayList<CustomClass>();
and in getView() method
checkboxItem.setChecked(data.get(position).getChecked());
and don't forget to change the checked boolean value on checkbox change listener..

Categories

Resources