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.
Related
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("");
}
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 use SQLITE database to store list items and Baseadapter to display listview in my application.
Each item in the listview have edit text value, By default the value is 1.
When user changes the value from 1 to 2 , then the value has to be updated in database.
This update has to be done inside Adapter.
Below is the Adapter code where I change the edit text value.
public class CustomAdapter_cart extends BaseAdapter {
ArrayList<String> list_name = new ArrayList<String>();
ArrayList<String> list_price = new ArrayList<String>();
ArrayList<String> list_images = new ArrayList<String>();
ArrayList<String> list_model = new ArrayList<String>();
ArrayList<String> list_productid = new ArrayList<String>();
ArrayList<Integer> ids = new ArrayList<Integer>();
CustomAdapter_cart cart_refresh;
Bitmap b;
Context context;
AddToCart cart;
String value,name,price,image_new,model,product,qty;
private static LayoutInflater inflater = null;
Cursor cu;
String quant;
Holder holder = new Holder();
SharedPreferences sharedpreferences;
ArrayList<String>listMessages = new ArrayList<String>(new LinkedHashSet<String>());
ArrayList<String> quant_items = new ArrayList<String>();
Cursor mCursor;
ContentValues data=new ContentValues();
String model_item;
String id;
int id_final;
public CustomAdapter_cart(Context context, ArrayList<String> list_name, ArrayList<String> list_price, ArrayList<String> bitmapArray, ArrayList<String> list_model, ArrayList<String> list_productid,ArrayList<String> qty, ArrayList<Integer>ids ) {
this.context = context;
this.list_name = list_name;
this.list_price = list_price;
this.list_images = bitmapArray;
this.list_model = list_model;
this.list_productid = list_productid;
this.quant_items = qty;
this.cart_refresh = this;
this.ids = ids;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list_name.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder {
TextView tv_name, tv_price, tv_model,tv_product,tv_id;
ImageView image;
Button delete;
EditText quantity;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View rowView = convertView;
if (convertView == null) {
// TODO Auto-generated method stub
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.list_items_cart, null);
holder.tv_name = (TextView) rowView.findViewById(R.id.name_cart);
holder.tv_price = (TextView) rowView.findViewById(R.id.price_cart);
holder.image = (ImageView) rowView.findViewById(R.id.image_cart);
holder.tv_model = (TextView) rowView.findViewById(R.id.model_cart);
holder.tv_product = (TextView) rowView.findViewById(R.id.product_cart);
holder.delete = (Button) rowView.findViewById(R.id.delete);
holder.quantity = (EditText) rowView.findViewById(R.id.quantity);
holder.tv_id = (TextView)rowView.findViewById(R.id.ids);
rowView.setTag(holder);
}
else
holder = (Holder) rowView.getTag();
holder.tv_name.setText(list_name.get(position));
name = holder.tv_name.getText().toString();
holder.tv_price.setText(list_price.get(position));
price = holder.tv_price.getText().toString();
holder.tv_model.setText(list_model.get(position));
model = holder.tv_model.getText().toString();
holder.tv_product.setText(list_productid.get(position));
product = holder.tv_product.getText().toString();
holder.quantity.setText(quant_items.get(position));
quant = holder.quantity.getText().toString();
holder.tv_id.setText(Integer.toString(ids.get(position)));
id = holder.tv_id.getText().toString();
id_final = Integer.parseInt(id);
holder.image.setImageBitmap(loadImageFromStorage(list_images.get(position)));
image_new = holder.image.toString();
final View finalRowView1 = rowView;
holder.quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
value = s.toString();
quant.replace(quant, value);
updateTable();
Toast.makeText(finalRowView1.getContext(), "Updating Table", Toast.LENGTH_SHORT).show();
}
});
final View finalRowView = rowView;
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name_item = ((TextView) finalRowView.findViewById(R.id.name_cart)).getText().toString();
String price_item = ((TextView) finalRowView.findViewById(R.id.price_cart)).getText().toString();
model_item = ((TextView) finalRowView.findViewById(R.id.model_cart)).getText().toString();
Intent in = new Intent(context, AddCart_FullImage.class);
in.putExtra("model", model_item);
in.putExtra("name", name_item);
in.putExtra("price", price_item);
context.startActivity(in);
}
});
return rowView;
}
private Bitmap loadImageFromStorage(String path) {
try {
File f = new File(path, "");
f.canRead();
b = BitmapFactory.decodeStream(new FileInputStream(f));
return b;
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
public void updateTable() {
final DatabaseHandler db = new DatabaseHandler(context);
SQLiteDatabase db1 = db.getWritableDatabase();
try {
db.updateContact(new Cart(id_final,name, price, image_new, model, product, value));
Log.v("LOG", "After text change value db " + value);
} catch (Exception e) {
}
}
}
Problem
When I try to update the edit text value, it gets updated in db but again it changes to default value "1".
I am not sure where I am going wrong.
Any help would be really greatfull.
Thanks.
Each time the system wants to redraw your ListView it calls the getView(...) method of your adapter. The following line sets the value of your quantity EditText:
holder.quantity.setText(quant_items.get(position));
When the user changes the value in the EditText you do the following:
quant.replace(quant, value);
updateTable();
As you can see, your adapter's datasource (quant_items) is not updated.
Since you are updating the database from within the adapter, you can just update the quant_items ArrayList and it should do the trick.
You need to notify your adapter if you change its data (and of, you need to update list_name with the new values).
The easiest way to notify your adapter is to use notifyDatasetChanged() after you updated your data.
i've recently started learning android and came across this problem:
after clicking button im displaying new TextView to my ListView - it's a new payment for one of 3 ppl: Lukasz/Marcelina/Karolina - and I want to make every Lukasz' payment appear RED, every Marcelinas BLUE and Karolinas - GREEN
What I tried so far was putting value to a flag (1, 2 or 3) in every CASE in ONCLICK method and adding if statement
if(flag==1){
holder.osoba.setTextColor(Color.RED);
}
else if(flag==2){
holder.osoba.setTextColor(Color.BLUE);
}else if (flag == 3) {
holder.osoba.setTextColor(Color.GREEN);
}
but it turns out I dont set color to a particular item in my List but to all the items (for example when i press 'lukas' it will give me RED Lukasz's payment, but then when I do a Marcelina's new payment which should be BLUE (and Lukasz should star RED) it makes every payment in the list BLUE. Any ideas how to set different color of each List element ?
my Main Activity looks like this:
public class MainActivity extends ListActivity implements View.OnClickListener {
private int flag = 0;
private TextView sum;
private Button addButton;
private EditText addPrice;
private TextView sumPerPerson;
private EditText description;
private ListaWplat listaWplat;
private RadioGroup czlonek;
private RadioButton lukaszRadioButton;
private RadioButton marcelinaRadioButton;
private RadioButton karolinaRadioButton;
private TextView sumaLukasz;
private TextView sumaMarcelina;
private TextView sumaKarolina;
private float tempLukasz = 0;
private float tempMarcelina = 0;
private float tempKarolina = 0;
public float getTempMarcelina() {
return tempMarcelina;
}
public float getTempLukasz() {
return tempLukasz;
}
public float getTempKarolina() {
return tempKarolina;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sum = (TextView) findViewById(R.id.suma);
addButton = (Button) findViewById(R.id.addButton);
addPrice = (EditText) findViewById(R.id.dodajCene);
sumPerPerson = (TextView) findViewById(R.id.sumaNaOsobe);
description = (EditText) findViewById(R.id.description);
sumaLukasz = (TextView) findViewById(R.id.sumaLukasz);
sumaMarcelina = (TextView) findViewById(R.id.sumaMarcelina);
sumaKarolina = (TextView) findViewById(R.id.sumaKarolina);
czlonek = (RadioGroup) findViewById(R.id.czlonek);
lukaszRadioButton = (RadioButton) findViewById(R.id.lukaszRadioButton);
marcelinaRadioButton = (RadioButton) findViewById(R.id.marcelinaRadioButton);
karolinaRadioButton = (RadioButton) findViewById(R.id.karolinaRadioButton);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int checkedRadioButtonId = czlonek.getCheckedRadioButtonId();
switch (checkedRadioButtonId) {
case R.id.lukaszRadioButton:
if (lukaszRadioButton.isChecked()) {
try {
tempLukasz += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy lukasza
String sumaLukasza = getString(R.string.sumaLukasz);
sumaLukasza = String.format(sumaLukasza, getTempLukasz());
sumaLukasz.setText(sumaLukasza + " zl");
flag = 1;
NowaWplata nowaWplata = new NowaWplata(lukaszRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
listaWplat.setWplaty(nowaWplata);
setListAdapter(new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty()));
}
break;
case R.id.marcelinaRadioButton:
if (marcelinaRadioButton.isChecked()) {
try {
tempMarcelina += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy marceliny
String sumaMarceliny = getString(R.string.sumaMarcelina);
sumaMarceliny = String.format(sumaMarceliny, getTempMarcelina());
sumaMarcelina.setText(sumaMarceliny + " zl");
flag=2;
NowaWplata nowaWplata = new NowaWplata(marcelinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
listaWplat.setWplaty(nowaWplata);
setListAdapter(new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty()));
}
break;
case R.id.karolinaRadioButton:
if (karolinaRadioButton.isChecked()) {
try {
tempKarolina += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy karoliny
String sumaKaroliny = getString(R.string.sumaKarolina);
sumaKaroliny = String.format(sumaKaroliny, getTempKarolina());
sumaKarolina.setText(sumaKaroliny + " zl");
flag=3;
NowaWplata nowaWplata = new NowaWplata(karolinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
ListaWplat.setWplaty(nowaWplata);
NewPaymentAdapter npa = new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty());
setListAdapter(npa);
}
break;
}
String sumaCalkowita = getString(R.string.sumaCalkowita);
sumaCalkowita = String.format(sumaCalkowita, getTempKarolina() + getTempLukasz() + getTempMarcelina());
sum.setText(sumaCalkowita);
String sumaSrednia = getString(R.string.sumaSrednio);
sumaSrednia = String.format(sumaSrednia, (getTempKarolina() + getTempLukasz() + getTempMarcelina()) / 3);
sumPerPerson.setText(sumaSrednia);
}
class NewPaymentAdapter extends ArrayAdapter<NowaWplata> {
public LayoutInflater layoutInflater;
public NewPaymentAdapter(Context context, int textViewResourceId, List<NowaWplata> wplaty) {
super(context, textViewResourceId, wplaty);
layoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
NowaWplata nowaWplata = getItem(position);
Holder holder = null;
if(view == null){
view = layoutInflater.inflate(R.layout.nowa_wplata, null);
TextView osobyWplata = (TextView) view.findViewById(R.id.osobaWplata);
TextView kwotaWplaty = (TextView) view.findViewById(R.id.kwotaWplata);
TextView opisWplaty = (TextView) view.findViewById(R.id.opisWplata);
holder = new Holder(osobyWplata, kwotaWplaty, opisWplaty);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
SpannableString spannableString = new SpannableString(nowaWplata.getOsoba().toString());
holder.osoba.setText("[" + nowaWplata.getDate() + "] " + spannableString);
holder.kwota.setText("- " + nowaWplata.getWplata() + "zł");
holder.opis.setText(nowaWplata.getOpis());
return view;
}
}
static class Holder{
public TextView osoba;
public TextView kwota;
public TextView opis;
public Holder(TextView osoba, TextView kwota, TextView opis) {
this.osoba = osoba;
this.opis = opis;
this.kwota = kwota;
}
}
}
Add this flag to the NowaWplata class:
class NowaWplata {
int flag;
public NowaWplata (String par1, String par2, String par3, int flag) {
this.flag = flag;
...
}
}
Then create the instance in next way:
flag=2;
NowaWplata nowaWplata = new NowaWplata(marcelinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString(), flag);
And update your NewPaymentAdapter.getView() method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
NowaWplata nowaWplata = getItem(position);
Holder holder = null;
if(view == null){
view = layoutInflater.inflate(R.layout.nowa_wplata, null);
TextView osobyWplata = (TextView) view.findViewById(R.id.osobaWplata);
TextView kwotaWplaty = (TextView) view.findViewById(R.id.kwotaWplata);
TextView opisWplaty = (TextView) view.findViewById(R.id.opisWplata);
holder = new Holder(osobyWplata, kwotaWplaty, opisWplaty);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
SpannableString spannableString = new SpannableString(nowaWplata.getOsoba().toString());
holder.osoba.setText("[" + nowaWplata.getDate() + "] " + spannableString);
holder.kwota.setText("- " + nowaWplata.getWplata() + "zł");
holder.opis.setText(nowaWplata.getOpis());
if(nowaWplata.flag==1){
holder.osoba.setTextColor(Color.RED);
}
else if(nowaWplata.flag==2){
holder.osoba.setTextColor(Color.BLUE);
}else if (nowaWplata.flag == 3) {
holder.osoba.setTextColor(Color.GREEN);
}
return view;
}
I am using BaseAdapter for loading the data in gridview. When the data is loaded to the gridview, and the user tries to scroll, I used to get incorrect data. In order to fix that I used ViewHolder. That actually fixed the issue, however, when the users click any of the data in the gridview, instead of getting the correct id from the item, all the items are returning a similar id number.
public class ProductAdapter extends BaseAdapter {
// Context context;
private Activity activity;
private ArrayList<HashMap<String, String>> data;
private static LayoutInflater inflater = null;
ViewHolder holder;
int layoutResourceId;
Event event;
EventDBAdapter eventDb;
int id;
PersianCalendar sc;
String Today;
SharedPreferences Prefrences_test;
String date, userid;
String newText = "";
String test;
int status;
MoodsDBAdapter moodsDBAdapter;
Mood mood;
ArrayList<MoodsNote> arrayMoodsNote;
MoodsNoteDBAdapter moodsNoteDBAdapter;
MoodsNote moodsNote;
public ProductAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
activity = a;
// this.context = context;
eventDb = new EventDBAdapter(activity);
event = new Event();
moodsDBAdapter = new MoodsDBAdapter(activity);
mood = new Mood();
moodsNoteDBAdapter = new MoodsNoteDBAdapter(activity);
data = d;
// this.layoutResourceId = layoutResourceId;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Prefrences_test = activity.getSharedPreferences("temp", 0);
date = Prefrences_test.getString("date", "");
userid = Prefrences_test.getString("userid", "");
sc = new PersianCalendar();
Today = date;
eventDb = new EventDBAdapter(activity.getApplicationContext());
event = eventDb.getName(Today);
try {
arrayMoodsNote = moodsNoteDBAdapter.getItems(event.getID());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
holder = null;
HashMap<String, String> song = new HashMap<String, String>();
song = data.get(position);
if (vi == null) {
vi = inflater.inflate(R.layout.note_mood_list_item, null);
holder = new ViewHolder();
holder.title = (TextView) vi.findViewById(R.id.mood_text);
holder.txt_id = (TextView) vi.findViewById(R.id.txt_id_mood);
holder.thumb_image = (ImageView) vi.findViewById(R.id.mood_img);
holder.linear = (LinearLayout) vi.findViewById(R.id.mood_layout);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
holder.linear.setBackgroundResource(R.drawable.bg_mood);
//holder.txt_id.setText("");
String titles = song.get("name");
holder.title.setText(titles);
Resources res = activity.getResources();
int resourceId = res.getIdentifier(song.get("icon"), "drawable",
activity.getPackageName());
holder.thumb_image.setBackgroundResource(resourceId);
holder.txt_id.setText(song.get("id"));
try {
for (MoodsNote m : arrayMoodsNote) {
int moodd = m.getMOOD();
if (Integer.parseInt(holder.txt_id.getText().toString()) == moodd)
{
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
}
} catch (Exception e) {
// TODO: handle exception
}
holder.thumb_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(activity, holder.txt_id.getText().toString(), 0).show();
status = 1;
event = new Event();
int tedad = eventDb.getDate(date);
if (tedad <= 0) {
event = new Event(userid, date);
eventDb.insert(event);
}
event = eventDb.getName(date);
moodsNote = new MoodsNote();
id = 0;
id = Integer.parseInt(holder.txt_id.getText().toString());
// id = rowItem.getID();
int tedadd = moodsNoteDBAdapter.getLastItemID(id);
if (tedadd <= 0)
{
moodsNote.setMOOD(id);
moodsNote.setEVENT(event.getID());
moodsNoteDBAdapter.insert(moodsNote);
holder.linear.setBackgroundResource(R.drawable.bg_mood_on);
}
else {
moodsNoteDBAdapter.deleteId(id);
holder.linear.setBackgroundResource(R.drawable.bg_mood);
}
}
});
return vi;
}
static class ViewHolder {
ImageView thumb_image;
TextView txt_id, title;
LinearLayout linear;
}