How to handle multiple checkbox in listview - android

I've got a listview containing checkbox, text ...
My problem is with the checkbox, i've got a list of Objects (models) that are coming from my local database, i've got a boolean in my model which is telling me if i need to check or not the checkbox at the moment i build the listview. My problem is from the moment i check one box, the next time i'm coming to that view, all the checkbox will be checked, or unchecked ...
I first thaught that i had a problem with my list of models, but they are all correct ... i have no idea why ...
Here is the getView method of the adapter:
public View getView(int position, View convertView, ViewGroup parent)
{
ViewHolder allItems = null;
if (convertView == null)
{
allItems = new ViewHolder();
convertView = mInflater.inflate(R.layout.row, null);
allItems.delete = (ImageButton) convertView.findViewById(R.id.deleteItem);
allItems.chkTick = (CheckBox) convertView.findViewById(R.id.checkBox1);
allItems.txtName = (TextView) convertView.findViewById(R.id.nameItem);
allItems.price = (TextView) convertView.findViewById(R.id.priceItem);
allItems.numberItem = (TextView) convertView.findViewById(R.id.numberItem);
allItems.plus = (ImageButton) convertView.findViewById(R.id.plusItem);
allItems.minus = (ImageButton) convertView.findViewById(R.id.minusItem);
convertView.setTag(allItems);
}
else
allItems = (ViewHolder) convertView.getTag();
final int pos = position;
allItems.txtName.setText(this._sqlHelper.getItemById(items.get(position).getItemId()).getName());
allItems.numberItem.setText(Integer.toString(items.get(position).getQuantity()));
allItems.chkTick.setChecked(items.get(position).getIsChecked());
if (tmp != null && tmp.compareTo("TRUE") == 0)
{
allItems.price.setVisibility(View.VISIBLE);
allItems.price.setText("(" + Double.toString(items.get(position).getPrice()) + "€)");
}
else
allItems.price.setVisibility(View.INVISIBLE);
allItems.chkTick.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
items.get(pos).setIsChecked(isChecked);
getPos(buttonView);
if (isChecked)
{
if (tmp != null && tmp.compareTo("TRUE") == 0)
ShowPopup(activity, p, pos);
}
_sqlHelper.updateShoppingListItem(items.get(pos));
}
});
allItems.delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(ListItemsAdaptor.this.activity);
builder.setCancelable(false);
builder.setTitle("Delete Item");
builder.setMessage("Are you sure you want to delete this item ?");
builder.setPositiveButton("Update", null);
builder.setNegativeButton("Cancel", null);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
_sqlHelper.deleteShoppingListItemByIdItem(items.get(pos).getListId(), items.get(pos).getItemId());
items.remove(pos);
updateResults(items);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
builder.show();
}
});
allItems.plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
items.get(pos).setQuantity(items.get(pos).getQuantity()+ 1);
updateResults(items);
_sqlHelper.updateShoppingListItem(items.get(pos));
}
});
allItems.minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (items.get(pos).getQuantity() > 1){
items.get(pos).setQuantity(items.get(pos).getQuantity()- 1);
updateResults(items);
_sqlHelper.updateShoppingListItem(items.get(pos));
}
}
});
return (convertView);
}
Thank you for helping guys !

I recomends that youuse a private ListArray checkedItems and add or remove in checked ones, after all, pass or use this list Array after the code.

I think you need to call the adapter's notifyDataSetChanged() method in your onCheckedChangeListener (and after every time you change the items)

Related

listview itemclick set text to textview issue

In my listview, when I long press row 1 it should change the amount of a textview in row 1. However I have a problem, when I try to change the amount of the specific row (example: row 1), the 5th row of the listview also changes. Also, when the listview is recycled, the textview returns to its old value. Been trying to solve this for a day already but to no luck.
Any help is appreciated!
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final ViewHolder holder;
if (mView == null) {
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.row_layout, null, false);
holder = new ViewHolder();
holder.tx_number = (TextView) mView.findViewById(R.id.tx_number);
holder.tx_amount = (TextView) mView.findViewById(R.id.tx_amount);
holder.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}
try this. please add this two methods if not added
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
Add notifyDataSetChange on positive button click listener.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
you should learn the listview lifecycle. however if you want to do that you have to change the item data from the datasource which in this case , its mData. and after updateting the item call notifyItemchanged() on adapter to apply the item in listview. the reason for after recycling you see the old data is that the list gets data from mData and you just updated the View. so instead of geting the viewholder. get item by position in longclick and after you updated the item just call notifyItemChanged(position);
First you missed }); in your code before mView.setTag(holder);, so your code will have compile issues which I think you should have seen.
Second, you should not call listView.setOnItemLongClickListener in getView. Because this will repeat many times depends on how many items visible in your screen.
Finally, you should update the data source, i.e.: mData in your code, with the latest data, and then call adapter.notifyDatasetChanged() to update the UI.
So your code should be something like below:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
// Remove codes below
// txAmt.setText(zzx);
// holder.tx_status.setText(zzx);
// holder.tx_amount.setText(zzx);
mData.get(position).setXXX(zzx); // call the setter of your data model
adapter.notifyDatasetChanged(); // call this will update the listview with the latest data
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
});
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final ViewHolder holder;
if (mView == null) {
Context context = viewGroup.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
mView = inflater.inflate(R.layout.row_layout, null, false);
holder = new ViewHolder();
holder.tx_number = (TextView) mView.findViewById(R.id.tx_number);
holder.tx_amount = (TextView) mView.findViewById(R.id.tx_amount);
holder.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}

CheckBox state is not maintain in Listview

I am setting checkbox for deleting multiple item.When I checked element my Add button changes
to delete but when i scroll the listview ,my delete button changes to add button but it should not be happed until all checkbox are unchecked .for maintaining delete and add button in action bar i am using a List box when I click on Check i am setting current position of element to checkbox, and when checkbox is unchecked removing that position from checkbox.
Here My problem is that when check box is checked, the add sign changes to the
delete icon. When I scroll and the checked record is not on the screen, the
delete icon changes to add icon and when I scroll back to the checked
record, the delete icon comes back. I am very confusing about this checkbox in Listview.Please check my code help me.
Thanks in advance
package com.office.sdpa.custom.classes;
public class ManagePracAdapter extends ArrayAdapter {
private final List<Model> list;
private final Activity context;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
List<Integer> SelectedBox= new ArrayList<Integer>();
MenuItem Delete,addlog;
public ManagePracAdapter(Activity context, List<Model> list,MenuItem mymenu,MenuItem myaddlog) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
Delete=mymenu;
addlog=myaddlog;
}
static class ViewHolder {
protected TextView text;
protected TextView datetime;
protected TextView weather;
protected TextView duration;
protected TextView supervisor;
protected TextView day_night_icon;
protected CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.logitem1, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.id_skills);
viewHolder.datetime = (TextView) convertView.findViewById(R.id.id_datetime);
viewHolder.weather = (TextView) convertView.findViewById(R.id.id_weather);
viewHolder.duration=(TextView) convertView.findViewById(R.id.totminutes);
viewHolder.supervisor=(TextView) convertView.findViewById(R.id.conditions);
viewHolder.day_night_icon=(TextView) convertView.findViewById(R.id.day_night_icon);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.id_chkDelete);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
if(SelectedBox.size()-1==0)
{
Delete.setVisible(false);
addlog.setVisible(true);
}else
{
addlog.setVisible(false);
}
if(isChecked)
{
SelectedBox.add(position);
Delete.setVisible(true);
addlog.setVisible(false);
}else /*if(!isChecked)*/
{
SelectedBox.remove(SelectedBox.indexOf(position));
}
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.id_skills, viewHolder.text);
convertView.setTag(R.id.id_chkDelete, viewHolder.checkbox);
convertView.setTag(R.id.id_datetime,viewHolder.datetime);
convertView.setTag(R.id.id_weather,viewHolder.weather);
convertView.setTag(R.id.totminutes,viewHolder.duration);
convertView.setTag(R.id.conditions,viewHolder.supervisor);
convertView.setTag(R.id.day_night_icon,viewHolder.day_night_icon);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.datetime.setText(list.get(position).getDatetime());
viewHolder.weather.setText(list.get(position).getWeather());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
if(!list.get(position).getDay_minutes().toString().equalsIgnoreCase("0"))
{
viewHolder.duration.setText(list.get(position).getDay_minutes());
viewHolder.day_night_icon.setBackgroundResource(R.drawable.sun);
}else
{
viewHolder.duration.setText(list.get(position).getNight_minutes());
viewHolder.day_night_icon.setBackgroundResource(R.drawable.moon);
}
if(list.get(position).getSupervisor().equals("No supervisor"))
{
viewHolder.supervisor.setBackgroundResource(R.drawable.pending);
}else
{
viewHolder.supervisor.setBackgroundResource(R.drawable.approve);
}
String fontPath = "fonts/Roboto-Light.ttf";
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
viewHolder.datetime.setTypeface(tf);
viewHolder.duration.setTypeface(tf);
viewHolder.text.setTypeface(tf);
viewHolder.weather.setTypeface(tf);
Delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Student Driving Practice Log");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure want to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
try
{
NewNewDataHelper db=new NewNewDataHelper(context);
if(!SelectedBox.isEmpty())
{
for(int i=0;i<SelectedBox.size();i++)
{
// resultp=data.get(SelectedBox.get(i));
String str[]=list.get(i).getDatetime().split(" ");
Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+list.get(i).getName());
db.DeleteSingleLog(list.get(i).getName(),str[0],str[1]);
/*resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/
Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();
}
Log.d("LISTSTSTSTST", SelectedBox.toString());
Intent intent = new Intent(context,ManagePracticeLogActivity.class);
intent.putExtra("s11", "delete");
context.startActivity(intent);
}
}catch(Exception e)
{
}
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return false;
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str1 = null;
String str[]=list.get(position).getDatetime().split(" ");
Log.d("PARTICULAR SKILLLLL",str[1]);
str1=str[0]+"~"+list.get(position).getName()+"~"+str[1];
Log.d("PARTICULAR SKILLLLL", str1);
Intent intent = new Intent(context,LogEdit.class);
intent.putExtra("s11","Update Practice");
intent.putExtra("dataupdate",str1);
context.startActivity(intent);
}
});
return convertView;
}
}
Try to replace your adapter getView().
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.logitem1, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.id_skills);
viewHolder.datetime = (TextView) convertView.findViewById(R.id.id_datetime);
viewHolder.weather = (TextView) convertView.findViewById(R.id.id_weather);
viewHolder.duration=(TextView) convertView.findViewById(R.id.totminutes);
viewHolder.supervisor=(TextView) convertView.findViewById(R.id.conditions);
viewHolder.day_night_icon=(TextView) convertView.findViewById(R.id.day_night_icon);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.id_chkDelete);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.text.setText(list.get(position).getName());
viewHolder.datetime.setText(list.get(position).getDatetime());
viewHolder.weather.setText(list.get(position).getWeather());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
if(!list.get(position).getDay_minutes().toString().equalsIgnoreCase("0"))
{
viewHolder.duration.setText(list.get(position).getDay_minutes());
viewHolder.day_night_icon.setBackgroundResource(R.drawable.sun);
}else
{
viewHolder.duration.setText(list.get(position).getNight_minutes());
viewHolder.day_night_icon.setBackgroundResource(R.drawable.moon);
}
if(list.get(position).getSupervisor().equals("No supervisor"))
{
viewHolder.supervisor.setBackgroundResource(R.drawable.pending);
}else
{
viewHolder.supervisor.setBackgroundResource(R.drawable.approve);
}
String fontPath = "fonts/Roboto-Light.ttf";
Typeface tf = Typeface.createFromAsset(context.getAssets(), fontPath);
viewHolder.datetime.setTypeface(tf);
viewHolder.duration.setTypeface(tf);
viewHolder.text.setTypeface(tf);
viewHolder.weather.setTypeface(tf);
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
list.get(position).setSelected(isChecked); // Set the value of checkbox to maintain its state.
if(SelectedBox.size()-1==0)
{
Delete.setVisible(false);
addlog.setVisible(true);
}else
{
addlog.setVisible(false);
}
if(isChecked)
{
SelectedBox.add(position);
Delete.setVisible(true);
addlog.setVisible(false);
}else /*if(!isChecked)*/
{
SelectedBox.remove(SelectedBox.indexOf(position));
}
}
});
Delete.setOnMenuItemClickListener(new OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("Student Driving Practice Log");
// set dialog message
alertDialogBuilder
.setMessage("Are you sure want to Delete Record!")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
try
{
NewNewDataHelper db=new NewNewDataHelper(context);
if(!SelectedBox.isEmpty())
{
for(int i=0;i<SelectedBox.size();i++)
{
// resultp=data.get(SelectedBox.get(i));
String str[]=list.get(i).getDatetime().split(" ");
Log.d("Checked Element",str[0]+"\n"+str[1]+"\n"+list.get(i).getName());
db.DeleteSingleLog(list.get(i).getName(),str[0],str[1]);
/*resultp=data.get(SelectedBox.get(i));
String str[]=resultp.get("date_time").split(" ");
db.DeleteSingleLog(resultp.get("Skill"),str[0],str[1]);*/
Toast.makeText(context,"Record Deleted", Toast.LENGTH_LONG).show();
}
Log.d("LISTSTSTSTST", SelectedBox.toString());
Intent intent = new Intent(context,ManagePracticeLogActivity.class);
intent.putExtra("s11", "delete");
context.startActivity(intent);
}
}catch(Exception e)
{
}
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
return false;
}
});
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String str1 = null;
String str[]=list.get(position).getDatetime().split(" ");
Log.d("PARTICULAR SKILLLLL", str[1]);
str1=str[0]+"~"+list.get(position).getName()+"~"+str[1];
Log.d("PARTICULAR SKILLLLL", str1);
Intent intent = new Intent(context,LogEdit.class);
intent.putExtra("s11","Update Practice");
intent.putExtra("dataupdate",str1);
context.startActivity(intent);
}
});
return convertView;
}
Try to make your getView method as follows:
public class ViewHolder
{
TextView contactname, statusmsg, msisdnview, imgview, chatstsview;
ImageView img;
CheckBox contactCheckBox;
}
ViewHolder holder = null;
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
holder=new ViewHolder();
View rowView = convertView;
if(rowView == null)
{
rowView = inflater.inflate(R.layout.contact_list, null);
holder.contactname=(TextView) rowView.findViewById(R.id.textView1);
holder.statusmsg=(TextView) rowView.findViewById(R.id.textView2);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.contactCheckBox = (CheckBox) rowView.findViewById(R.id.contactchk);
rowView.setTag(holder);
}
else
{
holder = (ViewHolder) rowView.getTag();
}
holder.contactname.setTag("textview_"+msisdn[position]);
holder.contactCheckBox.setTag("checkbox_"+msisdn[position]);
holder.contactname.setText(result[position]);
ImageLoader img = new ImageLoader(context);
img.DisplayImage(imageId[position], loader, holder.img);
holder.statusmsg.setText(status[position]);
holder.contactCheckBox.setTag(position);
holder.contactCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
// TODO Auto-generated method stub
int getPosition = (Integer) buttonView.getTag();
isCheckedCheckBox[getPosition] = buttonView.isChecked();
}
});
if(isCheckedCheckBox[position])
{
holder.contactCheckBox.setChecked(true);
}
else
{
holder.contactCheckBox.setChecked(false);
}
holder.contactCheckBox.setOnClickListener(null);
rowView.setTag(holder);
return rowView;
}
This should solve your issue.

Setting TextViews from an onClick(View v) within an onClick(View v)?

This line will not set, holder.t1.setText(NewItem);
If I move it to the parent onClick, with a hardcoded string (for testing) it does.
Keep in mind, this is inside a getView method of an ArrayAdapter. I am trying to setText to ListView rows.
Edit:
EXPANDED, COMPLETE getView() -- AS REQUESTED
(Did not have time to edit, will later, sorry!)
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.commentlayout, parent,
false);
holder = new ViewHolder();
holder.t1 = (TextView) convertView.findViewById(R.id.labelComment);
holder.t2 = (TextView) convertView.findViewById(R.id.labelDate);
holder.t3 = (TextView) convertView.findViewById(R.id.labelUser);
holder.t3.setTypeface(tf);
holder.t4 = (TextView) convertView
.findViewById(R.id.labelHelpfulCount);
holder.t5 = (TextView) convertView
.findViewById(R.id.labelCommentCount);
holder.ib1 = (ImageView) convertView
.findViewById(R.id.labelChatIcon);
holder.ib2 = (ImageView) convertView
.findViewById(R.id.labelCommentFlag);
holder.rb1 = (RatingBar) convertView
.findViewById(R.id.myCommentsRatingBarSmall);
holder.b1 = (Button) convertView.findViewById(R.id.bReview1);
holder.b2 = (Button) convertView.findViewById(R.id.bReview2);
holder.b3 = (Button) convertView.findViewById(R.id.bReview3);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
convertView.setOnCreateContextMenuListener(null);
}
ReviewObject ro = getItem(position);
final String item = ro.item;
final String review = ro.review;
final String username = ro.username;
Long date = Long.valueOf(ro.date);
String rating = ro.ratings;
String voteCount = ro.voteCount;
String chatcount = ro.chatCount;
String cat = ro.cat;
final ArrayList<String> passing = new ArrayList<String>();
passing.add(item);
passing.add(review);
passing.add(cat);
passing.add(username);
String time = "";
time = DateConvert.dateConvert(Long.valueOf(date));
holder.t1.setText(review);
holder.t2.setText(time);
holder.t3.setText(username);
holder.t4.setText(voteCount);
holder.t5.setText(chatcount);
holder.ib1.setImageResource(R.drawable.updown);
holder.ib2.setImageResource(R.drawable.comment);
holder.rb1.setRating(Float.valueOf(rating));
if (rating.equals("0")) {
holder.rb1.setEnabled(false);
}
holder.b1.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String ReviewUser = holder.t3.getText().toString();
String ReviewWords = holder.t1.getText().toString();
Intent intent = new Intent(getContext(), Comments.class);
intent.putExtra("comment", ReviewWords);
intent.putExtra("user", ReviewUser);
intent.putExtra("item", item);
getContext().startActivity(intent);
}
});
if (!Rateit.username.equals(username)) {
holder.b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(getContext());
alertbox.setMessage("Did you like this?");
alertbox.setNegativeButton("Vote Up",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface arg0,
int arg1) {
String VoteTally = holder.t4.getText()
.toString();
int ReviewCountInt = Integer
.valueOf(VoteTally) + 1;
VoteTally = String.valueOf(ReviewCountInt);
holder.t4.setText(VoteTally);
new HelpfulTask().execute(passing);
}
});
alertbox.setPositiveButton("Vote Down",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog,
int id) {
String VoteTally = holder.t4.getText()
.toString();
int ReviewCountInt = Integer
.valueOf(VoteTally) - 1;
VoteTally = String.valueOf(ReviewCountInt);
holder.t4.setText(VoteTally);
new UnHelpfulTask().execute(passing);
}
});
alertbox.setNeutralButton("Report Spam",
new DialogInterface.OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(DialogInterface dialog,
int id) {
new SpamTask().execute(passing);
}
});
alertbox.show();
}
});
} else {
holder.b2.setText("Edit");
holder.b2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Dialog dialog = new Dialog(getContext());
dialog.setContentView(R.layout.editreview);
dialog.setTitle("Edit Review");
dialog.show();
final EditText etEdit = (EditText) dialog
.findViewById(R.id.etEditReview);
etEdit.setText(review);
Button bInsert = (Button) dialog.findViewById(R.id.bInsert);
bInsert.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
NewItem = etEdit.getText().toString();
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
} else {
holder.t1.setText(NewItem);
passing.add(NewItem);
dialog.dismiss();
new EditCommentTask().execute(passing);
}
}
});
}
});
}
if (!Rateit.username.equals(username)) {
holder.b3.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(getContext(), OtherProfile.class);
i.putExtra("userprofile", username);
getContext().startActivity(i);
}
});
} else {
holder.b3.setText("Delete");
holder.b3.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(
getContext());
alertbox.setMessage("Are you sure you want to delete your review?");
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
}
});
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
new DeleteReviewTask().execute(passing);
}
});
alertbox.show();
}
});
}
return convertView;
}
From what you've said in the above comments, this is the intended function. Since,
Except, the dialog does dismiss, I get the toast and the task runs correctly.
This is coded into your onClick() here:
bInsert.setOnClickListener(new OnClickListener() {
#SuppressWarnings("unchecked")
public void onClick(View v) {
NewItem = etEdit.getText().toString();
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
} else {
holder.t1.setText(NewItem);
passing.add(NewItem);
dialog.dismiss();
new EditCommentTask().execute(passing);
}
}
});
Specifically, this is executing:
if (NewItem.equals("")) {
Toast.makeText(getContext(),
"Please add something first.",
Toast.LENGTH_SHORT).show();
}
so I am assuming your problem is with NewItem, I never see where you actually initialize it, but I am assuming it .equals("") since this is executing. Try throwing a Log.d or println() just below the line NewItem = etEdit.getText().toString(); to see what the value of NewItem is at this point.

Deleting list item form list view in android

I read many more realted to this problem but not getting more idea. After this, i am trying to post, here in this picture I have 3 items on list, I have 2 item click. So I want to delete these two checked item. But i am the newbie for android, So could not get more idea behind this.
Code
public class CountryList extends Activity implements OnClickListener,
OnItemClickListener {
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempCountry.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.country);
holder.checkBox = (CheckedTextView) convertView
.findViewById(android.R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtcnt.setText(country[position]);
return convertView;
}
static class ViewHolder {
TextView txtcnt;
CheckBox checkBox;
}}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
lv = (ListView) findViewById(R.id.list);
btn_delete = (Button) findViewById(R.id.delete);
btn_delete.setOnClickListener(this);
checkbox = (CheckBox) findViewById(R.id.checkbox);
txtname= (TextView) findViewById(R.id.body);
String name= pref.getString("name", "");
country= name.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setMessage("Are you Sure want to delete checked country ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// how to remove country
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Delete Country");
alert.show();
case R.id.checkbox:
//What is the procedue in this section
default:
break;
}
}
public void onItemClick(AdapterView<?> pareant, View view, int position,
long id) {
try {
// I have trying this but could not proper output or only errors
SparseBooleanArray sp = lv.getCheckedItemPositions();
/*String str = "";
for (int i = 0; i < sp.size(); i++) {
str += country[sp.keyAt(i)] + ",";
}*/
} catch (Exception e) {
e.printStackTrace();
}}}
This is the only three country, actually, I have more then hundreds countries.
Delete items from tempCountry and then call adapter.notifyDataSetChanged().
Have a button on list and let it onclick feature in xml
like to get postion first
public void OnClickButton(View V){
final int postion = listView.getPositionForView(V);
System.out.println("postion selected is : "+postion);
Delete(postion);
}
public void Delete(int position){
if (adapter.getCount() > 0) {
//Log.d("largest no is",""+largestitemno);
//deleting the latest added by subtracting one 1
comment = (GenrricStoring) adapter.getItem(position);
//Log.d("Deleting item is: ",""+comment);
dbconnection.deleteComment(comment);
List<GenrricStoring> values = dbconnection.getAllComments();
//updating the content on the screen
this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
else
{
int duration = Toast.LENGTH_SHORT;
//for showing nothing is left in the list
Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}

Nothing to deleted checked item in listview in android

I am trying to deleted checked item in listview in android, but I haven't achive this, why? my code is below. please response . I have try this code as well , which has not get more idea.
How to delete check box items from list
and many more related to delete list item form list view.
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static String[] tempTitle = new String[100];
static String[] tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle[position]);
holder.text2.setText(tempBody[position]);
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.length;b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
tempTitle = one.split(",");
tempBody = two.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}
please update this code with no errors. Or give be best idea for this.
You are removing items from a list while traversing it. At least you must make sure to account for the removed item in the counter variable and the list size (which is why there is an i-- in the original code, but you have commented it out).
I.e. after you deleted the item with index 2, the next in the list is still 2, not 3.
Un-comment the i--, that should fix it.
you want to delete checked item, but not modifying data source of list, please load data source from checks list. as Below:
public class BookmarksJokes extends Activity implements OnClickListener,
OnItemClickListener {
ListView lv;
static ArrayList<Integer> checks=new ArrayList<Integer>();
static ArrayList<String> tempTitle = new String[100];
static ArrayList<String> tempBody = new String[100];
static String[] pos = new String[100];
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempTitle.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.titleJok);
holder.text2 = (TextView) convertView
.findViewById(R.id.bodyJok);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkBox.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(((CheckBox)v).isChecked()){
checks.set(position, 1);
}
else{
checks.set(position, 0);
}
}
});
holder.text1.setText(tempTitle.get(position));
holder.text2.setText(tempBody.get(position));
return convertView;
}
class ViewHolder {
TextView text1;
TextView text2;
CheckBox checkBox;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
setUpViews();
for(int b=0;b<tempTitle.size();b++){
checks.add(b,0); //Assign 0 by default in each position of ArrayList
}
String one = pref.getString("title", "");
String two = pref.getString("body", "");
String[] tokens = one.split(",");
tempTitle=Arrays.asList(tokens);
tokens= two.split(",");
tempBody =Arrays.asList(tokens);
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this);
alt_bld.setMessage("Are you Sure want to delete all checked jok ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
for(int i=0;i<checks.size();i++){
if(checks.get(i)==1){
Log.d(TAG, "i Value >>"+i);
checks.remove(i);
tempTitle.remove(i);
tempBody.remove(i);
// i--;
Log.d(TAG, "checked Value >>"+checks);
Log.d(TAG, "i Value -- >>"+i);
}
}
((EfficientAdapter)lv.getAdapter()).notifyDataSetChanged();
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
alert.setTitle("Delete Jokes");
alert.show();
case R.id.checkbox:
default:
break;
}
}

Categories

Resources