wrong item is being selected in listview when selecting checkbox - android

**
When i select the items which are at the bottom of the listview,they wont get selected,
rather only first four items in the list is being selected.its because the items are out of view.
what to do to get these items in view ??sometimes the item gets randomly selected.
Please help me.
thank you
Here is my code**
Main activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ExceptionAppActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private final int REQUEST_CODE = 20;
String flagg;
String empNm = Constants.Common.STR_BLNK;
String empCode = Constants.Common.STR_BLNK;
SessionManager session = null;
final Context context = this;
static Typeface custom_font = null;
TextView lblExcId, lblExcEmpNm, lblExcFrmDt, lblExcFrmDtVal, lblExcToDtVal, lblExcTyp, lblExcStat, lblExcEmpCmt;
Button btnExcRej, btnExcApp, btnExcSrch, btnExcExit;
CheckBox cb, chkBox;
ListView excSrchListView;
ArrayList<Excp> Results;
CustomListViewAdapter cla;
ExceptionAppDao eCon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exception_app_activity);
/* get Resources from Xml file */
btnExcApp = (Button) findViewById(R.id.btnExcApp);
btnExcRej = (Button) findViewById(R.id.btnExcRej);
btnExcSrch = (Button) findViewById(R.id.btnExcSrch);
btnExcExit = (Button) findViewById(R.id.btnExcExit);
lblExcEmpNm = (TextView) findViewById(R.id.lblExcEmpNm);
lblExcFrmDt = (TextView) findViewById(R.id.lblExcFrmDt);
lblExcFrmDtVal = (TextView) findViewById(R.id.lblExcFrmDtVal);
lblExcToDtVal = (TextView) findViewById(R.id.lblExcToDtVal);
lblExcTyp = (TextView) findViewById(R.id.lblExcTyp);
lblExcStat = (TextView) findViewById(R.id.lblExcStat);
lblExcEmpCmt = (TextView) findViewById(R.id.lblExcEmpCmt);
lblExcId = (TextView) findViewById(R.id.lblExcId);
chkBox = (CheckBox) findViewById(R.id.chkBx);
excSrchListView = (ListView) findViewById(R.id.excSrchListView);
// Session Manager
session = new SessionManager(getApplicationContext());
custom_font = Typeface.createFromAsset(getAssets(), "fonts/DejaVuSans.ttf");
// Connection object for Login
eCon = new ExceptionAppDao(context);
// get User Details from Session
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = session.getUserDetails();
empNm = hashMap.get(SessionManager.KEY_EMP_NM);
empCode = hashMap.get(SessionManager.KEY_EMP_CODE);
btnExcApp.setTypeface(custom_font);
btnExcRej.setTypeface(custom_font);
btnExcSrch.setTypeface(custom_font);
btnExcExit.setTypeface(custom_font);
new SyncData(empCode).execute();
if (getIntent().getBooleanExtra("EXIT", false)) {
}
// on click any button
addButtonListener();
}
/**
* on click any button
*/
private void addButtonListener() {
btnExcApp.setOnClickListener(this);
btnExcRej.setOnClickListener(this);
btnExcSrch.setOnClickListener(this);
btnExcExit.setOnClickListener(this);
}
public class SyncData extends AsyncTask<String, String, ArrayList<Excp>> {
private final ProgressDialog dialog = new ProgressDialog(context);
List<ExcpMstVo> rtnExcVo = new ArrayList<ExcpMstVo>();
ExcpMstVo rtnExcMstVo = new ExcpMstVo();
ArrayList<Excp> resultLst = new ArrayList<Excp>();
ExceptionService_Service excpServObj = new ExceptionService_Service();
String syncFlg = Constants.Common.STR_BLNK;
private View rootView;
String flag = "";
int x;
boolean success = false;
boolean successSyncFlag = false;
int countApp = 0;
public SyncData(String str) {
syncFlg = str;
}
public SyncData(View rootView) {
// TODO Auto-generated constructor stub
this.rootView = rootView;
}
#Override
protected ArrayList<Excp> doInBackground(String... params) {
ExceptionSearchCriteria vo = new ExceptionSearchCriteria();
ExcpMstVo excpMstVo = new ExcpMstVo();
try {
if (syncFlg.equals(empCode)) {
vo = setAppData(vo);
rtnExcVo = excpServObj.getExceptionPort().searchExceptionApproval(vo);
if (!(rtnExcVo.isEmpty())) {
System.out.println("rtnExcVo" + rtnExcVo.size());
Excp exc = null;
for (ExcpMstVo excMstVo : rtnExcVo) {
exc = new Excp();
exc.setExcId(excMstVo.getExcpId());
exc.setEmpCode(excMstVo.getEmpCode());
exc.setEmpNm(excMstVo.getEmpnm());
exc.setFromDt(excMstVo.getFromDt());
exc.setToDt(excMstVo.getToDt());
exc.setExcType(excMstVo.getExcpType());
exc.setExcStatus(excMstVo.getStatus());
exc.setEmpComments(excMstVo.getEmpComments());
exc.setExcFor(excMstVo.getExcpFor());
exc.setExcReason(excMstVo.getExcpReason());
resultLst.add(exc);
Results = resultLst;
success = true;
}
}
} else if (btnExcApp.equals(rootView.getRootView().findViewById(rootView.getId()))) {
for (x = excSrchListView.getChildCount() - 1; x >= 0; x--) {
cb = (CheckBox) excSrchListView.getChildAt(x).findViewById(R.id.chkBx);
if (cb.isChecked()) {
excpMstVo = setEmpData();
rtnExcMstVo = excpServObj.getExceptionPort().changeExceptionStatus(excpMstVo);
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
countApp++;
success = false;
}
}
/*if (countApp == 0) {
} else*/ if (countApp > 0) {
new SyncData(rootView).execute();
//flagg = false;
}
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
}
// get dump from device
CopyDbFromDevice cd = new CopyDbFromDevice();
cd.copyDbToSdcard(context);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success::::" + success);
successSyncFlag = success;
System.out.println("successSyncFlag::::::::" + successSyncFlag);
return resultLst;
}
private ExcpMstVo setEmpData() {
ExcpMstVo excpMstVo = new ExcpMstVo();
excpMstVo.setExcpId(Results.get(x).getExcId());
excpMstVo.setFromDt(Results.get(x).getFromDt());
excpMstVo.setStatus(Constants.Status.STAT_APPRV);
excpMstVo.setMngrComments("");
excpMstVo.setApprovedBy(empCode);
excpMstVo.setLoggedInUser(empCode);
return excpMstVo;
}
private ExceptionSearchCriteria setAppData(ExceptionSearchCriteria vo) {
vo.setApprover(empCode);
vo.setStatus(Constants.Status.PENDING_APPROVAL);
return vo;
}
protected void onPostExecute(ArrayList<Excp> searchResults) {
System.out.println("successSyncFlag1::::::::" + successSyncFlag);
if (successSyncFlag == true) {
System.out.println("entering ON POST IF");
cla = new CustomListViewAdapter(ExceptionAppActivity.this, resultLst);
excSrchListView.setAdapter(cla);
}
else {
System.out.println("ENTERING ONPOST ELSE PART ");
System.out.println("successSyncFlag2:;;;;;; " + successSyncFlag);
System.out.println("success2:::::::::::: " + success);
System.out.println("NEW METHOD STARTED:::::;");
if (countApp == 0) {
System.out.println("ENTERING COUNT APP 0 ");
String flag = "checkItemApp";
dialogBox(flag);
} else {
new SyncData(empCode).execute();
String flag = "excApp";
dialogBox(flag);
System.out.println("NEW METHOD STARTED1:::::::::");
}
}
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onClick(View v) {
int countRej = 0;
int id = v.getId();
Intent intent = null;
if (id == R.id.btnExcApp) {
new SyncData(v).execute();
} else if (id == R.id.btnExcRej) {
int itemPos = 0;
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cla.notifyDataSetChanged();
countRej++;
}
}
// Check if any Exception is selected for Rejection and proceed
// accordingly
if (countRej == 1) {
CustomListViewAdapter cla = (CustomListViewAdapter) excSrchListView.getAdapter();
Object o = cla.getItem(itemPos);
Excp selectedExcp = (Excp) o;
intent = new Intent(getBaseContext(), ExcAppDtlsActivity.class);
intent.putExtra("selectedExcp", selectedExcp);
intent.putExtra("readOnly", false);
startActivityForResult(intent, REQUEST_CODE);
} else if (countRej == 0) {
// show dialogue of Select at least 1
String flag = "checkItemRej";
dialogBox(flag);
} else if (countRej > 1) {
String flag = "checkOnlyOne";
dialogBox(flag);
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cb.setChecked(false);
cla.notifyDataSetChanged();
}
}
}
} else if (id == R.id.btnExcSrch) {
intent = new Intent(this, FurtherSearchActivity.class);
intent.putExtra("readOnly", false);
startActivity(intent);
} else if (id == R.id.btnExcExit) {
finish();
}
}
/**
* create alert dialog
*
* #param flag
*/
private void dialogBox(String flag) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
/*if (flag == "excApp") {
alertDialogBuilder.setTitle("Exception Approved successfully !");
} else*/ if (flag == "checkOnlyOne") {
alertDialogBuilder.setTitle("Please select only one item to reject !");
} else if (flag == "checkItemRej") {
alertDialogBuilder.setTitle("Select Exception to Reject !");
}
/*else if (flag == "checkItemApp") {
alertDialogBuilder.setTitle("Select Exception to Approve !");
} */
else if (flag == "excRej") {
alertDialogBuilder.setTitle("Exception Rejected successfully !");
}
/*else {
alertDialogBuilder.setTitle("Flag - " + flag);
}*/
Dialogbox dbx = new Dialogbox(context);
dbx.createDialogAlert(flag, alertDialogBuilder);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined above
/*
* if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //
* Extract name value from result extras flagg =
* data.getExtras().getString("flagg"); if ((flagg.equals("Approve")) ||
* (flagg.equals("Reject"))) { for (int x = 0; x <
* excSrchListView.getChildCount(); x++) { cb = (CheckBox)
* excSrchListView.getChildAt(x).findViewById( R.id.chkBx); if
* (cb.isChecked()) { // If Approval is successful remove from list
* Results.remove(x); cb.setChecked(false); cla.notifyDataSetChanged();
* if (flagg.equals("Approve")) { dialogBox("excApp"); } else {
* dialogBox("excRej"); } } }
*
* } }
*/
}
}
CUSTOM LIST ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TextView;
import com.eanda.smarttime_mobi.R;
import com.eanda.smarttime_mobi.model.Excp;
public class CustomListViewAdapter extends BaseAdapter {
private static ArrayList<Excp> searchArrayList;
HashMap<Integer, Boolean> checked;
private LayoutInflater mInflater;
Typeface custom_font = null;
public CustomListViewAdapter(Context context, ArrayList<Excp> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
checked = new HashMap<Integer, Boolean>(getCount());
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DejaVuSans.ttf");
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// created custom view
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);
holder.txtExcId = (TextView) convertView.findViewById(R.id.lblExcId);
holder.txtEmpNm = (TextView) convertView.findViewById(R.id.lblExcEmpNm);
holder.txtFrmDt = (TextView) convertView.findViewById(R.id.lblExcFrmDtVal);
holder.txtToDt = (TextView) convertView.findViewById(R.id.lblExcToDtVal);
holder.txtExcTyp = (TextView) convertView.findViewById(R.id.lblExcTyp);
holder.txtExcStat = (TextView) convertView.findViewById(R.id.lblExcStat);
holder.txtEmpCmt = (TextView) convertView.findViewById(R.id.lblExcEmpCmt);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
convertView.setTag(holder);
convertView.setTag(R.id.chkBx, holder.checkBox);
} else {
holder = (ViewHolder) convertView.getTag();
}
System.out.println("exception_name" + searchArrayList.get(position).getEmpNm());
holder.txtExcId.setText(Integer.toString(searchArrayList.get(position).getExcId()));
holder.txtEmpNm.setText(searchArrayList.get(position).getEmpNm());
holder.txtFrmDt.setText(searchArrayList.get(position).getFromDt());
holder.txtToDt.setText(searchArrayList.get(position).getToDt());
holder.txtExcTyp.setText(searchArrayList.get(position).getExcType());
holder.txtExcStat.setText(searchArrayList.get(position).getExcStatus());
holder.txtEmpCmt.setText(searchArrayList.get(position).getEmpComments());
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
holder.txtExcId.setTypeface(custom_font);
holder.txtEmpNm.setTypeface(custom_font);
holder.txtFrmDt.setTypeface(custom_font);
holder.txtToDt.setTypeface(custom_font);
holder.txtExcTyp.setTypeface(custom_font);
holder.txtExcStat.setTypeface(custom_font);
holder.txtEmpCmt.setTypeface(custom_font);
return convertView;
}
static class ViewHolder {
TableLayout myTable;
TextView txtExcId;
TextView txtEmpNm;
TextView txtFrmDt;
TextView txtToDt;
TextView txtExcTyp;
TextView txtExcStat;
TextView txtEmpCmt;
CheckBox checkBox;
}
}

CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
You already have check box reference stored in the holder, I wonder why you are initializing it again.
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
Checked state will be changed when the user clicks the checkbox, so no need to change the checked state again.
Try the following code
----
----
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
holder.checkBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
-----
----

Related

listview effecting multiple rows 4th,7th,10th

i have a custom listview and custom adapter. each row has multiple items inside it, when i click on like button it change the color of imageview but it also effect the 4th,7th and 10th row.
after searching on internet i learned that i have to use getTag and setTag but i dont know how to use it.
please help me in understanding the concept of getTag and setTag and solving this error.
here is my code:-
package rj.osmthemes;
import java.util.ArrayList;
import android.content.Context;
import android.os.Build;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.bumptech.glide.Glide;
import static android.R.attr.data;
import static rj.osmthemes.R.id.downlink;
import static rj.osmthemes.R.id.likebtn;
import static rj.osmthemes.R.id.likecount;
public class ListAdapter extends ArrayAdapter<DataModel> {
customButtonListener customListner;
private ArrayList<DataModel> dataSet;
public String temp1;
public interface customButtonListener {
public void onButtonClickListner(int position,String value);
public void onImageClickListner(int position,String value);
public void onlikeImageClickListner(int position,String value);
public void ondislikeImageClickListner(int position,String value);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
private Context context;
//private ArrayList<String> data = new ArrayList<String>();
public ListAdapter(ArrayList<DataModel> data, Context context) {
super(context, R.layout.list_layout, data);
this.dataSet = data;
this.context = context;
}
private int lastPosition = -1;
// public ListAdapter(Context context, ArrayList<String> dataItem) {
// super(context, R.layout.list_layout, dataItem);
// this.data = dataItem;
// this.context = context;
// }
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
final DataModel dataModel = getItem(position);
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.list_layout, null);
viewHolder = new ViewHolder();
viewHolder.themename = (TextView) convertView.findViewById(R.id.themename);
viewHolder.madeby = (TextView) convertView.findViewById(R.id.madeby);
viewHolder.downcount = (TextView) convertView.findViewById(R.id.downcount);
viewHolder.likecount = (TextView) convertView.findViewById(likecount);
viewHolder.dislikecount = (TextView) convertView.findViewById(R.id.dislikecount);
viewHolder.ss1 = (ImageView) convertView.findViewById(R.id.img1);
viewHolder.ss2 = (ImageView) convertView.findViewById(R.id.img2);
viewHolder.ss3 = (ImageView) convertView.findViewById(R.id.img3);
viewHolder.likebtn = (ImageView) convertView.findViewById(likebtn);
viewHolder.dislikebtn = (ImageView) convertView.findViewById(R.id.dislikebtn);
viewHolder.btndownload = (Button) convertView.findViewById(downlink);
convertView.setTag(viewHolder);
final String temp = getItem(position).toString();
viewHolder.likebtn.setTag(temp);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
lastPosition = position;
//final String temp = getItem(position).toString();
// viewHolder.tempid = Integer.parseInt(dataModel.getId());
final String ss1link,ss2link,ss3link,downlink;
viewHolder.themename.setText(dataModel.getTheme_name());
viewHolder.madeby.setText(dataModel.getMade_by());
viewHolder.downcount.setText(dataModel.getDown_count());
viewHolder.likecount.setText(dataModel.getLike_count());
viewHolder.dislikecount.setText(dataModel.getDislike_count());
ss1link = dataModel.getSs1();
ss2link = dataModel.getSs2();
ss3link = dataModel.getSs3();
downlink = dataModel.getDown_link();
// viewHolder.text.setText(temp);
viewHolder.btndownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
int downcounttmp = Integer.parseInt(dataModel.getDown_count());
downcounttmp++;
viewHolder.downcount.setText(""+downcounttmp);
String name = downlink + "#" + dataModel.getTheme_name() + "#" + dataModel.getId() + "#" + downcounttmp;
customListner.onButtonClickListner(position,name);
}
}
});
viewHolder.ss1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss1link);
}
}
});
viewHolder.ss2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss2link);
}
}
});
viewHolder.ss3.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
customListner.onImageClickListner(position,ss3link);
}
}
});
viewHolder.likebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
// Toast.makeText(context, dataModel.getId() + " { " ,Toast.LENGTH_LONG).show();
if(viewHolder.check == 0){
int likecount = Integer.parseInt(dataModel.getLike_count());
likecount++;
viewHolder.likecount.setText(""+likecount);
String name = likecount + "#" + dataModel.getId();
// Toast.makeText(context,position + " " + temp,Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.likebtn.setImageResource(R.drawable.ic_thumb_up_red_24dp);
//viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.likebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_up_red_24dp));
viewHolder.check = 1;
}
customListner.onlikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
viewHolder.dislikebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (customListner != null) {
if(viewHolder.check == 0) {
int dislikecount = Integer.parseInt(dataModel.getDislike_count());
dislikecount++;
viewHolder.dislikecount.setText(""+dislikecount);
String name = dislikecount + "#" + dataModel.getId();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp, getContext().getTheme()));
viewHolder.check = 1;
} else {
viewHolder.dislikebtn.setImageDrawable(context.getResources().getDrawable(R.drawable.ic_thumb_down_red_24dp));
viewHolder.check = 1;
}
customListner.ondislikeImageClickListner(position,name);
}
else {
Toast.makeText(context,"You cant use this action",Toast.LENGTH_LONG).show();
}
}
}
});
Glide
.with(context)
.load(ss1link)
.into(viewHolder.ss1);
Glide
.with(context)
.load(ss2link)
.into(viewHolder.ss2);
Glide
.with(context)
.load(ss3link)
.into(viewHolder.ss3);
return convertView;
}
public class ViewHolder {
TextView themename,madeby,downcount,likecount,dislikecount;
Button btndownload;
ImageView ss1,ss2,ss3,likebtn,dislikebtn;
int check = 0, tempid = 0;
}
}
This is because of object reuse in your list view.
You can manage separate ArrayList or HashMap to maintain your likes.
And based on that you should update in your getView like this,
if([already selected]) {
viewHolder.likebtn.setBackground([your selected drawable]);
} else {
viewHolder.likebtn.setBackground([your non selected drawable]);
}

fix listview data disappear when activity restarted in android

I wrote an android app and it simply displays a list view.
and everything works fine except one.
I installed my app on my tablet and when i run the app, that problem occurs.
==>. that is . . .
When I press power button to turn off screen and press power button again to turn screen on, the whole list view data disappears.
I think this is some problem with activity lifecycle, but I can't deal with this..
Please help me..
Here is my code...
package com.jo.fivemancard;
import android.content.Context;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
public ScoreListAdapter scoreListAdapter;
class RoundScore {
public int score1 = 0;
public int score2 = 0;
public int score3 = 0;
public int score4 = 0;
public int score5 = 0;
public RoundScore(){
score1 = score2 = score3 = score4 = score5 = 0;
}
}
class ScoreListAdapter extends BaseAdapter{
public Context context;
class ViewHolder{
TextView textViewScore1;
TextView textViewScore2;
TextView textViewScore3;
TextView textViewScore4;
TextView textViewScore5;
}
public ArrayList<RoundScore> scoreList;
public ScoreListAdapter(Context cont){
context = cont;
scoreList = new ArrayList<RoundScore>();
}
public void appendData(RoundScore rc){
scoreList.add(rc);
notifyDataSetChanged();
}
#Override
public int getCount() {
return scoreList.size();
}
#Override
public Object getItem(int position) {
return scoreList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.listviewitem_score, parent, false);
vh = new ViewHolder();
vh.textViewScore1 = (TextView)rowView.findViewById(R.id.textViewScore1);
vh.textViewScore2 = (TextView)rowView.findViewById(R.id.textViewScore2);
vh.textViewScore3 = (TextView)rowView.findViewById(R.id.textViewScore3);
vh.textViewScore4 = (TextView)rowView.findViewById(R.id.textViewScore4);
vh.textViewScore5 = (TextView)rowView.findViewById(R.id.textViewScore5);
convertView = rowView;
}else {
vh = (ViewHolder) convertView.getTag();
}
RoundScore rc = scoreList.get(position);
vh.textViewScore1.setText("" + rc.score1);
vh.textViewScore2.setText("" + rc.score2);
vh.textViewScore3.setText("" + rc.score3);
vh.textViewScore4.setText("" + rc.score4);
vh.textViewScore5.setText("" + rc.score5);
convertView.setTag(vh);
return convertView;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.buttonNextRound).setOnClickListener(this);
findViewById(R.id.floatActionButtonCalculate).setOnClickListener(this);
scoreListAdapter = new ScoreListAdapter(this);
((ListView)findViewById(R.id.listViewScore)).setAdapter(scoreListAdapter);
((TextView)findViewById(R.id.textViewPlayer1)).setText(GlobalConstant.playername1);
((TextView)findViewById(R.id.textViewPlayer2)).setText(GlobalConstant.playername2);
((TextView)findViewById(R.id.textViewPlayer3)).setText(GlobalConstant.playername3);
((TextView)findViewById(R.id.textViewPlayer4)).setText(GlobalConstant.playername4);
((TextView)findViewById(R.id.textViewPlayer5)).setText(GlobalConstant.playername5);
}
public int getScore(String score){
if(score.trim().equals("")){
return 0;
}
if(score.length() == 0){
return 0;
}
boolean isNumber;
if(score.charAt(0) == '-'){
isNumber = android.text.TextUtils.isDigitsOnly(score.substring(1));
}else{
isNumber = android.text.TextUtils.isDigitsOnly(score);
}
if(isNumber) {
return Integer.parseInt(score.trim());
}
return 0;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.buttonNextRound){
String score1 = ((EditText)findViewById(R.id.editTextNewScorePlayer1)).getText().toString();
String score2 = ((EditText)findViewById(R.id.editTextNewScorePlayer2)).getText().toString();
String score3 = ((EditText)findViewById(R.id.editTextNewScorePlayer3)).getText().toString();
String score4 = ((EditText)findViewById(R.id.editTextNewScorePlayer4)).getText().toString();
String score5 = ((EditText)findViewById(R.id.editTextNewScorePlayer5)).getText().toString();
if(score1.trim().equals("")){
score1 = "0";
}
RoundScore rc = new RoundScore();
rc.score1 = getScore(score1);
rc.score2 = getScore(score2);
rc.score3 = getScore(score3);
rc.score4 = getScore(score4);
rc.score5 = getScore(score5);
if(rc.score1 == 0 && rc.score2 == 0 && rc.score3 == 0 && rc.score4 == 0 && rc.score5 == 0){
Toast.makeText(this, "Bad Input...", Toast.LENGTH_SHORT).show();
return;
}
scoreListAdapter.appendData(rc);
((ListView)findViewById(R.id.listViewScore)).setSelection(scoreListAdapter.getCount() - 1);
Toast.makeText(this, "Next Round...", Toast.LENGTH_SHORT).show();
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("");
}
if(v.getId() == R.id.floatActionButtonCalculate){
RoundScore rs = new RoundScore();
int i;
for(i=0;i<scoreListAdapter.scoreList.size();i++){
rs.score1 += scoreListAdapter.scoreList.get(i).score1;
rs.score2 += scoreListAdapter.scoreList.get(i).score2;
rs.score3 += scoreListAdapter.scoreList.get(i).score3;
rs.score4 += scoreListAdapter.scoreList.get(i).score4;
rs.score5 += scoreListAdapter.scoreList.get(i).score5;
}
if(findViewById(R.id.buttonNextRound).isEnabled()){
String str1 = ((EditText)findViewById(R.id.editTextNewScorePlayer1)).getText().toString().trim();
String str2 = ((EditText)findViewById(R.id.editTextNewScorePlayer2)).getText().toString().trim();
String str3 = ((EditText)findViewById(R.id.editTextNewScorePlayer3)).getText().toString().trim();
String str4 = ((EditText)findViewById(R.id.editTextNewScorePlayer4)).getText().toString().trim();
String str5 = ((EditText)findViewById(R.id.editTextNewScorePlayer5)).getText().toString().trim();
if(!str1.equals("") || !str2.equals("") || !str3.equals("") || !str4.equals("") || !str5.equals("")){
Toast.makeText(this,"It seems you wanna add score info.",Toast.LENGTH_SHORT);
return;
}
findViewById(R.id.buttonNextRound).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("" + rs.score1);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("" + rs.score2);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("" + rs.score3);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("" + rs.score4);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("" + rs.score5);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setEnabled(false);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setEnabled(false);
}else{
findViewById(R.id.buttonNextRound).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setText("");
((EditText)findViewById(R.id.editTextNewScorePlayer1)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer2)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer3)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer4)).setEnabled(true);
((EditText)findViewById(R.id.editTextNewScorePlayer5)).setEnabled(true);
}
}
}
private Boolean exit = false;
#Override
public void onBackPressed() {
if (exit) {
finish(); // finish activity
} else {
Toast.makeText(this, "Press Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 1 * 1000);
}
}
}

Index does not update unless the item is being pressed two times in Adapter

For some reason, the variable mItemIndex does not update its value until I press the same item for two times.
Yet when I logged both instances of mItemIndex, they logged different values. What is wrong here? I've been debugging this for the whole day, yet I can't find the appropriate solution for it.
package com.app.burgerking.menu.category.product;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.ParseException;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.app.burgerking.R;
import com.app.burgerking.layout.FontHandler;
import com.app.burgerking.models.ModifierGroup;
import com.app.burgerking.models.ModifierItem;
import android.content.SharedPreferences;
/*** Reference to Pass TextView to Adapter:
http://stackoverflow.com/questions/9785523/on-button-click-how-to-increment-counter-and-show-in-textview
***/
public class ModifierGridViewAdapter extends BaseAdapter {
private Context mContext;
private List<ModifierItem> mItems;
private Typeface berthold;
private String mModGroupId;
private TextView tv_totalPrice;
private TextView tv_totalPrice2;
private int mItemIndex = -1;
private TextView tv_availableOptionsCount;
private ModifierGroup mModGroup;
private NumberFormat nf;
// Gregg's Code
private static final String ACTIVITY = "languageStorage";
private static String savedLanguage = "";
private static SharedPreferences spLanguage;
// End
public ModifierGridViewAdapter(Context context) {
mContext = context;
mItems = new ArrayList<ModifierItem>();
berthold = FontHandler.getTypefaceBertholdCondensed();
nf = NumberFormat.getInstance(mContext.getResources().getConfiguration().locale);
// Gregg's Code
spLanguage = mContext.getSharedPreferences(ACTIVITY, Context.MODE_PRIVATE);
// End
}
#Override
public int getItemViewType(int position) {
int type;
if (mModGroup.getMax() <= 1) {
// Load Second Layout (Layout with only touch events)
type = 1;
} else {
// Load First Layout (Layout with Increment / Decrement buttons)
type = 0;
}
return type;
}
public void setTotalPriceTextView(TextView textViewFromActivity) {
this.tv_totalPrice = textViewFromActivity;
}
public void setTotalPriceTextView2(TextView textViewFromActivity) {
this.tv_totalPrice2 = textViewFromActivity;
}
public void setAvailableOptionsCount(TextView textViewFromActivity) {
this.tv_availableOptionsCount = textViewFromActivity;
}
public void setModifierGroup(ModifierGroup modGroupFromActivity) {
this.mModGroup = modGroupFromActivity;
}
public void setItems(List<ModifierItem> items, String id) {
mItems = items;
mModGroupId = id;
}
public int countSelected() {
int count = 0;
for (int i = 0; i < mItems.size(); i++) {
if (mItems.get(i).isSelected())
count++;
}
return count;
}
private List<ModifierItem> getSelectedModifiers() {
List<ModifierItem> list = new ArrayList<ModifierItem>();
for (int i = 0; i < mItems.size(); i++) {
ModifierItem item = mItems.get(i);
if (item.isSelected()) {
item.setGroupId(mModGroupId);
list.add(item);
}
}
return list;
}
public ModifierGroup getModifierGroup() {
String id = mModGroupId;
int min = -999;
int max = -999;
int free = -999;
String name = null;
List<ModifierItem> items = getSelectedModifiers();
return new ModifierGroup(id, min, max, free, name, items);
}
public double getTotalPrice() {
double ret = 0.0;
for (ModifierItem item : mItems) {
ret += (item.getPrice() * item.getQuantity());
}
return ret;
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public ModifierItem getItem(int pos) {
return mItems.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
public void highlightSelected(ViewHolder holder, final int position) {
getItem(position).setQuantity(getItem(position).getQuantity() + 1);
double convertedTotalPrice = 0.0;
double convertedTotalPrice2 = 0.0;
try {
convertedTotalPrice = nf.parse(tv_totalPrice.getText().toString()
.substring(0, tv_totalPrice.getText().toString().indexOf(" "))).doubleValue();
convertedTotalPrice2 = nf.parse(tv_totalPrice2.getText().toString()
.substring(0, tv_totalPrice2.getText().toString().indexOf(" "))).doubleValue();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
convertedTotalPrice += getItem(position).getPrice();
convertedTotalPrice2 += getItem(position).getPrice();
tv_totalPrice.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice));
tv_totalPrice2.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice2));
holder.container.setBackgroundResource(R.drawable.modifier_button_toggled);
holder.name.setTextColor(Color.parseColor("#ffffff"));
holder.img.setImageResource(R.drawable.checkout_check);
holder.price.setTextColor(Color.parseColor("#ffffff"));
}
public void unhighlightSelected(ViewHolder holder, final int position) {
decrementAvailableOptions(tv_availableOptionsCount);
getItem(position).setQuantity(getItem(position).getQuantity() - 1);
double convertedTotalPrice = 0.0;
double convertedTotalPrice2 = 0.0;
try {
convertedTotalPrice = nf.parse(tv_totalPrice.getText().toString()
.substring(0, tv_totalPrice.getText().toString().indexOf(" "))).doubleValue();
convertedTotalPrice2 = nf.parse(tv_totalPrice2.getText().toString()
.substring(0, tv_totalPrice2.getText().toString().indexOf(" "))).doubleValue();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
convertedTotalPrice -= getItem(position).getPrice();
convertedTotalPrice2 -= getItem(position).getPrice();
tv_totalPrice.setText(String.format("%.2f " + mContext.getString(R.string.sar_string), convertedTotalPrice));
tv_totalPrice2.setText(String.format("%.2f " + mContext.getString(R.string.sar_string), convertedTotalPrice2));
holder.container.setBackgroundResource(R.drawable.modifier_button_untoggled);
holder.name.setTextColor(Color.parseColor("#777777"));
holder.img.setImageResource(R.drawable.checkout_add);
holder.price.setTextColor(Color.parseColor("#777777"));
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
final ViewHolder holder;
savedLanguage = new String(spLanguage.getString("language", ""));
int type = getItemViewType(position);
if (convertView == null) {
switch (type) {
case 1: // Modifier Group has only less than or equal to one Available Option
convertView = inflater.inflate(R.layout.modifier_item, parent, false);
holder = new ViewHolder();
holder.container = (RelativeLayout) convertView.findViewById(R.id.modifier_item_container);
holder.img = (ImageView) convertView.findViewById(R.id.modifier_item_image);
holder.name = (TextView) convertView.findViewById(R.id.modifier_item_name);
holder.price = (TextView) convertView.findViewById(R.id.modifier_item_price);
convertView.setTag(holder);
convertView.setTag(R.id.modifier_item_container, holder.container);
convertView.setTag(R.id.modifier_item_image, holder.img);
convertView.setTag(R.id.modifier_item_name, holder.name);
convertView.setTag(R.id.modifier_item_price, holder.price);
if (getItem(position).getQuantity() > 0) {
mItemIndex = position;
highlightSelected(holder, position);
}
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
Log.d("INDEX", Integer.toString(mItemIndex));
// Case 1: The user deselects the item he/she selected.
if (getItem(position).getQuantity() > 0) {
mItemIndex = -1;
Log.d("INDEX 2", Integer.toString(mItemIndex));
unhighlightSelected(holder, position);
} else {
}
}
});
break;
case 0: // Modifier Group has more than one Available Option
convertView = inflater.inflate(R.layout.modifier_item_2, parent, false);
holder = new ViewHolder();
holder.container = (RelativeLayout) convertView.findViewById(R.id.modifier_item_container_2);
holder.incrementImg = (ImageView) convertView.findViewById(R.id.modifier_item_increment_quantity);
holder.quantity = (TextView) convertView.findViewById(R.id.modifier_item_quantity);
holder.decrementImg = (ImageView) convertView.findViewById(R.id.modifier_item_decrement_quantity);
holder.name = (TextView) convertView.findViewById(R.id.modifier_item_name_2);
holder.price = (TextView) convertView.findViewById(R.id.modifier_item_price_2);
convertView.setTag(holder);
convertView.setTag(R.id.modifier_item_container_2, holder.container);
convertView.setTag(R.id.modifier_item_increment_quantity, holder.incrementImg);
convertView.setTag(R.id.modifier_item_quantity, holder.quantity);
convertView.setTag(R.id.modifier_item_decrement_quantity, holder.decrementImg);
convertView.setTag(R.id.modifier_item_name_2, holder.name);
convertView.setTag(R.id.modifier_item_price_2, holder.price);
holder.quantity.setText(Integer.toString(getItem(position).getQuantity()));
holder.quantity.setTypeface(berthold);
holder.incrementImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isAvailableCountBelowZero(tv_availableOptionsCount)) {
displayErrorMessage();
return;
}
int acquiredQuantity = Integer.parseInt(holder.quantity.getText().toString());
acquiredQuantity += 1;
getItem(position).setQuantity(acquiredQuantity);
double convertedTotalPrice = 0.0;
double convertedTotalPrice2 = 0.0;
try {
convertedTotalPrice = nf.parse(tv_totalPrice.getText().toString()
.substring(0, tv_totalPrice.getText().toString().indexOf(" "))).doubleValue();
convertedTotalPrice2 = nf.parse(tv_totalPrice2.getText().toString()
.substring(0, tv_totalPrice2.getText().toString().indexOf(" "))).doubleValue();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
convertedTotalPrice += getItem(position).getPrice();
convertedTotalPrice2 += getItem(position).getPrice();
tv_totalPrice.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice));
tv_totalPrice2.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice2));
holder.quantity.setText(Integer.toString(acquiredQuantity));
}
});
holder.decrementImg.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int acquiredQuantity = Integer.parseInt(holder.quantity.getText().toString());
if (acquiredQuantity - 1 < 0) {acquiredQuantity = 0;}
else {
decrementAvailableOptions(tv_availableOptionsCount);
acquiredQuantity -= 1;
getItem(position).setQuantity(acquiredQuantity);
double convertedTotalPrice = 0.0;
double convertedTotalPrice2 = 0.0;
try {
convertedTotalPrice = nf.parse(tv_totalPrice.getText().toString()
.substring(0, tv_totalPrice.getText().toString().indexOf(" "))).doubleValue();
convertedTotalPrice2 = nf.parse(tv_totalPrice2.getText().toString()
.substring(0, tv_totalPrice2.getText().toString().indexOf(" "))).doubleValue();
} catch (java.text.ParseException e) {
e.printStackTrace();
}
convertedTotalPrice -= getItem(position).getPrice();
convertedTotalPrice2 -= getItem(position).getPrice();
tv_totalPrice.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice));
tv_totalPrice2.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
convertedTotalPrice2));
}
holder.quantity.setText(Integer.toString(acquiredQuantity));
}
});
break;
default:
convertView = inflater.inflate(R.layout.modifier_item, parent, false);
holder = new ViewHolder();
holder.container = (RelativeLayout) convertView.findViewById(R.id.modifier_item_container);
holder.img = (ImageView) convertView.findViewById(R.id.modifier_item_image);
holder.name = (TextView) convertView.findViewById(R.id.modifier_item_name);
holder.price = (TextView) convertView.findViewById(R.id.modifier_item_price);
convertView.setTag(holder);
convertView.setTag(R.id.modifier_item_container, holder.container);
convertView.setTag(R.id.modifier_item_image, holder.img);
convertView.setTag(R.id.modifier_item_name, holder.name);
convertView.setTag(R.id.modifier_item_price, holder.price);
break;
}
}
else {
holder = (ViewHolder) convertView.getTag();
}
if (savedLanguage.equals("ar")) {
holder.name.setText(getItem(position).getAltName().toUpperCase());
} else {
holder.name.setText(getItem(position).getName().toUpperCase());
}
holder.price.setText(String.format("%.2f " + mContext.getString(R.string.sar_string),
getItem(position).getPrice()));
holder.name.setTypeface(berthold);
holder.price.setTypeface(berthold);
return convertView;
}
public void decrementAvailableOptions(TextView tv_count) {
int availableCount = Integer.parseInt(tv_count.getText().toString());
if (availableCount + 1 > mModGroup.getMax()) {
availableCount = mModGroup.getMax();
} else {
availableCount += 1;
if ((mModGroup.getSelectedCount() - 1) < 0) {
mModGroup.setSelectedCount(0);
} else {
mModGroup.setSelectedCount(mModGroup.getSelectedCount() - 1);
}
}
tv_count.setText(Integer.toString(availableCount));
}
public boolean isAvailableCountBelowZero(TextView tv_count) {
boolean isBelowZero = false;
int availableCount = Integer.parseInt(tv_count.getText().toString());
if (availableCount - 1 < 0) {
isBelowZero = true;
}
else {
mModGroup.setSelectedCount(mModGroup.getSelectedCount() + 1);
tv_count.setText(Integer.toString(availableCount - 1));
}
return isBelowZero;
}
public void displayErrorMessage() {
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Add-On Limit");
builder.setMessage("You have exceeded the maximum number of items you can add.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
private class ViewHolder {
RelativeLayout container;
ImageView img;
ImageView incrementImg;
TextView quantity;
ImageView decrementImg;
TextView name;
TextView price;
}
}
You are updating mItemIndex inside few conditions. Can you add below line in getView() method of adapter.
mItemIndex = position;

Custom BaseAdapter doesn't call getView after resume app

i'm having some problems with a custom BaseAdapter which is showed in a PullToRefreshListView (whitch is an extension from ListView that you can update by pulling the list).
My problem is that when I minimize and later I resume my app, the ListView is not showing nothing... I had a breakpoint at my last line of code and my method getCount from my adapter return always more than zero, but getView still not being called...
Adapter:
package extrasoftware.triptreat.Adapters;
/**
* Creado pormsolla on 7/01/14.
*/
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.GregorianCalendar;
import extrasoftware.triptreat.Clases.ImageLoader;
import extrasoftware.triptreat.Clases.ImageViewEscalable;
import extrasoftware.triptreat.Clases.Ofertas.Oferta;
import extrasoftware.triptreat.Clases.Ofertas.OfertasLlenar_R;
import extrasoftware.triptreat.Comun.Constantes;
import extrasoftware.triptreat.Comun.Datos;
import extrasoftware.triptreat.Comun.General;
import extrasoftware.triptreat.OfertasActivity;
import extrasoftware.triptreat.OfertasDetalleActivity;
import extrasoftware.triptreat.R;
public class OfertasAdapter extends BaseAdapter {
private Activity activity;
private OfertasLlenar_R oRespuesta;
private OfertasLlenar_R oRespuestaTotal;
private static LayoutInflater inflater = null;
private ImageLoader imageLoader;
public static boolean abrirVentana = true;
//public static boolean okComentario = true;
public OfertasAdapter(Activity a, OfertasLlenar_R d, OfertasLlenar_R d_total) {
activity = a;
oRespuesta = d;
oRespuestaTotal = d_total;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Display display = activity.getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
imageLoader = new ImageLoader(activity.getApplicationContext(), R.drawable.sinimagen, Constantes.ImageLoaderTipo.Lista);
}
public int getCount() {
return oRespuesta.datos.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
View vista = convertView;
try{
vista = inflater.inflate(R.layout.ofertas_row, parent, false);
final Oferta oferta = oRespuesta.datos.get(position);
final TextView txtTitulo = (TextView)vista.findViewById(R.id.txtTitulo);
final TextView txtNegocio = (TextView)vista.findViewById(R.id.txtNegocio);
final ImageViewEscalable imgOferta = (ImageViewEscalable)vista.findViewById(R.id.imgOferta);
final ImageView imgEstado = (ImageView)vista.findViewById(R.id.imgEstado);
imgOferta.setImageBitmap(null);
String urlImagen = General.ObtenerRutaImagen(Constantes.Ventanas_Origen.Ofertas, oRespuesta.oferta_raiz + "/" + oferta.oferta_imagen, activity);
imageLoader.DisplayImage(urlImagen, imgOferta);
txtNegocio.setText(oferta.negocio_nombre);
txtTitulo.setText(oferta.titulo);
GregorianCalendar calendar = new GregorianCalendar();
final boolean caducada = calendar.getTime().after(oferta.valido_hasta_F);
if(caducada){
imgEstado.setImageResource(R.drawable.caducada);
}
else if(oferta.estado == Constantes.Ofertas_Estados.Aceptada){
imgEstado.setImageResource(R.drawable.aceptada);
}
else if(oferta.estado == Constantes.Ofertas_Estados.Usada){
imgEstado.setImageResource(R.drawable.usada);
}
else{
imgEstado.setVisibility(View.GONE);
}
vista.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final CharSequence[]
options = {
activity.getResources().getString(R.string.borrar),
activity.getResources().getString(R.string.excluir),
activity.getResources().getString(R.string.cancelar)
};
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(activity.getResources().getString(R.string.borrar))) {
OfertasActivity.ConfirmarBorrar(v, oferta.oferta_id);
}
else if (options[item].equals(activity.getResources().getString(R.string.excluir))) {
OfertasActivity.ConfirmarExcluir(v, oferta.negocio_id, oferta.negocio_nombre);
}
else if (options[item].equals(activity.getResources().getString(R.string.cancelar))) {
dialog.dismiss();
}
}
});
builder.show();
return true;
}
});
// Click event for single list row
vista.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try{
if(abrirVentana && !caducada){
abrirVentana = false;
General.MostrarCargando(activity);
Datos.setCodigosFiltrados(activity.getApplicationContext(), oRespuesta);
Intent detalleIntent = new Intent(activity.getApplicationContext(), OfertasDetalleActivity.class);
detalleIntent.putExtra(Constantes.Parametros_Extra.Indice, String.valueOf(General.ObtenerIndiceOfertaEnLista(oRespuesta.datos, oferta.oferta_id)));
activity.startActivity(detalleIntent);
}
}
catch (Exception e){
e.printStackTrace();
}
}
});
}
catch(Exception e){
e.printStackTrace();
}
return vista;
}
public void setDatos(OfertasLlenar_R oRespuestaFiltro){
oRespuesta = oRespuestaFiltro;
this.notifyDataSetChanged();
}
}
Thanks!
I had just find an error in the activity that uses this adapter... But i don't understand this, and i'm not sure that it was the betters solution...
This method was the problem:
private static void CargarListasOfertas(OfertasLlenar_R oRespuesta){
try{
OfertasLlenar_R oRespuestFiltradas = (OfertasLlenar_R) oRespuesta.clone();
if(m_listaNavegaciones != null && m_listaNavegaciones.size() != 0){
final short paisID = m_listaNavegaciones.get(m_indice_actual).pais_id;
final short ciudadID = m_listaNavegaciones.get(m_indice_actual).ciudad_id;
Predicate<Oferta> ofertasPredicate = new Predicate<Oferta>() {
public boolean apply(Oferta oferta) {
return oferta.pais_id == paisID && oferta.ciudad_id == ciudadID;
}
};
Collection<Oferta> ofertas = General.Filtrar(oRespuestFiltradas.datos, ofertasPredicate);
oRespuestFiltradas.datos = new ArrayList<Oferta>(ofertas);
if(adapterOfertas == null){
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
}
else{
adapterOfertas.setDatos(oRespuestFiltradas);
}
}
else{
oRespuestFiltradas.datos = new ArrayList<Oferta>();
if(adapterOfertas == null){
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
}
else{
adapterOfertas.setDatos(oRespuestFiltradas);
}
oRespuestFiltradas.datos = new ArrayList<Oferta>();
}
final long ONE_MINUTE_IN_MILLIS = 60000;//millisecs
long t = Calendar.getInstance().getTime().getTime();
Date afterAddingTenMins = new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
if(Datos.ventana_origen != Constantes.Ventanas_Origen.OfertasDetalle
|| (OfertasDetalleActivity.getFechaCarga() != null
&& !OfertasDetalleActivity.getFechaCarga().before(afterAddingTenMins))){
m_posicionOfertas = lstOfertas.getRefreshableView().getFirstVisiblePosition();
}
if(m_posicionOfertas != -1){
lstOfertas.getRefreshableView().setSelection(m_posicionOfertas);
}
General.OcultarCargando();
}
catch (Exception e){
e.printStackTrace();
General.OcultarCargando();
}
}
The code that now is working fine is:
private static void CargarListasOfertas(OfertasLlenar_R oRespuesta){
try{
OfertasLlenar_R oRespuestFiltradas = (OfertasLlenar_R) oRespuesta.clone();
if(m_listaNavegaciones != null && m_listaNavegaciones.size() != 0){
final short paisID = m_listaNavegaciones.get(m_indice_actual).pais_id;
final short ciudadID = m_listaNavegaciones.get(m_indice_actual).ciudad_id;
Predicate<Oferta> ofertasPredicate = new Predicate<Oferta>() {
public boolean apply(Oferta oferta) {
return oferta.pais_id == paisID && oferta.ciudad_id == ciudadID;
}
};
Collection<Oferta> ofertas = General.Filtrar(oRespuestFiltradas.datos, ofertasPredicate);
oRespuestFiltradas.datos = new ArrayList<Oferta>(ofertas);
}
else{
oRespuestFiltradas.datos = new ArrayList<Oferta>();
}
adapterOfertas = new OfertasAdapter(activity, oRespuestFiltradas, oRespuesta);
lstOfertas.setAdapter(adapterOfertas);
final long ONE_MINUTE_IN_MILLIS = 60000;//millisecs
long t = Calendar.getInstance().getTime().getTime();
Date afterAddingTenMins = new Date(t + (10 * ONE_MINUTE_IN_MILLIS));
if(Datos.ventana_origen != Constantes.Ventanas_Origen.OfertasDetalle
|| (OfertasDetalleActivity.getFechaCarga() != null
&& !OfertasDetalleActivity.getFechaCarga().before(afterAddingTenMins))){
m_posicionOfertas = lstOfertas.getRefreshableView().getFirstVisiblePosition();
}
if(m_posicionOfertas != -1){
lstOfertas.getRefreshableView().setSelection(m_posicionOfertas);
}
General.OcultarCargando();
}
catch (Exception e){
e.printStackTrace();
General.OcultarCargando();
}
}

How to Handle the checkbox ischecked and unchecked event in android

i am new in android.i make a simple maths apps.
i use the check box for select right option but problem is here the answer option is not only one but also two,three means multi select so i use the check box
chkOption.setOnCheckedChangeListener(this);
event and try to handle this.and store the select value in one Arraylist.but when i select option the value is add in arrayList but when i do uncheck(Diselect) then also the event is occur and the value add in arraylist.
my code is below
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
CheckBox chk=(CheckBox) buttonView;
if(chk.isChecked())
{
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
}
forMetchCheckbow is my String ArrayList .So i can what to do?
How to Handle this problem.
if any user deselect the option then the checkbox select value is remove from ArrayList.it`s possible?
It seems you are having more than one checkbox and you are setting global listener for every checkbox. So, in that case you need to identify the event for specific checkbox also.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
int id = buttonView.getId();
if(id == R.id.chk)
{
if(chk.isChecked()){
forMetchCheckBox.add(String.valueOf(chk.getText()));
}
else{
forMetchCheckBox.remove(String.valueOf(chk.getText()));
}
}
else if(id == R.id.chk1){
....
}
}
and so on, that will make your listener work perfect.
What's wrong is your if condition. It should be:
if( isChecked )
and not
if( chk.isChecked() )
chk.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
chetimeslot = (String)chk.getTag();
checkbox_timeslot.add(chetimeslot);
}
else{
chetimeslot = (String)chk.getTag();
checkbox_timeslot.remove(chetimeslot);
}
});
To Select Maximum 5 Checkbox at one Time or Count selected and unselected checkbox in Custom listview with CheckBox
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ListViewCheckboxesActivity extends ListActivity {
AlertDialog alertdialog = null;
int i1, i2, i3 = 0;
Country rowcheck;
MyCustomAdapter dataAdapter = null;
ListView listView = null;
int k = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fmain);
// Generate list View from ArrayList
displayListView();
checkButtonClick();
}
private void displayListView() {
// Array list of countries Equipments
ArrayList<Country> rowcheckList = new ArrayList<Country>();
Country rowcheck = new Country("", "Hex Bolts", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Hex Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Round Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Slotted Head Hex Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Socket Cap Screw", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Sockets", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Square Head Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Carriage Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Plow Bolt", false);
rowcheckList.add(rowcheck);
rowcheck = new Country("", "Struts Clamp", false);
rowcheckList.add(rowcheck);
listView = getListView();
dataAdapter = new MyCustomAdapter(this, R.layout.rowcheck_info,
rowcheckList);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Country rowcheck = (Country) parent.getItemAtPosition(position);
}
});
}
private class MyCustomAdapter extends ArrayAdapter<Country> {
private ArrayList<Country> rowcheckList;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<Country> rowcheckList) {
super(context, textViewResourceId, rowcheckList);
this.rowcheckList = new ArrayList<Country>();
this.rowcheckList.addAll(rowcheckList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.rowcheck_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
holder.name.setOnClickListener( new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v ;
Country rowcheck = (Country) cb.getTag();
//To check maximum 5 Selection
if(k>5)
{
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else
{
System.out.println("if block in-----");
cb.setChecked(false);
Toast.makeText(getApplicationContext(), "Maximum Selection", Toast.LENGTH_LONG).show();
}
}
else
{
System.out.println("else block in-----");
if(!cb.isChecked())
{
rowcheck.selected=true;
System.out.println(k--);
}
else if(cb.isChecked())
{
rowcheck.selected=false;
System.out.println(k++);
}
}
Toast.makeText(getApplicationContext(),
"Clicked on Checkbox: " + cb.getText() +
" is " + cb.isChecked(),
Toast.LENGTH_LONG).show()
rowcheck.setSelected(cb.isChecked());
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
Country rowcheck = rowcheckList.get(position);
// holder.code.setText(" (" + rowcheck.getCode() + ")");
holder.code.setText(rowcheck.getName());
// holder.name.setText(rowcheck.getName());
holder.name.setChecked(rowcheck.isSelected());
holder.name.setTag(rowcheck);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) findViewById(R.id.findSelected);
myButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
StringBuffer responseText = new StringBuffer();
responseText.append("The following were selected...\n");
ArrayList<Country> rowcheckList = dataAdapter.rowcheckList;
System.out.println("Size" + rowcheckList.size());
int j = 0;
ArrayList<String> stt = new ArrayList<String>();
for (int i = 0; i < rowcheckList.size(); i++) {
Country rowcheck = rowcheckList.get(i);
// System.out.println(rowcheck.getName());
if (rowcheck.isSelected()) {
stt.add(rowcheck.getName());
// Country.st=new ArrayList<String>();
String s = rowcheck.getName();
System.out.println("String--" + rowcheck.getName());
Country.st.add(s);
j = j++;
System.out.println(j++);
responseText.append("\n" + rowcheck.getName());
}
}
for (int i = 0; i < stt.size(); i++) {
System.out.println("Names----" + stt.get(i).toString());
}
if (j >= 1 && j <= 5) {
Intent i = new Intent(ListViewCheckboxesActivity.this,
PickedItemListView.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
} else {
Toast.makeText(ListViewCheckboxesActivity.this,
"Maximum 5 Selection Allowed", Toast.LENGTH_LONG)
.show();
}
Toast.makeText(ListViewCheckboxesActivity.this, responseText,
Toast.LENGTH_LONG).show();
}
});
}
//Logout ALert Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
LayoutInflater inflater = LayoutInflater
.from(ListViewCheckboxesActivity.this);
View dialogview = inflater.inflate(R.layout.logout_popup, null);
final Button ok = (Button) dialogview.findViewById(R.id.ok);
final Button cancel = (Button) dialogview.findViewById(R.id.cancel);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(
(ListViewCheckboxesActivity.this));
dialogbuilder.setView(dialogview);
dialogbuilder.setInverseBackgroundForced(true);
alertdialog = dialogbuilder.create();
alertdialog.show();
ok.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.dismiss();
final Intent intent = new Intent(
ListViewCheckboxesActivity.this,
LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}
});
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View paramView) {
alertdialog.cancel();
}
});
}
return super.onKeyDown(keyCode, event);
}
}
checkBox_sound.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
var boolSoundOn = (isChecked) ? true : false;
}
});
It works Perfect...

Categories

Resources