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.
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("");
}
I just created an application on android optimized for the mobile phone. Now as the client asked to optimize for 17inch screen size without building separate apk. I almost implemented with some minor UI changes. But in case of listviews, they need Gridviews. So What I did was I created a separate layout for bigger screen with gridview I used a code to detect the screen size and in activity I used a code to detect the screen size and if it's bigger, then I initialized Gridview and after async task i added to a cardview adapter and set the gridview adapter to cardview adapter.
I switched gridview and listview as:
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid = (GridView) getView().findViewById(R.id.card_gridview);
} else {
listView = (ListView)getView().findViewById(R.id.card_listView);
listView.addHeaderView(new View(getActivity()));
listView.addFooterView(new View(getActivity()));
}
Using Restclient helper:
public void fetchTransaction(){
loading.setVisibility(View.VISIBLE);
pd.setMessage("Fetching Transactions..Please Wait");
pd.setCancelable(false);
pd.show();
String fromDate = from.getText().toString();
String toDate = to.getText().toString();
//mydb.deleteAllTransactions();
cardArrayAdapter = new CardArrayAdapter(this.getActivity().getApplicationContext(), R.layout.list_item_card);
cardArrayAdapter.clear();
String android_id = Settings.Secure.getString(getActivity().getContentResolver(),
Settings.Secure.ANDROID_ID);
String userid = prefs.getString("userId","0");
Log.e("TRANSACTON", Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate);
RestClientHelper.getInstance().get(Constants.BASE_URL_TRANSACTIONS+"?deviceid="+android_id+"&userid="+userid+"&from="+fromDate+"&to="+toDate, new RestClientHelper.RestClientListener() {
#Override
public void onSuccess(String response) {
pd.dismiss();
try{
mydb.deleteAllTransactions();
JSONObject result = new JSONObject(response);
JSONArray posts = result.optJSONArray("result");
for (int i = 0; i < posts.length(); i++) {
JSONObject post = posts.optJSONObject(i);
String id = post.optString("id");
String heading = post.optString("heading");
String description = post.optString("description");
String amount = post.optString("amount");
String imageurl = post.optString("imageurl");
String credit = post.optString("credit");
String date = post.optString("date");
String type = post.optString("type");
String service = post.optString("service");
String cost = post.optString("cost");
String balance = post.optString("balance");
String amountinfo = post.optString("amountinfo");
Log.e("ENTERING TO DB","DATA"+i);
Card card = new Card(heading, description,amount,date,credit,imageurl,cost,balance,amountinfo,id,service);
cardArrayAdapter.add(card);
//mydb.addTransactionContact(new TransactionData(heading, description, amount, imageurl,credit,type,date));
}
} catch (JSONException e) {
e.printStackTrace();
}
catch(Exception e){
}
finally {
//showTransaction();
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.INVISIBLE);
if(Constants.isScreenLarge(getActivity())) {
// width > height, better to use Landscape
mygrid.setAdapter(cardArrayAdapter);
} else {
listView.setAdapter(cardArrayAdapter);
}
cardArrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onError(String error) {
pd.dismiss();
SnackbarManager.show(Snackbar.with(getActivity()) // context
.text("An Error occured.. Try after sometime"));
textView2.setText("Some Error Ocurred");
rl = (RelativeLayout)getView().findViewById(R.id.noItems);
rl.setVisibility(view.VISIBLE);
loading.setVisibility(View.INVISIBLE);
}
});
}
My CardArrayAdapter code is:
public class CardArrayAdapter extends ArrayAdapter<Card> {
private static final String TAG = "CardArrayAdapter";
private List<Card> cardList = new ArrayList<Card>();
private Context mContext;
DatabaseUserTable mydb;
PreferenceHelper prefs;
ProgressDialog pd;
static class CardViewHolder {
TextView line1;
TextView line2;
ImageView cimageView;
TextView amount;
TextView credit;
TextView date;
TextView cost;
TextView balance;
TextView amountinfo;
TextView costinfo;
TextView balanceinfo;
}
public CardArrayAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
this.mContext = context;
mydb = new DatabaseUserTable(this.mContext);
prefs = new PreferenceHelper(this.mContext);
pd = new ProgressDialog(this.mContext);
}
#Override
public void add(Card object) {
cardList.add(object);
super.add(object);
}
#Override
public int getCount() {
return this.cardList.size();
}
#Override
public Card getItem(int index) {
return this.cardList.get(index);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CardViewHolder viewHolder;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_card, parent, false);
viewHolder = new CardViewHolder();
viewHolder.line1 = (TextView) row.findViewById(R.id.line1);
viewHolder.line2 = (TextView) row.findViewById(R.id.line2);
viewHolder.amount = (TextView) row.findViewById(R.id.amount);
viewHolder.date = (TextView) row.findViewById(R.id.date);
viewHolder.credit = (TextView) row.findViewById(R.id.credit);
viewHolder.cimageView = (ImageView) row.findViewById(R.id.imageId);
viewHolder.cost = (TextView) row.findViewById(R.id.cost);
viewHolder.balance = (TextView) row.findViewById(R.id.balance);
viewHolder.amountinfo = (TextView) row.findViewById(R.id.amountinfo);
viewHolder.costinfo = (TextView) row.findViewById(R.id.costinfo);
viewHolder.balanceinfo = (TextView) row.findViewById(R.id.balanceinfo);
row.setTag(viewHolder);
} else {
viewHolder = (CardViewHolder)row.getTag();
}
Card card = getItem(position);
viewHolder.line1.setText(card.getLine1());
viewHolder.line1.setTextColor(Color.parseColor("#000000"));
viewHolder.line2.setText(card.getLine2());
viewHolder.line2.setTextColor(Color.parseColor("#999999"));
viewHolder.amount.setText(card.getAmount());
viewHolder.amount.setTextColor(Color.parseColor("#000000"));
viewHolder.date.setText(card.getDate());
viewHolder.date.setTextColor(Color.parseColor("#999999"));
viewHolder.credit.setText(card.getCredit());
viewHolder.credit.setTextColor(Color.parseColor("#000000"));
viewHolder.cost.setText(card.getCost());
viewHolder.cost.setTextColor(Color.parseColor("#000000"));
viewHolder.balance.setText(card.getBalance());
viewHolder.balance.setTextColor(Color.parseColor("#000000"));
viewHolder.amountinfo.setText(card.getAmountinfo());
viewHolder.amountinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.costinfo.setText("Cost");
viewHolder.costinfo.setTextColor(Color.parseColor("#000000"));
viewHolder.balanceinfo.setText("Balance");
viewHolder.balanceinfo.setTextColor(Color.parseColor("#000000"));
final String salesid = card.getSalesid();
final String servicename = card.getServiceName();
row.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Log.e("TRANSACTIONS SERVICENAM",servicename);
if(servicename.equals("VOUCHER")) {
alertBox(v,salesid);
}
else if(servicename.equals("WALLET")) {
SnackbarManager.show(Snackbar.with(v.getRootView().getContext()) // context
.text("No Reprinting available for this transaction"));
}
else if(servicename.equals("ELECTRICITY")) {
errorAlert(v,"Printing not yet supported");
//alertBoxElectricity(v,salesid);
}
else if(servicename.equals("MONEY TRANSFER")) {
//errorAlert(v,"Printing not yet supported");
alertBoxMoney(v,salesid);
}
else{
alertBoxOther(v,salesid);
}
//Toast.makeText(v.getContext(), amountinfo, Toast.LENGTH_SHORT).show();
/*SnackbarManager.show(Snackbar.with(this) // context
.text(amountinfo));*/
}
});
Log.e("card.getLine1()",card.getLine1());
Log.e("TRASACTION URL",Constants.BASE_URL_IMAGE+card.getUrl());
Picasso.with(mContext).load(Constants.BASE_URL_IMAGE+card.getUrl()).fit().placeholder(R.drawable.mobeeloadicon).error(R.drawable.mobeeloadicon).into(viewHolder.cimageView);
return row;
}
But I got the error as:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a
null object reference
How can I change CardArrayAdapter as GridViewAdapter preserving all the Card data. Any Help please
UPDATE
I got this right. It was a silly mistake. I was populating the wrong layout.
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.
I used CustomListAdapter class which extends baseadapter. In that i have a button on each view of the list view ..when I lick on the button it should print a text. everything is working fine except that the text is printed in someother view too. I have found many similar question but no exact solution.
public class CustomListAdapter extends BaseAdapter {
List<HashMap<String, Object>> models;
Context context;
LayoutInflater inflater;
ImageView pic,image,delam;
TextView name,timestamp,msg,url,idas,idas2;
ArrayList<String> listItems;
public int count1 = 0;
ProgressDialog pDialog;
//String session_email="",session_type="",share_app,share_via;
private String stringVal;
private int mCounter1=1;
private int counter=0;
public int temp=0;
String con, pros;
private int[] counters;
int pos;
int width,height;
Transformation transformation;
//ImageButton sharingButton;
String pacm,session_email;
int i ;
ImageButton like;
ImageButton share;
JSONParser jsonParser = new JSONParser();
static String IP = IpAddress.Ip;
//url to create new product
public static String add_wish = IP+"/studio/add_wishlist.php";
private static String url_all_propertiesdel = IP+"/studio/getdelete_all_agent.php";
boolean isSelected;
int a,a1,b,b1;
//private static final String TAG_SUCCESS1 = "mass";
private static final String TAG_USER = "users";
private static final String TAG_PRO = "properties";
//private static final String TAG_PRO1 = "properties1";
// products JSONArray
JSONArray users = null;
//JSONArray users1 = null;
View view;
// JSON Node names
private static final String TAG_SUCCESS = "success";
SharedPreferences sPref;
// int position;
public CustomListAdapter(Context context, List<HashMap<String, Object>> models) {
this.context = context;
this. models = models;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.counters = new int[30];
//this.session_email = sPref.getString("SESSION_UID","");
}
public class ViewHolder {
public TextView countt;
public ImageButton like,share;
}
public void clear(){
if(models!=null)
models.clear();
}
#Override
public int getCount() {
return models.size();
}
public HashMap<String, Object> getItem(int position) {
return models.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
#Override
public View getView( int position, final View convertView, ViewGroup parent) {
// view = null;
view = convertView;
ViewHolder viewHolder;
pos = getItemViewType(position);
// long posn = getItemId(position);
// final int paps= (int)posn ;
if (view == null) {
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.fragment_home2, parent, false);
//your code
//add below code after (end of) your code
viewHolder.like=(ImageButton)view.findViewById(R.id.likem);
viewHolder.share=(ImageButton)view.findViewById(R.id.share);
viewHolder.like.setTag(position);
// viewHolder.share.setTag(position);
/* viewHolder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HashMap<String, Object> item = models.get(position);
Intent share = new Intent(Intent.ACTION_SEND);
// If you want to share a png image only, you can do:
// setType("image/png"); OR for jpeg: setType("image/jpeg");
share.setType("image/*");
// Make sure you put example png image named myImage.png in your
// directory
String imagePath = Environment.getExternalStorageDirectory()
+ "/108.png";
String imagePath = (String)item.get("IMAGE");
Toast.makeText(context, imagePath, Toast.LENGTH_LONG).show();
File imageFileToShare = new File(imagePath);
Uri uri = Uri.fromFile(imageFileToShare);
share.putExtra(Intent.EXTRA_STREAM, uri);
context.startActivity(Intent.createChooser(share, "Share Image!"));
}
});*/
// viewHolder.share.setOnItemClickListener(this);
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (Integer) v.getTag();
// viewHolder.countt = (TextView) v.findViewById(R.id.count);
HashMap<String, Object> item = models.get(position);
isSelected = (Boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
final HashMap<String, Object> item = getItem(position);
// like = (ImageView) view.findViewById(R.id.like);
//sharingButton = (ImageButton) view.findViewById(R.id.share);
// final HashMap<String, Object> item1 = getItem(position);
isSelected = (Boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
pic = (ImageView) view.findViewById(R.id.profilePic);
name = (TextView) view.findViewById(R.id.name);
idas = (TextView) view.findViewById(R.id.hpid);
idas2 = (TextView) view.findViewById(R.id.hpid2);
timestamp = (TextView) view.findViewById(R.id.timestamp);
msg = (TextView) view.findViewById(R.id.txtStatusMsg);
url = (TextView) view.findViewById(R.id.txtUrl);
image = (ImageView) view.findViewById(R.id.feedImage1);
//countt =(TextView)view.findViewById(R.id.count);
/*if any exception raises please use
locationTitle.setText(((String)item.get(“NAME�?)));
use this technique for the Image also.
*/
//holder.like.setText(item.get(item));
//like.setText((String) item.get(R.id.like));
idas.setText((CharSequence) item.get("UIDAS"));
// listItems.add(idas.getText().toString());
name.setText((CharSequence) item.get("NAME"));
timestamp.setText((CharSequence) item.get("TIME"));
msg.setText((CharSequence) item.get("MSG"));
url.setText((CharSequence) item.get("URL"));
//countt.setText((CharSequence) item.get("COUN"));
//count.setText("" + count1);
int w = image.getWidth();
int h = image.getHeight();
if (w > 1000)
{
a=w-1000;
b=w-a;
}
else
{
b=w;
}
if (h > 1000)
{
a1=h-1000;
b1=h-a1;
}
else
{
b1=h;
}
Picasso.with(context)
//.load("PIC")
.load((String)item.get("PIC"))
.placeholder(R.drawable.profile_dummy)
//.error(R.drawable.ic_whats_hot)
.resize(50, 50)
// .centerCrop()
// .fit()
.into(pic);
/*Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width = size.x;*/
Picasso.with(context)
.load((String)item.get("IMAGE"))
//.load("IMAGE")
// .placeholder(R.drawable.ic_pages)
//.error(R.drawable.ic_home)
.resize(1000,b1)
.onlyScaleDown()
//.centerCrop()
// .fit().centerInside()
.into(image);
/*if ((image).length() < 0)
{
//image.setVisibility(View.VISIBLE);
// invalid = true;
idas2.setText(1);
// Toast.makeText(getApplicationContext(), "hgghghghjgh", Toast.LENGTH_LONG).show();
}*/
/* delam.setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
// pacm = idas.getText().toString();
listItems.remove(index.intValue());
notifyDataSetChanged();
}
}
);
*/
/*
delam.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
pacm = idas.getText().toString();
removeItemFromList();
}
});
*/
/* like.setTag(position);
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// int p = (Integer)v.getTag();
//int p;
//int posit=(Integer)v.getTag();
//String s = view[position];
//Context get = null;
//Toast.makeText(context, String.valueOf(p) , Toast.LENGTH_LONG).show();
//like.setBackgroundResource(R.drawable.checked);
if( viewHolder.like.isSelected()){
viewHolder.like.setSelected(false);
//ctv.setBackgroundColor (Color.parseColor("#ffffff"));
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}else if(! viewHolder.like.isSelected()){
viewHolder.like.setSelected(true);
//ctv.setBackgroundColor (Color.parseColor("#d2d0d0"));
viewHolder.like.setBackgroundResource(R.drawable.checked);
}
}
});*/
return view;
}
// HashMap<String, Object> item = models.get(position);
}
Well try this, in your HashMap list you need to have one more item called selected to store selected row status
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
//your code
if (view == null) {
viewHolder = new ViewHolder();
//your code
//add below code after (end of) your code
viewHolder.like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int) v.getTag();
HashMap<String, Object> item = models.get(position);
boolean isSelected = (boolean) item.get("selected");
item.put("selected", !isSelected);
notifyDataSetChanged();
}
});
} else {
viewHolder = (ViewHolder) view.getTag();
}
//updated
viewHolder.like.setTag(position);
final HashMap<String, Object> item = getItem(position);
boolean isSelected = (boolean) item.get("selected");
if (isSelected) {
viewHolder.like.setBackgroundResource(R.drawable.checked);
} else {
viewHolder.like.setBackgroundResource(R.drawable.unchecked);
}
//your other code
}
This problem is due to recycling of Viewholder object in your ListView through convertView. Do not make logic based on the view state as the same state can be passed to some another item of ListView, where it supposed to be presented.
So what to do?
Hold your state on your data Item. And use notify dataSetChanged when you click some item not change its background Directly.
You can see example here. That one id for RecyclerView Adapter, but concept is same. RecyclerView causes issue when recycling
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();
}
});