Custom list view delete row in android - android

I am using a custom list view in my application. In custom list view in all rows I have placed an image button. If I click that image button, I have to delete clicked button row in the custom list view. Can anybody tell me how to do this? The below coding is not working:
imgcross=(ImageView)v.findViewById(R.id.imgcross);
imgcross.setId(position);
if(v.getId()==R.id.imgcross)
{
Log.d("image id is",Integer.toString(imgcross.getId()));
myScheduleList.removeViewAt(imgcross.getId());
Toast.makeText(MyScheduleDay0RequestedMeeting.this, "Cross Button is Clicked", Toast.LENGTH_LONG).show();
}
if (v.getId()==R.id.imgcross)
{ //Integer index=(Integer)imgcross.getTag();
//Log.d("image id is",Integer.toString(index));
int index=imgcross.getId(); (imgcross.getId());
MyScheduleBean.listName.remove(index);
MyScheduleBean.dateValue.remove(index);
MyScheduleBean.dateValue.remove(index);
CAdapter = new CustomAdapter(this,MyScheduleBean.listName,MyScheduleBean.dateValue,MyScheduleBe­an.meeting,R.layout.myschedule_day0_requestedmeetingrow,to);
myScheduleList.setAdapter(CAdapter);
}
Thanks

You need to delete the data from the underlying Adapter. Done properly, this will automatically update the ListView. Otherwise, also call notifyDataSetChanged() on the Adapter, and that will cause the ListView to update.

I've been searching too long for this answer - thank you very much.
After deleting the record from the database with:
DBRecordOperation.deleteRecord(dbRecord);
simply remove the record from the ListView with:
adapter.remove(dbRecord);
I'm doing this on a long click in the ListView. Full code for onContextItemSelected is:
#Override
public boolean onContextItemSelected(MenuItem item){
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
DBRecord dbRecord = (DBRecord) getListAdapter().getItem(info.position);
int dbRecordId = dbRecord.getId();
DBRecordOperation.deleteRecord(dbRecord);
adapter.remove(dbRecord);
return true;
}

Related

notifyDataSetChanged not working from within custom adapter

I'm faced with strange problem. I've made a ListView, populated it with adapter and everything works fine until I want to delete any item. After I press confirmation button view really deletes, but text inside of it doesn't changes on the text from next view.
For example I've got such items in ListView:
Item 1
Item 2
Item 3
When I press delete Item 2, Item 3 disappears but text in view on position 2 doesn't changes. I know that Item 2 was deleted as I use database for storing data and after app restart everything show as expected. I suppose that problem is in reuse of views by View Holder but I can't figure out how to change text in second view.
Here is code that doesn't work (at least I think that problem is here)
confirmDeleteButton.setOnClickListener(new View.OnClickListener() {//this button is in dialog
#Override
public void onClick(View v) {
DBController.init(context).delete("main", "id=" + item.get(position).getId(), null);//deleting item from database
remove(getItem(position)); //removing view from adapter
notifyDataSetChanged(); //notifying adapter
dialog.dismiss(); //closing dialog
}
});
SOLUTION
Just use RecyclerView instead of ListView.
First you have to remove the data from adapter like adapter.remove(adapter.getItem(position));
and then call notifyDataSetChanged()
don't use the get position to delete the datas, first setid() to confirm buttons like, confirmDeleteButton.setid(position) used in getview adapter class.
then remove the id based on getid() like:
DBController.init(context).delete("main", "id=" + item.get(v.getid()).getId(), null);//deleting item from database
remove(v.getid()); //removing view from adapter
Is better if you use:
adapter.notifyItemRangeRemoved(int positionStart, int itemCount)
adapter.notifyItemRemoved(int position)
More info: https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html

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..

ListView Selected Position always resets

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.

Cannot use onItemSelectListener() with Spinner with One Item

So I have a spinner (spinner2 here) which is populated via an ArrayAdapter from an SQLite table. On selecting an item I want it
deleted from the DB
deleted from the spinner
The code below actually works. Except when the spinner has only one item. When that happens
it seems onItemSelected is not called at all.
I get the following LogCat
10-01 22:30:55.895: WARN/InputManagerService(1143): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#45a06028
Oh and when two items are populating the spinner, spinner.getcount() shows two items, so it's not some strange case of the system thinking the spinner is empty or something like that.
This is the code:
public class SpinnerItemSelectListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
if(parent == spinner2){
if(autoselected){
autoselected=false;
}
else{
//uniqvalarray is the arraymade from pulling data from SQLite and populaitng array adapter
Integer i = uniquevalarray.get(pos);
deleteRow(i);//deletes the row from the database and repopulates the above array.
autoselected=true;//just a boolean to stop autoslecting in onCreate()
//makeAlert(i);initially wanted to make alert box.
loadSpinner2();//reloads the spinner with new data
}
}
}
public void onNothingSelected(AdapterView parent) {
//TODO
}
}
The spinner runs this way : Only fire when you change the selected item . If you dont change that element , cause its the only one that exist , it can't change .
The solution i think you must use is using a button next to the spinner to throw the delete funcions.
You must think that Spinner is not made to be with an unique element , cause only changes usually when you change the selected one . then the natural solution can be that .

Categories

Resources