ToggleButton enable other toggle button automatically in listview in android? - android

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.

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;
}
}

How to compare two arraylist and enable toggle accordingly in android

I have an app in which listview with two arraylist suppose 1st "listStorage" and second is "existingDataSet" i have to compare these two arraylist value if found same then enable toggle of that index.
code:-
private LayoutInflater layoutInflater;
private List<AllAppList> listStorage;
private Context mContext;
ArrayList<WhiteListModel> newDataSet, existingDataSet;
private String TAG = AppAdapter.class.getSimpleName();
private MySharedPreference sharedPreference;
private WhiteListModel whiteListModel;
private Gson gson;
public AppAdapter(Context context, List<AllAppList> customizedListView) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
listStorage = customizedListView;
this.mContext = context;
existingDataSet = new ArrayList<>();
newDataSet = new ArrayList<>();
gson = new Gson();
sharedPreference = new MySharedPreference(mContext);
whiteListModel = new WhiteListModel();
//retrieve data from shared preference
String jsonScore = sharedPreference.getAppsArrayListData();
Type type = new TypeToken<ArrayList<WhiteListModel>>() {
}.getType();
existingDataSet = gson.fromJson(jsonScore, type);
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#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());
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
listViewHolder.switchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(final CompoundButton buttonView, 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 which) {
//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);
}
//Notifying adapter data has been changed.....
notifyDataSetChanged();
listViewHolder.switchCompat.setChecked(false);
}
}).setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
listViewHolder.switchCompat.setChecked(false);
}
}).show();
}
}
});
return convertView;
}
/**
* Save list of scores to own sharedpref
*
* #param whiteListApps
*/
private void saveScoreListToSharedpreference(ArrayList<WhiteListModel> whiteListApps) {
Gson gson = new Gson();
//convert ArrayList object to String by Gson
String jsonScore = gson.toJson(whiteListApps);
Log.e(TAG, "LIST::" + jsonScore);
//save to shared preference
sharedPreference.saveAppsArrayListData(jsonScore);
}
private static class ViewHolder {
static SwitchCompat switchCompat;
TextView textInListView;
ImageView imageInListView;
}
}
for (int i = 0 ; i < existingDataSet.size() ; i++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(i).getPackName())){
listViewHolder.switchCompat.setChecked(true);
}
}
}
can you try this? switch should retain its value false if not contains within 2 list when on getView because it trigger several times.
boolean isChecked = false
for (int i = 0; i<existingDataSet.size(); i++){
for (int j= 0; j<listStorage.size(); j++){
if (existingDataSet.get(i).getPackName().equalsIgnoreCase(listStorage.get(j).getPackName())){
isChecked = true;
}
}
}
listViewHolder.switchCompat.setChecked(isChecked);

Refresh ListView pressing option DialogFragment

I have a listview that clicking on an element shows a DialogFragmen with several options, options that take the user will be shown in the item of listview TextView and I get the following error in execution:
Activity app.gepv.Inventario has leaked IntentReceiver com.immersion.android.haptics.HapticFeedbackManager$HapticFeedbackBroadcastReceiver#426e94b8 that was originally registered here. Are you missing a call to unregisterReceiver()?
Enter the code that I think is important, if you need anything else edit the question :)
This is mi DialogFragment:
final String[] items= equiDisp.toArray(new String[equiDisp.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Asigne equipo/equipos:")
.setOnKeyListener(new Dialog.OnKeyListener(){
public boolean onKey(DialogInterface arg0, int keyCode,KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == KeyEvent.KEYCODE_BACK)
{
finish();
//dialog.dismiss();
actualizarDisplay();
}
return true;
}
})
.setMultiChoiceItems(items, null, new DialogInterface.OnMultiChoiceClickListener() {
public void onClick(DialogInterface dialog, int item, boolean isChecked) {
Log.i("Dialogos", "OpciĆ³n elegida: " + items[item]);
if(isChecked)
{
marcado.add(items[item]);
Log.i("Dialogos", "Marcado: " + items[item]);
obras.get(pulsado).equiA.add(Integer.parseInt(items[item]));
for( int k=0; k< obras.get(pulsado).equiA.size(); k++)
{
Log.i("Dialogos", "Equipos: " + obras.get(pulsado).equiA.get(k) );
}
}
}
});
So far everything is running well because I check with Log.i
This is the function ActualizarDisplay():
public void actualizarDisplay()
{
adapter = new ObrasAdapter(this, obras);
lvObras = (ListView) findViewById(R.id.lvItems);
lvObras.setAdapter(adapter);
lvObras.setOnItemClickListener(this);
}
And this is my custom dataApdapter for the listview:
public class ObrasAdapter extends ArrayAdapter<Obra> {
private Context context;
private ArrayList<Obra> datos;
public ObrasAdapter(Context context, ArrayList<Obra> datos) {
super(context, R.layout.listview_item, datos);
this.context = context;
this.datos = datos;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View item = convertView;
ObrasHolder holder;
if (item == null) {
item = LayoutInflater.from(context).inflate(R.layout.listview_item,
null);
holder = new ObrasHolder();
holder.foto = (ImageView) item.findViewById(R.id.imgAnimal);
holder.num = (TextView) item.findViewById(R.id.numC);
holder.iden = (TextView) item.findViewById(R.id.idenC);
holder.ubi = (TextView) item.findViewById(R.id.ubiC);
holder.hombres = (TextView) item.findViewById(R.id.homC);
holder.material = (TextView) item.findViewById(R.id.matC);
holder.eq1 = (TextView) item.findViewById(R.id.eq1);
holder.eq2 = (TextView) item.findViewById(R.id.eq2);
holder.eq3 = (TextView) item.findViewById(R.id.eq3);
holder.eq4 = (TextView) item.findViewById(R.id.eq4);
holder.fondo = (RelativeLayout) item.findViewById(R.id.fondobra);
item.setTag(holder);
}
holder = (ObrasHolder) item.getTag();
holder.foto.setImageResource(datos.get(position).getDrawableImageID());
if(datos.get(position).getPrioridad()==1)
{
holder.num.setTextColor(Color.RED);
holder.iden.setTextColor(Color.RED);
holder.ubi.setTextColor(Color.RED);
holder.hombres.setTextColor(Color.RED);
holder.material.setTextColor(Color.RED);
holder.eq1.setTextColor(Color.RED);
holder.eq2.setTextColor(Color.RED);
holder.eq3.setTextColor(Color.RED);
holder.eq4.setTextColor(Color.RED);
}
if(datos.get(position).getPrioridad()==2)
{
holder.num.setTextColor(Color.parseColor("#FF8000"));
holder.iden.setTextColor(Color.parseColor("#FF8000"));
holder.ubi.setTextColor(Color.parseColor("#FF8000"));
holder.hombres.setTextColor(Color.parseColor("#FF8000"));
holder.material.setTextColor(Color.parseColor("#FF8000"));
holder.eq1.setTextColor(Color.parseColor("#FF8000"));
holder.eq2.setTextColor(Color.parseColor("#FF8000"));
holder.eq3.setTextColor(Color.parseColor("#FF8000"));
holder.eq4.setTextColor(Color.parseColor("#FF8000"));
}
if(datos.get(position).getPrioridad()==3)
{
holder.num.setTextColor(Color.GREEN);
holder.iden.setTextColor(Color.GREEN);
holder.ubi.setTextColor(Color.GREEN);
holder.hombres.setTextColor(Color.GREEN);
holder.material.setTextColor(Color.GREEN);
holder.eq1.setTextColor(Color.GREEN);
holder.eq2.setTextColor(Color.GREEN);
holder.eq3.setTextColor(Color.GREEN);
holder.eq4.setTextColor(Color.GREEN);
}
holder.num.setText(datos.get(position).getNum());
holder.iden.setText(datos.get(position).getIden());
holder.ubi.setText(datos.get(position).getUb());
holder.hombres.setText(datos.get(position).getHom());
holder.material.setText(datos.get(position).getMat());
if(datos.get(position).getEstado()==1)
{
holder.fondo.setBackgroundColor(Color.GREEN);
holder.num.setTextColor(Color.WHITE);
holder.iden.setTextColor(Color.WHITE);
holder.ubi.setTextColor(Color.WHITE);
holder.hombres.setTextColor(Color.WHITE);
holder.material.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
holder.eq1.setTextColor(Color.WHITE);
}
if(! datos.get(position).equiA.isEmpty())
{
for(int i=0; i<datos.get(position).equiA.size();i++)
{
if(i == 0)
{
holder.eq1.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
if(i == 1)
holder.eq2.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 2)
holder.eq3.setText(String.valueOf(datos.get(position).equiA.get(i)));
if(i == 3)
holder.eq4.setText(String.valueOf(datos.get(position).equiA.get(i)));
}
}
else
{
holder.eq1.setVisibility(View.INVISIBLE);
holder.eq2.setVisibility(View.INVISIBLE);
holder.eq3.setVisibility(View.INVISIBLE);
holder.eq4.setVisibility(View.INVISIBLE);
}
return item;
}
}
Can anyone help me?
I think i must to do something as:
#Override
protected void onStop()
{
unregisterReceiver(sendBroadcastReceiver);
unregisterReceiver(deliveryBroadcastReceiver);
super.onStop();
}

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.

checkbox auto checked item after remove item

after remove item selected check box auto check next item.
i try to override getcount method but no result
CountryAdapter.java
CountryAdapter extends ArrayAdapter<MyCountry>{
Context context; int layoutResourceId; ArrayList<MyCountry> countries; ContextualActionMode activity;
public CountryAdapter(Context context, int layoutResourceId,
ArrayList<MyCountry> countries) {
}
#Override
public int getCount() {
return countries.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final MyCountry country = countries.get(position);
ViewHolder viewHolder = null;
if(convertView == null)
{
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layoutResourceId, null);
viewHolder.nameEn = (TextView) convertView.findViewById(R.id.tvNameEn);
viewHolder.nameVi = (TextView) convertView.findViewById(R.id.tvNameVi);
viewHolder.flag = (ImageView) convertView.findViewById(R.id.ivFlag);
viewHolder.check = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) convertView.getTag();
viewHolder.nameEn.setText(countries.get(position).getNameEn());
viewHolder.nameVi.setText(countries.get(position).getNameVi());
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
count = 0;
for (MyCountry country : countries) {
if(country.isCheck()) count++;
}
if(isChecked)
{
if(activity.actionMode == null || count == 0)
activity.actionMode = activity.startActionMode(activity.callback);
count++;
country.setCheck(true);
}
else
{
country.setCheck(false);
count--;
if(count == 0) activity.actionMode.finish();
}
}
});
return convertView;
}
int count = 0;
public class ViewHolder{
TextView nameEn;
TextView nameVi;
ImageView flag;
CheckBox check;
}
ContextualActionMode.java
public class ContextualActionMode extends Activity {
ArrayList<MyCountry> countries = new ArrayList<MyCountry>();
ListView listView;
CountryAdapter adapter;
ActionMode.Callback callback = new ActionMode.Callback() {
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.mnDelete:
for (int i = 0; i < countries.size(); i++)
{
if (countries.get(i).isCheck()) {
countries.remove(countries.get(i));
countries.get(i).setChecked(false)
}
}
adapter.notifyDataSetChanged();
mode.finish();
return true;
default:
break;
}
return false;
}
};
maybe error here, i find some solutions, but nothing work
i try to change the loop, because the list start index from 0
// i can fix it, thank a lot to Armaan Stranger
link to my source for who has the same problem with me
mediafire.com/?agnvic06c69cvw0
and edit in CountryAdapter.java
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setChecked(false); --> right here, i forgot to add set check false as default.
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
Try this:
Just add this line before your onCheckChanged() event like this.
viewHolder.nameEn.setText(countries.get(position).getNameEn());
viewHolder.nameVi.setText(countries.get(position).getNameVi());
viewHolder.flag.setImageDrawable(countries.get(position).getFlag());
viewHolder.check.setChecked(false);
viewHolder.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
count = 0;
for (MyCountry country : countries) {
if(country.isCheck())
count++;
}
if(isChecked)
{
if(activity.actionMode == null || count == 0)//chua co
activity.actionMode = activity.startActionMode(activity.callback);
count++;
country.setCheck(true);
}
else
{
country.setCheck(false);
count--;
if(count == 0)
activity.actionMode.finish();
}
}
});
Hope it Helps!!
You have to just set your listview before notifyDataSetChanged();
public void dellistview() {
listviewdata.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
SparseBooleanArray selected = listAdapterData.getCheckedItemPositions();
if (selected != null) {
try {
for (int i = (selected.size() - 1); i >= 0; i--)
{
if (selected.valueAt(i)) {
String str[] = arrList.get(selected.keyAt(i));
fmdbAccess.removelistitm(sourceTable, str[1]);
if (arrList != null)
arrList.remove(str);
}
}
} catch (Exception e) {
e.printStackTrace();
}
selected.clear();
arrList = fmdbAccess.getGenricTable(sourceTable, colName);
if (arrList != null && arrList.size() > 0)
setListAdapter();
listAdapterData.notifyDataSetChanged();
// finish();
}
}
Try to use android:checked="false" to CheckBox in your xml file please

Categories

Resources