I have an application in which there is a listview that displays values and when a row is pressed, the third value of the row will display a value.
Example is: third value is 30 and when it's pressed, it should be
divided by 6, so the answer should be 5.
But when I scroll and press a row in listview example: I pressed row1, there will be a duplicate checked row in row10 and the value of the third row returns to it's old value (30) for example.
Is there any way to keep the checkbox from duplicating and the value of the row preserved when clicked?
Here's my code for the adapter:
public class MyAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> mData;
public MyAdapter(ArrayList<HashMap<String, String>> mData2) {
this.mData = mData2;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public Object getItem(int i) {
return this.mData.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("betid");
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.tx_counter = (TextView) mView.findViewById(R.id.tx_counter);
mView.setTag(holder);
} else {
holder = (ViewHolder) mView.getTag();
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
String amountRamble = mData.get(i).get("amountRamble");
holder.tx_number.setText(betnumber);
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_counter;
}
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox checkBox = (CheckBox)view.findViewById(R.id.checkmark);
TextView tv3 = (TextView)view.findViewById(R.id.tx_counter);
EditText editText = (EditText)findViewById(R.id.editText3);
String yy = editText.getText().toString().trim();
String shitts = listView.getItemAtPosition(position).toString();
ArrayList<String> list = new ArrayList<String>();
try {
String[] a = shitts.split(", ");
String[] b = a[1].split("=");
String[] sep = a[0].split("=");
String betnumber = sep[1];
String betamount= b[1];
checkBox.setChecked(!checkBox.isChecked());
if(checkBox.isChecked()){
//sort number
final String sorted = betnumber.chars().sorted().mapToObj(c -> Character.valueOf((char)c).toString()).collect(Collectors.joining());
//check if double digit
Boolean checker = doubleChecker(sorted);
if (checker == true){
Toast.makeText(getApplicationContext(),"DOUBLE DIGIT", LENGTH_SHORT).show();
int answer = Integer.parseInt(betamount) / 3;
tv3.setText(String.valueOf(answer));
}else{
Toast.makeText(getApplicationContext(),"NOT DOUBLE DIGIT", LENGTH_SHORT).show();
int answer;
if(yy.equals("")){
answer = Integer.parseInt(betamount) / 6;
tv3.setText(String.valueOf(answer));
}else{
answer = (Integer.parseInt(betamount) - Integer.parseInt(yy)) / 6;
tv3.setText(String.valueOf(answer));
}
}
//TODO save to array to send
}else{
//TODO mistake RETURN tv3 to old value // remove from array
tv3.setText("0");
}
}catch (Exception e){
}
}
});
I think the issue is here
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("amountTarget");
String amountRamble = mData.get(i).get("amountRamble");
holder.tx_number.setText(betnumber);
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
}
You are missing an elsestatement to set other values when betid is null.
If betid is null, other rows can hold values from previous rows.
...
holder.tx_amount.setText(amountTarget);
holder.tx_counter.setText(amountRamble);
} else {
// assuming that if betid is null, then, TextViews should be cleared
// or replace with your own values
holder.tx_number.setText("");
holder.tx_amount.setText("");
holder.tx_counter.setText("");
}
Related
I am working on restaurant app wants to display selected items for order, with their price per item and total price (count*price) of each item. I want to add those total price of list of card items and display on text view outside Recycler View that will change dynamically.
Inside each card View, there are two buttons(- and +) that change the count value for each item so that it changes the total price of each item.
Here is My adapter class
public class MyListsToOrderAdapter extends
RecyclerView.Adapter<MyListsToOrderAdapter.MyHOldd>{
ArrayList<Element> element;
Context ctx;
TextView textView;
String c;
String db = "Elements";
String dbp = "Prices";
PriceDao priceDao;
ElementDao elementDao;
int count=0;
private LayoutInflater inflater;
float v1,v4,v5,v2,v3,v6;
float x1,x2,x3=0;
public MyListsToOrderAdapter( ArrayList<Element> element,Context ctx,TextView textView) {
this.textView=textView;
this.ctx = ctx;
this.element = element;
inflater = LayoutInflater.from(ctx);
}
#Override
public MyListsToOrderAdapter.MyHOldd onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.card_lists_to_order,parent,false);
MyHOldd holder = new MyHOldd(view,ctx,element);
return holder;
}
#Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {
priceDao=setUpDBPrice();
String bs= element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v1 = Float.parseFloat(pricev);
v2= Float.parseFloat(element.get(position).getCount());
v3=v1*v2;
final String res = String.valueOf(v3);
holder.listName.setText(element.get(position).getDescription());
holder.add.setImageResource(R.drawable.add);
holder.sub.setImageResource(R.drawable.minus);
holder.pricess.setText(pricev);
holder.totalPriceT.setText(res);
holder.status.setText(element.get(position).getCount());
if(v5==1)v5=v6;
else if(v5==2) v5=-v6;
else if(v5==3) v5=0;
else v5=v3;
v4=v4+v5;
String ch = String.valueOf(v4);
textView.setText("Total: "+ch);
}
#Override
public int getItemCount() {
return element.size();
}
class MyHOldd extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView listName;
public TextView pricess;
public TextView status;
public TextView totalPriceT;
public ImageView add;
public ImageView sub;
int count;
Context ctx;
ArrayList<Element> element = new ArrayList<>();
ElementDao elementDao = setupDbElement();
public MyHOldd(View itemView, Context ctx, ArrayList<Element> element) {
super(itemView);
this.ctx=ctx;
this.element=element;
listName = (TextView)itemView.findViewById(R.id.TitemName);
pricess = (TextView)itemView.findViewById(R.id.TitemPrice);
status = (TextView)itemView.findViewById(R.id.Tstatus);
totalPriceT = (TextView)itemView.findViewById(R.id.totalPrice);
add = (ImageView) itemView.findViewById(R.id.TplusSign);
sub = (ImageView) itemView.findViewById(R.id.TminusSign);
add.setOnClickListener(this);
sub.setOnClickListener(this);
}
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Element element = this.element.get(position);
String bd= element.getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v6 = Float.parseFloat(pricev);
x3=v6*count;
v5=0;
count= Integer.parseInt(element.getCount());
if(view.getId()==add.getId()) {
count = count+1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=1;
} else if (view.getId()==sub.getId()) {
if(count==0) {
count = 0;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=3;
}
else {
count = count-1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=2;
}
}
count= Integer.parseInt(element.getCount());
}
}
#Habatamu
Everytime you click add or sub imageview the textview for totalSum should be updated. In your case, the override method onclick does not seems to be updating the totalSum.
it works like this for me, I changed notifyDataSetChanged(); into notifyItemChanged(position);
so that I can get the total value (v4) and pass it to text view as shown
#Override
public void onClick(View view) {
int position = getAdapterPosition();
Element element = this.element.get(position);
String bd= element.getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bd)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v6 = Float.parseFloat(pricev);
x3=v6*count;
v5=0;
count= Integer.parseInt(element.getCount());
if(view.getId()==add.getId()) {
count = count+1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=1;
} else if (view.getId()==sub.getId()) {
if(count==0) {
count = 0;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=3;
}
else {
count = count-1;
c = String.valueOf(count);
element.setCount(c);
elementDao.update(element);
notifyDataSetChanged();
v5=2;
}
}
count= Integer.parseInt(element.getCount());
}
}
///////////////////////////////
so that I can get the total value (v4) and pass it to text view as shown
#Override
public void onBindViewHolder(final MyListsToOrderAdapter.MyHOldd holder, final int position) {
priceDao=setUpDBPrice();
String bs= element.get(position).getCode();
List<Price> priceList = priceDao.queryBuilder().where(PriceDao.Properties.ElCode.eq(bs)).list();
String pricev = priceList.get(0).getPriceValue();
// Calculating the total price of each
v1 = Float.parseFloat(pricev);
v2= Float.parseFloat(element.get(position).getCount());
v3=v1*v2;
final String res = String.valueOf(v3);
holder.listName.setText(element.get(position).getDescription());
holder.add.setImageResource(R.drawable.add);
holder.sub.setImageResource(R.drawable.minus);
holder.pricess.setText(pricev);
holder.totalPriceT.setText(res);
holder.status.setText(element.get(position).getCount());
holder.addNote.setText("Add");
// Calculating the Total price of all items
if(v5==1)v5=v6;
else if(v5==3) v5=-v6;
else if(v5==2) v5=0;
else v5=v3;
v4=v4+v5;
// displayin on the textView
String ch = String.valueOf(v4);
textView.setText("Total: "+ch);
}
I have a listview with a check box, if scrolled up or down, the checkbox becomes unchecked. How can I fix this?
Here is my listviewadapter:
String myisme = "1";
private int SELF = 100;
static final int CUSTOM_DIALOG_ID1 = 1;
public FeedHomeAdapter(Context c, ArrayList<String> id, ArrayList<String> uname,
ArrayList<String> fname, ArrayList<String> time, ArrayList<String> status,
ArrayList<String> promo, ArrayList<String> ifliked, ArrayList<String> uid, ArrayList<String> pspic,
ArrayList<String> ppic, ArrayList<String> pcolor, ArrayList<String> slike, ArrayList<String> scomment,
ArrayList<String> slink, ArrayList<String> slinktext, ArrayList<String> sother,
ArrayList<String> sid, ArrayList<String> svideo, ArrayList<String> isfollow, ArrayList<String> ischat) {
this.mContext = c;
this.id = id;
this.puName = uname;
this.pfName = fname;
this.ptime = time;
this.psatus = status;
this.ppromo = promo;
this.pifliked = ifliked;
this.puid = uid;
this.pstatuspc = pspic;
this.pprofilepc = ppic;
this.pprofilecolor = pcolor;
this.statuslike = slike;
this.statuscomment = scomment;
this.statuslink = slink;
this.statuslinktext = slinktext;
this.statusother = sother;
this.statusid = sid;
this.statusvideo = svideo;
this.isfollowing = isfollow;
this.pischat = ischat;
}
public int getCount() {
// TODO Auto-generated method stub
return id.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
return position;
}
public ArrayList<int[]> getSpans(String body, char prefix) {
ArrayList<int[]> spans = new ArrayList<int[]>();
Pattern pattern = Pattern.compile(prefix + "\\w+");
Matcher matcher = pattern.matcher(body);
// Check all occurrences
while (matcher.find()) {
int[] currentSpan = new int[2];
currentSpan[0] = matcher.start();
currentSpan[1] = matcher.end();
spans.add(currentSpan);
}
return spans;
}
public View getView(final int pos, View child, ViewGroup parent) {
final Holder mHolder;
if (child == null) {
child = LayoutInflater.from(mContext).inflate(R.layout.chat_display_item, parent, false);
LayoutInflater layoutInflater;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.card_layout, null);
mHolder = new Holder();
mHolder.txt_uName = (TextView) child.findViewById(R.id.name);
mHolder.txt_uName1 = (TextView) child.findViewById(R.id.name1);
mHolder.txt_fName = (TextView) child.findViewById(R.id.fname);
mHolder.txt_satus = (TextView) child.findViewById(R.id.note);
mHolder.txt_time = (TextView) child.findViewById(R.id.time);
mHolder.txt_linktext = (TextView) child.findViewById(R.id.lint_title);
mHolder.cunt_like = (TextView) child.findViewById(R.id.l_count);
mHolder.like_text = (TextView) child.findViewById(R.id.like_text);
mHolder.cunt_comment = (TextView) child.findViewById(R.id.c_count);
mHolder.com_text = (TextView) child.findViewById(R.id.com_text);
mHolder.txt_promo = (TextView) child.findViewById(R.id.promoted);
mHolder.like = (ThumbUpView) child.findViewById(R.id.tpv2);
mHolder.profile_pic = (CircleImageView) child.findViewById(R.id.profilePic);
mHolder.status_pic = (ProportionalImageView) child.findViewById(R.id.status_pic);
mHolder.video_cover = (RelativeLayout) child.findViewById(R.id.video_cover);
mHolder.video_view = (FensterVideoView) child.findViewById(R.id.play_video_texture);
mHolder.download = (LinearLayout) child.findViewById(R.id.download);
mHolder.error_d = (LinearLayout) child.findViewById(R.id.error_d);
mHolder.profile_view = (RelativeLayout) child.findViewById(R.id.id_to_profile);
mHolder.comment = (ImageButton) child.findViewById(R.id.replide);
child.setTag(mHolder);
} else {
mHolder = (Holder) child.getTag();
}
mHolder.txt_satus.setHighlightColor(Color.WHITE);
mHolder.txt_satus.setHighlightColor(Color.TRANSPARENT);
if (statuslike.get(pos).toString().equals("0")) {
mHolder.like_text.setVisibility(View.GONE);
} else {
mHolder.cunt_like.setText(statuslike.get(pos));
}
if (statuscomment.get(pos).toString().equals("0")) {
mHolder.com_text.setVisibility(View.GONE);
} else {
mHolder.cunt_like.setText(statuslike.get(pos));
mHolder.cunt_comment.setText(statuscomment.get(pos));
}
mHolder.txt_linktext.setText(statuslinktext.get(pos));
mHolder.txt_time.setText(ptime.get(pos));
if (pifliked.get(pos).toString().equals("liked")) {
//set liked
mHolder.like.Like();
} else {
//set like
mHolder.like.UnLike();
}
// init Effects class
Effects.getInstance().init(mContext);
mHolder.like.checkbox(new ThumbUpView.OnThumbUp() {
#Override
public void like(boolean like) {
FeedCache controller = new FeedCache(mContext);
dataBaseall = controller.getWritableDatabase();
ContentValues values = new ContentValues();
if (like) {
String yesliked = "liked";
values.put(FeedCache.KEY_IFLIKE, yesliked);
dataBaseall.update(FeedCache.TABLE_NAME, values, FeedCache.KEY_NOTEID + "= '" + statusid.get(pos) + "'", null);
mHolder.cunt_like.setText(String.valueOf(Integer.valueOf(mHolder.cunt_like.getText().toString()) + 1));
Effects.getInstance().playSound(Effects.SOUND_1);
} else {
String yeslike = "like";
values.put(FeedCache.KEY_IFLIKE, yeslike);
dataBaseall.update(FeedCache.TABLE_NAME, values, FeedCache.KEY_NOTEID + "= '" + statusid.get(pos) + "'", null);
mHolder.cunt_like.setText(String.valueOf(Integer.valueOf(mHolder.cunt_like.getText().toString()) - 1));
Effects.getInstance().playSound(Effects.SOUND_1);
}
//close database
dataBaseall.close();
}
});
public class Holder {
TextView txt_id;
TextView txt_satus;
TextView txt_time;
TextView txt_uName;
TextView txt_uName1;
TextView txt_fName;
TextView like_text;
TextView cunt_like;
TextView cunt_comment;
TextView com_text;
TextView txt_linktext;
TextView txt_promo;
ThumbUpView checkbox;
}
}
}
You are number 12345 with this problem. Your problem (recycling of list items) has been reported many times on stackoverflow. So just google a bit for the solution. To give you a hint: you should add a boolean array indicating the checked state of every checkbox. And set the checkbox in getView() according to array value for position. In an onClickListener for the checkbox set the value of the corrresponding array item to the checked state.
The Problem is :
I am having list of products in listview and a textview following incremenat/decrement buttons. If I perform increment and decrement on first item of the listview it changes to the other listview positions also while performing scrolling on it.
what all I have tried so far:
TextView's value changed while scrolling listview
TextView in listview rows showing repeated values on scroll in Android?
Duplicated entries in ListView
Android list items are changing when scrolling
I was not able to solve my problem with none of these.
I am stuck with this problem from last three days. Any one please help me with it I will be really grateful to you. Thanks
This is my code of Adapter Class:
class SubProductsListAdapter extends BaseAdapter{
private Context context;
// private ArrayList<String> list;
DBHelper dbHelper;
ArrayList<AddedProducts> arrayList;
boolean exists;
String addedQuant;
String quant;
String discounted;
String finalPrice;
URI uri;
private List<SubProductData> subProductDataList = null;
public SubProductsListAdapter(Context context, ArrayList<SubProductData> list){
this.context = context;
this.subProductDataList = list;
}
#Override
public int getCount() {
return subProductDataList.size();
}
#Override
public Object getItem(int position) {
return subProductDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
dbHelper = new DBHelper(context);
convertView = LayoutInflater.from(context).inflate(R.layout.sub_fragment_list_items,null,false);
holder.ItemImage = (ImageView) convertView.findViewById(R.id.item_image);
holder.txtItemName = (TextView) convertView.findViewById(R.id.item_name);
holder.disCountedPrice = (TextView) convertView.findViewById(R.id.discounted_price);
holder.finalPrice = (TextView) convertView.findViewById(R.id.final_price);
holder.quantity = (TextView) convertView.findViewById(R.id.quantity);
holder.addedQuantity = (TextView) convertView.findViewById(R.id.item_quantity);
holder.addItem = (Button) convertView.findViewById(R.id.add);
holder.removeItem = (Button) convertView.findViewById(R.id.remove);
holder.v = (Vibrator) this.context.getSystemService(Context.VIBRATOR_SERVICE);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
/** set item name from the arrayList */
holder.txtItemName.setText(subProductDataList.get(position).getProductName());
final String url = subProductDataList.get(position).getProductImage();
String parentUrl = "http://test//";
String finalUrl = parentUrl+url;
try {
uri = new URI(finalUrl.replaceAll(" ", "%20"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
Picasso.with(context)
.load(String.valueOf(uri)) // loaded image
.placeholder(R.drawable.categorydefault) // thumbnail image
.error(R.drawable.categorydefault) // if unable to load image or fetch image from server
.into(holder.ItemImage);
String productPrice = subProductDataList.get(position).getProductPrice();
double myProductFianlPrice = Double.parseDouble(productPrice);
myProductFianlPrice =Double.parseDouble(new DecimalFormat("##.####").format(myProductFianlPrice));
holder.finalPrice.setText(String.valueOf(myProductFianlPrice));
/** Strike discounted price */
holder.disCountedPrice.setPaintFlags(holder.disCountedPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
addedQuant = holder.addedQuantity.getText().toString();
discounted = holder.disCountedPrice.getText().toString();
finalPrice = holder.finalPrice.getText().toString();
/** Setting quantitiy of products from databse to textview */
final String itemName =subProductDataList.get(position).getProductName();
arrayList = dbHelper.getAllProducts();
exists = false;
for (AddedProducts hmap : arrayList)
{
if (hmap.getTitle().equals(itemName))
{
exists = true;
break;
}}
if (exists){
Cursor id = dbHelper.getQuantityOfProduct(itemName);
quant = null;
id.moveToFirst();
if (id.moveToFirst()) {
quant = id.getString(id.getColumnIndex("qty"));
Log.e(quant,"this is my quantity");
}
holder.addedQuantity.setText(quant);
}
/** Add items to the cart */
holder.addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String present_value_string = holder.addedQuantity.getText().toString();
int present_value_int = Integer.parseInt(present_value_string);
present_value_int++;
holder.addedQuantity.setText(String.valueOf(present_value_int));
addedQuant = holder.addedQuantity.getText().toString();
float tot = Float.parseFloat(finalPrice) * present_value_int;
int dis = Integer.parseInt(discounted) * present_value_int;
String itemName =subProductDataList.get(position).getProductName();
String proIds = subProductDataList.get(position).getProductId();
String proModel = subProductDataList.get(position).getProductModel();
Log.e(proModel,"productModel");
final String url = subProductDataList.get(position).getProductImage();
String parentUrl = "http://falconet.co.in/jubstore/image/";
String finalUrl = parentUrl+url;
try {
uri = new URI(finalUrl.replaceAll(" ", "%20"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
boolean test = dbHelper.CheckIsDataAlreadyInDBorNot(itemName);
if (!test)
{
dbHelper.insertProduct(context,itemName,proIds,finalPrice, discounted,present_value_int,proModel,String.valueOf(uri),tot,dis);
}
else
{
//item already exists
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
Log.e(myId,"this is my id");
}
float tots = Float.parseFloat(finalPrice) * present_value_int;
dbHelper.updateProduct(Integer.parseInt(myId),present_value_int,tots);
Log.e(String.valueOf(tots),"updatedtotalcheck");
}
}
});
/** remove items from the cart */
holder.removeItem.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.KITKAT)
#Override
public void onClick(View v) {
String present_value_string = holder.addedQuantity.getText().toString();
int present_value_int = Integer.parseInt(present_value_string);
if (present_value_int > 0) {
present_value_int--;
holder.addedQuantity.setText(String.valueOf(present_value_int));
holder.v.vibrate(300);
String itemName =subProductDataList.get(position).getProductName();
boolean test = dbHelper.CheckIsDataAlreadyInDBorNot(itemName);
if (test)
{
//item already exists
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
Log.e(myId,"this is my id");
}
float tots = Float.parseFloat(finalPrice) * Integer.parseInt(addedQuant);
dbHelper.updateProduct(Integer.parseInt(myId),present_value_int,tots);
}
}
/** if textview quantity is equal to zero remove product from cart */
if (holder.addedQuantity.getText().toString() == "0"){
Cursor id = dbHelper.getQuantityData(itemName);
String myId = null;
id.moveToFirst();
if (id.moveToFirst()) {
myId = id.getString(id.getColumnIndex("id"));
SubProductsListAdapter.this.notifyDataSetChanged();
}
if (myId != null) {
dbHelper.deleteProduct(Integer.valueOf(myId));
}
}
}});
return convertView;
}
class ViewHolder{
Button removeItem;
Button addItem;
TextView disCountedPrice,finalPrice,quantity,addedQuantity;
ImageView ItemImage;
TextView txtItemName;
Vibrator v;
}
}
Add one variable in holder class that store value of quantity and set last quantity in it.
class ViewHolder{
int quanity
}
store that quantity
holder.quantity = your quantity
now you can get last quantity value from holder and place it to your textview.
/** set item name from the arrayList */
holder.txtItemName.setText(subProductDataList.get(position).getProductName());
holder.txtQuanity.setText(holder.quantity)
Hope this will help.
I have made a listview with a custom adapter. There are five textviews, 1 checkbox and one button.
-------------------------------------
<TextView>
<TextView> <checkbox>
<TextView>
<TextView> <button>
<TextView>
-------------------------------------
The arraylists that I am using to populate the textviews in the list has proper unique data. But the listview takes only four to five values of the begining and repeates it in the rest of the list.
Also when I scroll the values displayed change automatically. For example item A was displayed at first position. So when I scroll down and then come up again, item C or item D is displayed.
It is really confusing me! Please help!
Custom Adapter code
protected class MyCustomAdapter extends ArrayAdapter<String>
{
int len;
private SparseBooleanArray mCheckStates;
private SparseBooleanArray favourites;
ArrayList<String> myMake, myModel, myVer, myPrice, myPlace, sellr_pos;
int count = 0;
ViewHolder holder = null;
Boolean status;
public MyCustomAdapter(Context context, int textViewResourceId,
ArrayList<String> car_make, ArrayList<String> car_model,
ArrayList<String> car_version, ArrayList<String> car_price,
ArrayList<String> car_place, ArrayList<String> sellr_pos) {
super(context, textViewResourceId);
mCheckStates = new SparseBooleanArray(car_model.size());
favourites = new SparseBooleanArray(car_model.size());
myMake = car_make;
myModel = car_model;
myVer = car_version;
myPrice = car_price;
myPlace = car_place;
}
private class ViewHolder {
TextView txt1, txt2, txt3, txt4, txt5;
CheckBox chkbox;
Button btn_fav;
}
#Override
public int getCount() {
return myMake.size();
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.text_adaptr, null);
holder = new ViewHolder();
holder.txt1 = (TextView) convertView.findViewById(R.id.text1);
holder.txt2 = (TextView) convertView.findViewById(R.id.text5);
holder.txt3 = (TextView) convertView.findViewById(R.id.text3);
holder.txt4 = (TextView) convertView.findViewById(R.id.text4);
holder.txt5 = (TextView) convertView.findViewById(R.id.text2);
System.out.println("ListView position: " + position);
holder.txt1.setText(myMake.get(position));
holder.txt2.setText(myModel.get(position));
holder.txt3.setText(myVer.get(position));
holder.txt4.setText(myPrice.get(position));
holder.txt5.setText(myPlace.get(position));
holder.chkbox = (CheckBox) convertView
.findViewById(R.id.checkBox1);
holder.btn_fav = (Button) convertView.findViewById(R.id.fav);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.chkbox.setTag(position);
holder.chkbox.setChecked(mCheckStates.get(position, false));
if (favourites.get(position, false)) {
holder.btn_fav.setBackgroundResource(R.drawable.star);
} else {
holder.btn_fav.setBackgroundResource(R.drawable.star_grey);
}
len = fav_ids.size();
System.out.println("FAV_IDS len:" + len);
for (int t = 0; t < len; t++) {
String pos_id = pos.get(position).trim();
String fav_id = fav_ids.get(t).trim();
if (pos_id.equals(fav_id)) {
holder.btn_fav.setBackgroundResource(R.drawable.star);
break;
} else {
holder.btn_fav.setBackgroundResource(R.drawable.star_grey);
}
}
holder.chkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something
}
});
holder.btn_fav.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something
}
});
return convertView;
}
}
Set Values to the TextView at
if (convertView == null) {
....code...
........../.
/*
you are setting values here
remove it from here
*/
holder.txt1.setText(myMake.get(position));
holder.txt2.setText(myModel.get(position));
holder.txt3.setText(myVer.get(position));
holder.txt4.setText(myPrice.get(position));
holder.txt5.setText(myPlace.get(position));
}
else
{
....code...
}
/*
Set values here
it will solve the problem
*/
holder.txt1.setText(myMake.get(position));
holder.txt2.setText(myModel.get(position));
holder.txt3.setText(myVer.get(position));
holder.txt4.setText(myPrice.get(position));
holder.txt5.setText(myPlace.get(position));
It solves my problem
I have a listview in my application.I want to set the value of textview in that particular row when I click one of the textview in that row itself.so,I tried like below
likes.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
TextView t=(TextView)v;
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
int i= Integer.parseInt(likescount.get(position));
if(like_or_ulike.get(position).equals("Like")){
Log.e("inlike","like");
like_or_ulike.set(position, "Unlike");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"post");
j=i+1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
else{
Log.e("unlike","unlike");
like_or_ulike.set(position, "Like");
t.setText(like_or_ulike.get(position));
UrltoValue.getValuefromUrl("https://graph.facebook.com/"+objectid.get(position)+"/likes?access_token="+accesstoken+"&method="+"DELETE");
j=i-1;
String s=Integer.toString(j);
likescount.set(position, s);
likesnumber1.setText(likescount.get(position));
}
}
});
the "likes" reference which I used is textview and I want to set the textview by getting the id of that particular row.
TextView likesnumber1 = (TextView) findViewById(R.id.likesnumber);
when I use this I am getting the id of the first visible row of the screen.
How can I get the id of textview of that particular row,on a textview click.
Thanks
I'm not sure how you are populating your list with data, however here is a method I use that works very well.
Data Models
public class Publication {
public String string1;
public String string2;
public Publication() {
}
public Publication(String string1, String string2) {
this.string1= string1;
this.string2= string2;
}
}
Create an array adapter
public class ContactArrayAdapter extends ArrayAdapter<ContactModel> {
private static final String tag = "ContactArrayAdapter";
private static final String ASSETS_DIR = "images/";
private Context context;
//private ImageView _emotionIcon;
private TextView _name;
private TextView _email;
private CheckBox _checkBox;
private List<ContactModel> contactModelList = new ArrayList<ContactModel>();
public ContactArrayAdapter(Context context, int textViewResourceId,
List<ContactModel> objects) {
super(context, textViewResourceId, objects);
this.context = context;
this.contactModelList = objects;
}
public int getCount() {
return this.contactModelList.size();
}
public ContactModel getItem(int index) {
return this.contactModelList.get(index);
}
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
// ROW INFLATION
Log.d(tag, "Starting XML Row Inflation ... ");
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.contact_list_entry, parent, false);
Log.d(tag, "Successfully completed XML Row Inflation!");
}
// Get item
final ContactModel contactModel = getItem(position);
Resources res = this.getContext().getResources();
//Here are some samples so I don't forget...
//
//_titleCount = (TextView) row.findViewById(R.id.category_count);
// _category.setText(categories1.Category);
//
//if (categories1.Category.equals("Angry")) {
//Drawable angry = res.getDrawable(R.drawable.angry);
//_emotionIcon.setImageDrawable(angry);
//}
_checkBox = (CheckBox) row.findViewById(R.id.contact_chk);
_email = (TextView) row.findViewById(R.id.contact_Email);
_name = (TextView)row.findViewById(R.id.contact_Name);
//Set the values
_checkBox.setChecked(contactModel.IsChecked);
_email.setText(contactModel.Email);
_name.setText(contactModel.Name);
_checkBox.setOnClickListener(new CompoundButton.OnClickListener() {
#Override
public void onClick(View view) {
if (contactModel.IsChecked) {
contactModel.IsChecked = false;
notifyDataSetChanged();
}
else {
contactModel.IsChecked = true;
notifyDataSetChanged();
}
}
});
return row;
}
}
Use the array adapter to fill your list
ContactArrayAdapter contactArrayAdapter;
//
List<ContactModel> contactModelList;
//Fill list with your method
contactModelList = getAllPhoneContacts();
//
contactArrayAdapter = new ContactArrayAdapter(getApplicationContext(), R.layout.contact_list_entry, contactModelList);
//
setListAdapter(contactArrayAdapter);
A sample method to fill data:
public List<ContactModel> getAllPhoneContacts() {
Log.d("START","Getting all Contacts");
List<ContactModel> arrContacts = new Stack<ContactModel>();
Uri uri = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
Cursor cursor = getContentResolver().query(uri, new String[] {ContactsContract.CommonDataKinds.Email.DATA1
,ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
,ContactsContract.CommonDataKinds.Phone._ID}, null , null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
cursor.moveToFirst();
while (cursor.isAfterLast() == false)
{
String email= cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int phoneContactID = cursor.getInt(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone._ID));
if (email != null)
{
ContactModel contactModel = new ContactModel();
contactModel.Name = name;
contactModel.Email = email;
contactModel.IsChecked = false;
arrContacts.add(contactModel);
}
cursor.moveToNext();
}
cursor.close();
cursor = null;
Log.d("END","Got all Contacts");
return arrContacts;
}
Accessing the data on click
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
//Click handler for listview
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView parent, View view, int position, long id) {
ContactModel contact= getItem(position);//This gets the data you want to change
//
some method here tochange set data
contact.email = "new#email.com"
//send notification
contactArrayAdapter.notifyDataSetChanged();
}
});