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;
}
}
Related
I have a listview with toggle button and some data in listview. Let suppose I enable toggle at position 1 it works fine, and then I enable toggle at the position it automatically disable toggle at position 1. Please help me out.
code:-
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder listViewHolder;
if (convertView == null) {
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list_item, parent, false);
listViewHolder.textInListView = (TextView) convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView) convertView.findViewById(R.id.app_icon);
listViewHolder.switchCompat = (SwitchCompat) convertView.findViewById(R.id.toggleButton);
convertView.setTag(listViewHolder);
} else {
listViewHolder = (ViewHolder) convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
listViewHolder.switchCompat.setOnCheckedChangeListener(null);
boolean isCheck = false;
AllAppList model = listStorage.get(position);
if (existingDataSet != null) {
for (int i = 0; i < existingDataSet.size(); i++) {
if (model.getPackName().equalsIgnoreCase(existingDataSet.get(i).getPackName())) {
isCheck = true;
}
}
listViewHolder.switchCompat.setChecked(isCheck);
}
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, final boolean isChecked) {
if (isChecked) {
new AlertDialog.Builder(mContext, R.style.AppCompatAlertDialogStyle).setTitle("Warning").setMessage("You want to whiteList this application?").setPositiveButton("YES", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int pos) {
//Adding items in Dataset
AllAppList appList = listStorage.get(position);
whiteListModel.setName(appList.getName());
whiteListModel.setPackName(appList.getPackName());
if (existingDataSet!=null){
existingDataSet.add(whiteListModel);
saveScoreListToSharedpreference(existingDataSet);
}else {
newDataSet.add(whiteListModel);
saveScoreListToSharedpreference(newDataSet);
}
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(isChecked);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(isChecked);
}
}).show();
} else {
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
AllAppList model = listStorage.get(position);
if (existingDataSet != null) {
for (int i = 0; i < existingDataSet.size(); i++) {
if (model.getPackName().equalsIgnoreCase(existingDataSet.get(i).getPackName())) {
existingDataSet.remove(i);
}
}
saveScoreListToSharedpreference(existingDataSet);
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
Toast.makeText(mContext, "Removed", Toast.LENGTH_LONG).show();
}
}
}
});
return convertView;
}
Your isCheck variable is worked for the entire List.You have to make variable for each position.You can do this by making an boolean array,and make checked at that position.
I have a custom listview that contains two buttons on each line, what I am struggling with is the Listener for these buttons. My Listview is contained within a AlertDialog and this is the code I have
#Override
public void displayUnders(List<UndersLM> ulm) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
ArrayList<UndersLM> undersreturn = new ArrayList<UndersLM>();
final ListView L = new ListView(ctx);
final UndersLM y = new UndersLM();
for (UndersLM aulm : ulm) {
final UndersLM s = new UndersLM();
s.set_id(aulm.get_id());
s.set_cartonid(aulm.get_cartonid());
s.set_sku(aulm.get_sku());
s.set_sentqty(aulm.get_sentqty());
s.set_scannedqty(aulm.get_scannedqty());
undersreturn.add(s);
}
uadaptor = new Unders(ctx, undersreturn);
L.setAdapter(uadaptor);
builder.setView(L);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
L.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
});
AlertDialog d;
d = builder.create();
d.show();
}
As you can see I have tried the ItemClickListerner on the ListView its self, and the itemSelected on the AlertDialog.
What am I missing? Neither one of these ever hits the Object rid = parent.... lines
EDIT - ACTUALLY IGNORE THIS - ITS CRAP!
Ok, worked it out.
You basically have to do this (as far as I can work out) in your Custom Adaptor, so in my case this worked:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.unders, null);
holder = new ViewHolder();
holder.id = (TextView) vi.findViewById(R.id.id);
holder.cartonID = (TextView) vi.findViewById(R.id.cartonID);
holder.Sku = (TextView) vi.findViewById(R.id.Sku);
holder.Sent = (TextView) vi.findViewById(R.id.Sent);
holder.add = (Button) vi.findViewById(R.id.add);
holder.Scanned = (TextView) vi.findViewById(R.id.Scanned);
holder.subtract = (Button) vi.findViewById(R.id.subtract);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Lines.size() < -0) {
holder.id.setText("No Unprocessed Deliveries");
} else {
tempValues = null;
tempValues = (UndersLM) Lines.get(position);
holder.id.setText(String.valueOf(tempValues.get_id()));
holder.cartonID.setText(String.valueOf(tempValues.get_cartonid())+ " | ");
holder.Sku.setText(String.valueOf(tempValues.get_sku()) + " | ");
holder.Sent.setText(String.valueOf(tempValues.get_sentqty()) + " | ");
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()));
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new underCorrections(ctx,true,tempValues.get_cartonid(),tempValues.get_sku()).execute();
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()+1));
}
});
}
return vi;
}
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.
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)
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();
}
}