deleting multiple items from listview - android

I am trying to delete several items from my listview but it just deletes one element(even though i select more than one). The listview implements android.R.layout.simple_list_item_multiple_choice which has delListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE). I have a button where in the onClick method i would first like to check if there are no items selected if so prompt the user with some message. Else if there are some items selected delete them. This is what i have so far:
public void onClick(View v) {
// TODO Auto-generated method stub
selectItems();
Intent intent = new Intent(); ...
}
selectItems function:
private boolean selectItem()
{
String message = "Please select an item!";
for (int i = 0; i < array.size(); i++)
{
if(array.valueAt(i))
{
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
Log.i("my_app", item + " selected");
deleteAdapter.remove(item);
deleteAdapter.notifyDataSetChanged();
return false; //item found
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true; //no item found
}
Thank you for your help!
I have managed to solve my problem. My solution was:
private void deleteItems() {
// TODO Auto-generated method stub
for (int i = (array.size()) - 1; i >= 0; i--)
{
if(array.valueAt(i))
{
String selected = deleteAdapter.getItem(array.keyAt(i));
Log.i("my_app", selected + " will be selected");
deleteAdapter.remove(selectat);
}
}
Intent intent = new Intent();
intent.putStringArrayListExtra(BUNDLE_DELETE, deleteList);
setResult(REQUEST_CODE_DELETE_STRING, intent);
getInstance().finish();
}
private boolean selectItem()
{
String message = "Please select an item!";
for (int i = 0; i < array.size(); i++)
{
if(array.valueAt(i))
{
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
Log.i("my_app", item + " selected");
deleteItems();
return false;
}
}
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true;
}
I made a separate method for selecting the items and deleting them. Then i simply called the delete method in the selectItem(). In the onClick method i called the selectItem() method.
Thank you all for your help! :)

Notifydata set changed after all your items have been removed from the data map.

1) In onClick() call ListView.getCheckedItemPositions() to get the positions of the selected items in the list or ListView. getCheckedItemIds() to get the Id's of the selected items.
2) Then delete them.
3) Then call notifyDataSetChanged() on the Adapter to cause the list to be refreshed.

try something like this:
see an example :(Portuguese Link) http://nglauber.blogspot.com.br/2013/07/listview-com-selecao-multipla-actionbar.html
private boolean selectItem() {
String item = delListView.getAdapter().getItem(array.keyAt(i)).toString();
SparseBooleanArray checked = listView.getCheckedItemPositions();
for (int i = checked.size()-1; i >= 0; i--) {
if (checked.valueAt(i)) {
String item = delListView.getAdapter().getItem(checked.valueAt(i)).toString();
deleteAdapter.remove(item);
}
}
deleteAdapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
return true; //no item found
}
Edited:
I first want to verify(when
pressing a button) if there are no items selected.
mButton.setOnClickListener( new OnClickListener() {
#Override
public void onClick( final View v ) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
if ( checked.size() == 0 ) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
}
} );

Related

Checked the Checkboxes that is already checked

I have one EditText (edModelColor). when user click on edModelColor(EditText) then the custom dialog will be called.Custom dialog consist of RecylerView and searchview and one custom row for each item. Custom row contains ImageView(icon), TextView (colorNames) and checkbox for selection. When user click on any checkbox I passed the colorName and its position in adapter into method checkAndRemove. this method will add or remove the color name according to its adapter position and the colorNames will added into edModelColor(EditText). its working fine but the problem is that once the user click on edModelColor(EditText) again, I want to checked those checkboxes which are already checked inside CustomDialogbox.I have seen some articles online but I could not understand what they meant.
bodyColorDialog:
private void bodyColorDialog() {
TextView txtClose;
TextView tvCancel;
Button btnOk;
bodyColorDialog.setContentView(R.layout.ed_body_color_dialog);
bodyColorDialog.setCancelable(false);
txtClose = bodyColorDialog.findViewById(R.id.txtModelClose);
tvCancel = bodyColorDialog.findViewById(R.id.tvCancel);
btnOk = bodyColorDialog.findViewById(R.id.btnOk);
edBodyColorSearchView = bodyColorDialog.findViewById(R.id.edBodyColorSearchViewColor);
edBodyColorRecylerView = bodyColorDialog.findViewById(R.id.edBodyColorRecylerView);
edBodyColorRecylerView.setLayoutManager(new LinearLayoutManager(getContext()));
bodyColorArrayList.clear();
setUpBodyColorArrayList();
btnOk.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectionCMap = new HashMap<>();
selectionCMap = edBodyColorAdapter.selectionColorsMap;
for(String value : selectionCMap.values()){
/* tv.setText(tv.getText() + "\n" + value);*/
edBodyColor.append(value + ",");
}
bodyColorDialog.dismiss();
}
});
txtClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
tvCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
bodyColorDialog.dismiss();
}
});
bodyColorDialog.show();
}
private void setUpBodyColorArrayList() {
bodyColorArrayList.clear();
String bodyColorName[] = getResources().getStringArray(R.array.body_color_array);
int bodyColorIcons[] = {R.drawable.red, R.drawable.black, R.drawable.violet, R.drawable.white,
R.drawable.orange, R.drawable.blue, R.drawable.green, R.drawable.yello};
for(int i =0; i < bodyColorIcons.length; i++)
{
bodyColorArrayList.add(new edModelBodyColor(bodyColorName[i], bodyColorIcons[i]));
}
edBodyColorAdapter = new edBodyColorAdapter(getContext(), bodyColorArrayList);
edBodyColorRecylerView.setAdapter(edBodyColorAdapter);
edBodyColorSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
#Override
public boolean onQueryTextChange(String queryString) {
edBodyColorAdapter.getFilter().filter(queryString);
return false;
}
});
}
edBodyColorAdapter.java
holder.checkBoxColor.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
int position = holder.getAdapterPosition();
clickedColorNamePosition = edBodyColorArrayList.indexOf(filteredArrayList.get(position));
String name = edBodyColorArrayList.get(clickedColorNamePosition).getBodyColorName();
Toast.makeText(context, "name = " + name, Toast.LENGTH_SHORT).show();
//this mthod will check if selected checkbox value is already present or not.
// It present then remove ( means user unchecked box) and if value is not there means user has selected checkbox
checkAndRemove(position,name);
}
});
checkAndRemove:
private void checkAndRemove(int position, String name) {
if(selectionColorsMap.containsKey(position)){
selectionColorsMap.remove(position);
Toast.makeText(context, "removed", Toast.LENGTH_SHORT).show();
}else {
selectionColorsMap.put(position, name);
Toast.makeText(context, "added", Toast.LENGTH_SHORT).show();
}
}
preview:
Conculusion: I want to check these checkboxes values when user click again on edBodyColor dialog..
I as can see, you are initializing the ArrayList of colors every time you are showing the dialog, that's why, you start always at initial state.
Instead, you should initialized the ArrayList inside onCreate() and reuse it every time to maintain the previous state.

how to reload listview from another activity (adapter) class

i have tried all the things but i cant get proper result,i also try
adapter.clearAll()
adapter.notifyDataSetChanged()
but i cant get result when i delete row from list view its deleted from its position but when i change value of another row than the delete process working perfectly but changed value not set.getting value from database perfectly.
Here is my code please help me and tell where i m doing wrong.
Thank you in advance
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Identifier_fev = null;
String Default_Option = null;
String Quantity1 = null;
jffDatabase.open();
Cursor identifie = jffDatabase.getALL();
if (identifie.moveToPosition(position)) {
Identifier_fev = identifie.getString(identifie.getColumnIndexOrThrow("identifier"));
Default_Option = identifie.getString(identifie.getColumnIndexOrThrow("default_option"));
}
jffDatabase.delete(Identifier_fev, Default_Option);
identifier.remove(position);
title.remove(position);
defaultPrice.remove(position);
default_option.remove(position);
price.remove(position);
quantity.remove(position);
Cursor c1 = jffDatabase.getALL();
if (c1.moveToFirst()) {
do {
Quantity1 = c1.getString(c1.getColumnIndexOrThrow("quantity"));
update_quantity.add(Quantity1);
} while (c1.moveToNext());
}
for (int i = 0; i < update_quantity.size(); i++) {
Toast.makeText(ctx, "" + update_quantity, Toast.LENGTH_LONG).show();
Quantitylbl.setText(update_quantity.get(i).toString());
Toast.makeText(ctx, "set " + Quantitylbl.getText().toString(), Toast.LENGTH_LONG).show();
}
Quantity();
notifyDataSetChanged()
AddtoCartActivity.Cartcount.setText(String.valueOf(sum));
}
});
Good practice is use Interface
Create new Interface
public interface MyCustomObjectListener {
public void RefreshList();
//add parameter for delete if required ex-
//public void RefreshList(String Item_id);
}
then implement Activity by this Interface
YourActivityName extends Activity implements MyCustomObjectListener
And Implement Method
#Override
public void RefreshList() {
// Do your delete task and clear current List and get updated list task here
}
and from Base adapter onClick you can call method RefreshList like this
((YourActivityName)mContext).RefreshList();
you can delete and refresh list from #Override RefreshList

checkbox select all delete issue

i have checkboxes in custom list view and i have two seperate buttons one to select all and another to delete but i have big issue in it if i select one checkbox and select delete it works.but if i select all and delete it delete few of the data in lists ,for example i have 50 sms in list view once i select all and delete it delete few sms and again i press delete it delete another few like this..suggest some solutions
sel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i <sms.size() ; i++) {
if(sms.get(i).getChecked() == false ) {
sms.get(i).setChecked(true);
}else if(sms.get(i).getChecked()==true) {
sms.get(i).setChecked(false);
}
}
((datalist)mlistView.getAdapter()).notifyDataSetChanged();
}
});
del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0; i<sms.size(); i++){
if(sms.get(i).getChecked() == true){
sms.remove(i);
}
}
((datalist)mlistView.getAdapter()).notifyDataSetChanged();
}
I guess the problem arises when you remove the item from the ArrayList in the for loop there. It's size gets reduced as a result and this can induce undesirable side effects.
Try iterating your sms ArrayList in reverse order like this:
for (int i = sms.size()-1; i >= 0; i--) {
if(sms.get(i).getChecked() == true){
sms.remove(i);
}
}
This way reduction in the size of sms ArrayList won't effect the loop.
I think problem is upper for loop. In else if statement you are unchecking the checkboxes. try below code instead,
sel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i <sms.size() ; i++) {
if(sms.get(i).getChecked() == false ) {
sms.get(i).setChecked(true);
}else if(sms.get(i).getChecked()==true) {
sms.get(i).setChecked(true);
}
}
((datalist)mlistView.getAdapter()).notifyDataSetChanged();
}
});

Get values of multiple checkboxes on Android

I have one of these for each day of the week:
mondayRadioButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mondayRadioButton.isChecked()){
deleteAppointmentsLayout.removeAllViews();
daySelected = 1;
for(Iterator<Appointment> i = appointments.iterator(); i.hasNext();){
Appointment item = i.next();
if(item.getDay() == 1){
checkBox = new CheckBox(DeleteAppointmentActivity.this);
System.out.println("fucken did work");
id = item.getId();
time = item.getTime();
duration = item.getDuration();
description = item.getDescription();
boxText = time + ", " + duration + ", " + description;
checkBox.setText(boxText);
checkBox.setTextSize(12);
checkBox.setId((int) id);
deleteAppointmentsLayout.addView(checkBox);
}
else {
System.out.println("fucken didnt work");
}
}
}
}
});
When an onclick for a button is activated I want to retrieve the information for each of the selected checkboxes for the currently selected day (checkboxes are generated programmatically). How can I check which ones are selected when the onclick for the Delete button is activated?
Create a member variable Array like
public class MyClass extends Activity
{
ArrayList<CheckBox> cbArray = new ArrayList<CheckBox>();
then when you create a checkbox add it to the ArrayList. Now when you click the delete Button use a for loop to iterate over the ArrayList and call isChecked() on each one.
Then delete or add that to a checked Array to do whatever you need with it
for (int i=0; i<cbArray.size(); i++)
{
if (cbArray.get(i).isChecked())
{
// do whatever here

On listview only want to click one item at a time

I have a listview with item. Click on an item it goes to another activity. My problem is on clicking on multiple items (say 3 0r4 ) all clicked are loaded. But i dont need it. Only want to load 1 item at a time. Tested on HTC one,samsung galaxy s plus. Please help.
You can detect multitouch and neglect it.
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
if(event.getPointerCount() > 1) {
System.out.println("Multitouch detected!");
return true;
}
else
return super.onTouchEvent(event);
}
use the follow method can solve that:
public class FastClickUtil {
private static long lastClickTime;
public synchronized static boolean isFastClick() {
long time = System.currentTimeMillis();
if ( time - lastClickTime < 500) {
return true;
}
lastClickTime = time;
return false;
}
}
put that method in your onItemCLickListner or in your adapter‘s getview like me
holder.title.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// 解决短时间内同时点击多个item
if (FastClickUtil.isFastClick()) {
return;
} else {
Message msg = Message.obtain();
msg.what = MSG_WHAT_ONITEM_CLICK;
// Bundle data = new Bundle() ;
// msg.setData(data) ;
msg.obj = menuItem.getTitleResId();
getHandler().sendMessage(msg);
}
}
});
To stop this, Use this in your list view.
android:splitMotionEvents="false"

Categories

Resources