Getting Text from Textview in Listview inflated Layout - android

I have a listview in which I inflate a layout with multiple textviews and buttons. I understand to get the text from a view that was clicked is ((Textview)view.... However I am trying to get the text from the specific textview that is located in the layout in which the user clicked. I have tried using OnItemClick but when I use this the item must be focused before the any of the buttons functions work. I resorted to and prefer using onClickListeners in the getView method of my custom adapter. So simply put, how do I click a Button and get the text that is in TextView that is located in the appropriate inflated layout list view item, given that since each inflated layout is considered as one list item?
UPDATE
Here are pictures to clarify what i am looking for. Both layouts are members of a listview.
I want to click the button with the date on it and get the text from the textview in the middle of the layout. However when I click the button with the date on it, I can only get the text from the textview in the middle of the layout of the last child. If "My Party" is the first child in the listview and "3303 going away service..." is the second child, when I click the date button the code in my custom adapter returns the text from the last loaded text in the view which will be "3303 going away service". What I am trying to do is when I click the date button on "My party", get the text "My party". Like wise with the second child.
Here is the getView() in my custom adapter.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder = new ViewHolder();
positionHolder = position;
Log.i("Position", "" + position);
if(convertView == null) {
try {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.post_layout, parent, false);
postLayout = convertView;
viewHolder.unameTV = (TextView) postLayout.findViewById(R.id.postUnameTv);
viewHolder.unameTV.setText(viewContent.get(index));
viewHolder.unameTV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Starting new intent
Intent in = new Intent(getActivity(),
Profile.class);
// sending pid to next activity
String username =((TextView)view).getText().toString();
in.putExtra("username", username);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
viewHolder.fillSpace = (TextView)postLayout.findViewById(R.id.posthelpSpace);
viewHolder.fillSpace.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
viewHolder.image = (ImageView) postLayout.findViewById(R.id.postProfPic);
DisplayImageOptions options = initiateDisplayImageOptions();
viewHolder.image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.unameTV.performClick();
}
});
ImageLoader imageloader = ImageLoader.getInstance();
initImageLoader(getActivity());
imageloader.displayImage(viewContent.get(index + 1), viewHolder.image, options);
viewHolder.addToCalendarButton = (TextView) postLayout.findViewById(R.id.addToCalendarButton);
viewHolder.addToCalendarButton.setText(viewContent.get(index + 2));
viewHolder.addToCalendarButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = new GregorianCalendar();
cal.setTime(new Date());
cal.add(Calendar.MONTH, 2);
long time = cal.getTime().getTime();
Uri.Builder builder =
CalendarContract.CONTENT_URI.buildUpon();
builder.appendPath("time");
builder.appendPath(Long.toString(time));
Intent intent =
new Intent(Intent.ACTION_INSERT, CalendarContract.Events.CONTENT_URI);
title = testText.getText().toString();
Log.i("Title", "" + title);
intent.putExtra("title", title); // **NOT WORKING**
startActivity(intent);
}
});
viewHolder.eventTitle = (TextView) postLayout.findViewById(R.id.postTitleTV);
viewHolder.eventTitle.setText(viewContent.get(index + 3));
viewHolder.eventTitle.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
title = ((TextView)view).getText().toString();
Log.i("TITLE", "" + title);
}
});
testText = viewHolder.eventTitle;
viewHolder.eventImage = (ImageView) postLayout.findViewById(R.id.eventImage);
imageloader.displayImage(viewContent.get(index + 4), viewHolder.eventImage, options);
viewHolder.likesTV = (TextView) postLayout.findViewById(R.id.likesTV);
viewHolder.likesTV.setText("" + viewContent.get(index + 5));
viewHolder.planToAttendTV = (TextView) postLayout.findViewById(R.id.planToAttendTV);
viewHolder.planToAttendTV.setText(viewContent.get(index + 6));
viewHolder.addressTV = (TextView) postLayout.findViewById(R.id.postLocationTV);
viewHolder.addressTV.setText("" + viewContent.get(index + 7));
index = index + 8;
}
catch (IndexOutOfBoundsException ie)
{
ie.printStackTrace();
}
}
else
{
viewHolder = (ViewHolder) postLayout.getTag();
}
return postLayout;
}

Create a custom baseadapter and set on click listener for text view in the adapter. This will then be set for the specific text view corresponding to the position.

I think you already have custom BaseAdapter created, in the custom BaseAdapter setOnclicklistener of the textview to which you want the click to be registered.
Sample Code Below
public class M_Adapter extends BaseAdapter {
private LayoutInflater inflater = null;
private TextView contact_name;
private Context context;
private List<String> list;
private List<String> temp;
private Button btn;
public M_Adapter(Context context) {
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
list = new ArrayList<String>();
//add some values in list here
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, final View convertView, ViewGroup parent) {
final View rowview = inflater.inflate(R.layout.contact_listrow, parent, false);
contact_name = (TextView) rowview.findViewById(R.id.excl_ppl_contact_name);
btn=(Button)rowview.findViewById(R.id.excl_ppl_btn);
contact_name.setText(list.get(temp));
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v("myapp", "text clicked " + contact_name.getText());
}
});
return rowview;
}
}

I solved this problem with two series of if/else statements. First, in my onBindViewHolder (your getView) I have some global String variables take on the value of the TextView I'm interested in. Second, in the onClick method, I have the ViewHolder tell me the position of the item clicked using the getPosition method. Last, I match the value of the position clicked with the String variables created in the first part and carry on from there.
public void onBindViewHolder(final ViewHolder holder, final int position) {
YelpAPI.businessNumber = position;
YelpAPI.queryAPI(YelpAPI.yelpApi, YelpAPI.yelpApiCli);
Picasso.with(mContext).load(YelpAPI.picture).into(holder.yelpPicture);
holder.textName.setText(YelpAPI.name);
holder.textRating.setText(YelpAPI.rating);
holder.textReviews.setText(YelpAPI.reviews);
holder.textAddressDetails.setText(YelpAPI.fullAddress);
holder.textInfo.setText(YelpAPI.moreInfo);
holder.textID.setText(YelpAPI.businessID);
---------- First...
if(position == 0){
firstBusiness = YelpAPI.businessID; //these three String variables get created above
} else if(position == 1){
secondBusiness = YelpAPI.businessID;
} else if (position == 2) {
thirdBusiness = YelpAPI.businessID;
}
holder.business.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
----------Second...
int specific = holder.getPosition();
----------Last...
String saveMe = "";
if(specific == 0){
saveMe = firstBusiness;
} else if(specific == 1){
saveMe = secondBusiness;
} else if(specific == 2){
saveMe = thirdBusiness;
}
Log.d("Clicked this item: ", String.valueOf(specific));`

Related

Retrieving element in an ArrayList Adapter

I have created a listview that has an image and a button - I am using ArrayAdapter to view the items in the listview.
When I click on the button I would like to get the details of the item clicked.
So I tried the following:
pd = productList.get(position);
Where productList is ArrayList<ProductDetails> productList;
getproductdetailsbutton is a button in productListadapter extends ArrayAdapter<ProductDetails>
holder.getproductdetailsbutton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String productID = pd.getProductID();
String productName = pd. getProductName();
Log.d("Value", " Product Details " + productID + " " + productName);
}
});
When I click the button from the first item, I get details of the last item displayed on the screen in the log.
How do I get the details of clicked item for that position?
Thanks!
UPDATE: getVIEW Code:
#Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
Typeface tf = Typeface.createFromAsset(contextValue.getAssets(), fontPath);
Typeface tf2 = Typeface.createFromAsset(contextValue.getAssets(), fontPath2);
ViewHolder holder = null;
if (convertView == null)
{
convertView = vi.inflate(R.layout.product_details_items, null);
holder = new ViewHolder();
holder.image = (ImageView) convertView.findViewById(R.id.productimage);
holder.productgetdetails = (Button) convertView.findViewById(R.id.productgetdetails);
holder.productgetdetails.setTag(position);
holder.productgetdetails.setTypeface(tf2);
convertView.setTag(holder);
ProductDetails pd = productList.get(position);
if (pinexist.equalsIgnoreCase(contextValue.getString(R.string.pinexistvalue)))
{
Log.d("Value"," - ID " + pd.getProductID());
if (logdb.checkproductDetailsExists(pd.getProductID()) == 0)
{
holder.productgetdetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Log.e("Value", " = FINAL" + productList.get(position).getProductID());
}
});
}
else
{
holder.productgetdetails.setText(contextValue.getString(R.string.nodata));
}
}
else
{
//DO NOTHING
}
}
else
{
holder = (ViewHolder) convertView.getTag();
}
ProductDetails pd = productList.get(position);
Glide.with(getContext().getApplicationContext())
.load(pd.getProduct_image())
.placeholder(R.drawable.placeholder)
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(holder.image);
return convertView;
}
I guess(actually I'm confident), you must be declaring pd as global variable, which gets updated by last item displayed, try to move pd into getView() and mark it as final so you can use it inside onclick as in
public void getView(){
final ProductDetails pd = productList.get(position);
// your code for click
}
When inflating your layout to view in Adapter
you can set the OnClickListener on the button
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.list_layout, null,true);
final Product pd = pdList.get(position);
//....
Button btn= (Button) = rowView.findViewById(R.id.getproductdetailsbutton);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v) {
String productID = pd.getProductID();
String productName = pd.getProductName();
Log.d("Value", " Product Details " + productID + " " + productName);
}
});
//..
return rowView;
};
Or you can handle ListView OnItemClickListener

OnClickListener Inside Adapter View

In my activity I am displaying a list of data, each row has an edit and delete button. The listeners for these buttons are defined inside the listviews adapter.
I have implemented a custom array adapter:
public class SalesArrayAdapter extends ArrayAdapter<SaleModel> {
private Context context;
private int altColour;
private SaleModel sale;
private int position;
private ArrayList<SaleModel> sales;
private static class ViewHolder{
RelativeLayout container;
TextView tvId;
TextView tvDate;
TextView tvBusNo;
TextView tvDriver;
TextView tvNoOfTrips;
TextView tvTotalExpenditure;
TextView tvTotal;
TextView tvAmountReceived;
TextView tvStatus;
TextView tvReceiptCode;
ImageButton btnEdit;
ImageButton btnRemove;
}
public SalesArrayAdapter(#NonNull Context context, #NonNull ArrayList<SaleModel> sales) {
super(context, R.layout.row_sales, sales);
//this.getContext() = getContext();
//this.sales = sales;
}
#NonNull
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
// Get the data item for this position
sale = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_sales, parent, false);
viewHolder.container = (RelativeLayout) convertView.findViewById(R.id.row_sales_ll_container);
viewHolder.tvId = (TextView) convertView.findViewById(R.id.row_sales_tv_id);
viewHolder.tvDate = (TextView) convertView.findViewById(R.id.row_sales_tv_date);
viewHolder.tvDriver = (TextView) convertView.findViewById(R.id.row_sales_tv_driver);
viewHolder.tvNoOfTrips = (TextView) convertView.findViewById(R.id.row_sales_tv_total_no_of_trips);
viewHolder.tvTotalExpenditure = (TextView) convertView.findViewById(R.id.row_sales_tv_total_expenditure);
viewHolder.tvTotal = (TextView) convertView.findViewById(R.id.row_sales_tv_total);
viewHolder.tvAmountReceived = (TextView) convertView.findViewById(R.id.row_sales_tv_amount_received);
viewHolder.tvStatus = (TextView) convertView.findViewById(R.id.row_sales_tv_status);
viewHolder.tvReceiptCode = (TextView) convertView.findViewById(R.id.row_sales_tv_receipt_code);
viewHolder.btnEdit = (ImageButton) convertView.findViewById(R.id.row_sales_btn_edit);
viewHolder.btnRemove = (ImageButton) convertView.findViewById(R.id.row_sales_btn_trash);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data from the data object via the viewHolder object
// into the template view.
if (altColour == 0) {
viewHolder.container.setBackgroundColor(Color.parseColor("#FFFFFF"));
altColour = 1;
} else {
viewHolder.container.setBackgroundColor(Color.parseColor("#EFEFEF"));
altColour = 0;
}
viewHolder.tvId.setText(String.valueOf(sale.getId()));
viewHolder.tvDate.setText(sale.getDate());
viewHolder.tvDriver.setText(sale.getDriver());
double totalTripsAmount = 0;
for(int c = 0; c < sale.getTrips().length(); c++) {
try {
totalTripsAmount += sale.getTrips().getJSONObject(c).getDouble("trip_amount");
} catch (JSONException e) {
e.printStackTrace();
}
}
viewHolder.tvNoOfTrips.setText("GHS "+totalTripsAmount);
double totalExpenditureAmount = 0;
for(int c = 0; c < sale.getExpenditure().length(); c++) {
try {
totalExpenditureAmount += sale.getExpenditure().getJSONObject(c).getDouble("amount");
} catch (JSONException e) {
e.printStackTrace();
}
}
viewHolder.tvTotalExpenditure.setText("GHS "+totalExpenditureAmount);
viewHolder.tvTotal.setText("GHS "+sale.getTotal());
viewHolder.tvAmountReceived.setText("GHS "+sale.getAmountReceived());
viewHolder.tvStatus.setText(sale.getIsPending() == 1 ? "Pending" : "Complete");
viewHolder.tvReceiptCode.setText(sale.getReceiptCode());
viewHolder.btnEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent editSaleIntent = new Intent(getContext(), EditSaleActivity.class);
editSaleIntent.putExtra("sale", sale.toJson().toString());
((Activity) getContext()).startActivityForResult(editSaleIntent, 800);
}
});
viewHolder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int pos = new Integer(getPosition(sale));
removeSale(pos);
}
});
// Return the completed view to render on screen
return convertView;
}
private void removeSale(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Confirm");
builder.setMessage("Are you sure you want to delete?");
builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//Log.i("btnYes", "works");
SalesRequest salesRequest = new SalesRequest(getContext());
remove(getItem(position));
notifyDataSetChanged();
salesRequest.remove(getItem(position).getId(), mTrashOnSuccessListener, mTrashOnErrorListener);
}
});
builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do nothing
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private Response.Listener<JSONObject> mTrashOnSuccessListener = new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//
}
};
Response.ErrorListener mTrashOnErrorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Utils.showNetworkResponse(getContext(), error);
}
};
}
Now my issue is when I click the delete or edit button for any item being displayed it always picks the position or id of the last item being display in the listview.
For example if I wanted to delete the second item in the listview with a position of 1 it would pick the last item being displayed with a position of 10.
I've tried soo many things and made soo many changes but nothing has worked so far, this is my final code.
You can add a tag in a button. Tag the current position to the button when getView method is called every time. When the button is clicked get the tage of the button and it will return the updated value/position of the button. And do what you want to do with that current position in call back of that button click. Hope that helps
Adding more information
you have this line of code
viewHolder.btnEdit
this is the edit button . Now you should add a tag to this button using below code. You need to use below code after else clause of Viewholder object initialization.
viewHolder.btnEdit.setTag(position);
And in call back of onclick use below code
button.getTag()
Set the position of each ViewHolder object as a tag to the buttons and retrieve it using getTag() when they are clicked.
Something like this needs to be done:
viewHolder.btnEdit.setTag(position)
And inside onClick(), retrieve the position as viewHolder.btnEdit.getTag()
For using the viewHolder object inside onClick(), it must be declared final so you can copy the object as final ViewHolder finalHolder = viewHolder and do the above with finalHolder object
Try to set the tag for the buttons at each position in the following way, so that when ever a button is clicked you can get back the position using the tag.
#NonNull
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View getView(final int position, View convertView, #NonNull ViewGroup parent) {
// Get the data item for this position
sale = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// If there's no view to re-use, inflate a brand new view for row
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_sales, parent, false);
//Fetch other views here .....
viewHolder.btnEdit = (ImageButton) convertView.findViewById(R.id.row_sales_btn_edit);
viewHolder.btnRemove = (ImageButton) convertView.findViewById(R.id.row_sales_btn_trash);
// Cache the viewHolder object inside the fresh view
convertView.setTag(viewHolder);
} else {
// View is being recycled, retrieve the viewHolder object from tag
viewHolder = (ViewHolder) convertView.getTag();
}
//Setting the position as the tag for both buttons
viewHolder.btnRemove.setTag(position);
viewHolder.btnEdit.setTag(position);
Now in click listener..
viewHolder.btnRemove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Remove the below line
int pos = new Integer(getPosition(sale));
//Use this
int pos = (int)v.getTag();
removeSale(pos);
}
});
Hope, am helpful.
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (fileDataVo.isPdf()) {
Intent intent = new Intent(context, PdfActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
} else if (fileDataVo.isExcel()) {
Intent intent = new Intent(context, ExcelFileActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
}
else if (fileDataVo.isPpt()) {
Intent intent = new Intent(context, PptActivity.class);
intent.putExtra("position", position);
context.startActivity(intent);
}
}

Last value is incremented / decremented while click previous list item in ListView

I am developing an app which is similar to Shopping cart. Here I am using BaseAdapter to populate cart data. There are,
3 ListItems:
Row 1
Row 2
Row 3
When I click increase / decrease button of Row 1 / Row 2, cart item count of the Row 3 is increased / decreased respectively. And I need to calculate TotalSum of the all the product.
Here is my code. Please check it and help me to fix it.
Thanks in advance.
public class CartCountBaseAdapter extends BaseAdapter implements View.OnClickListener {
Context con;
ArrayList<HashMap<String, String>> ArproductMap;
String MYFRAGMENT;
ViewHolder viewHolder;
public CartCountBaseAdapter(Context context, ArrayList<HashMap<String, String>> arproductMap, String myfragment) {
this.con = context;
this.ArproductMap = arproductMap;
this.MYFRAGMENT = myfragment;
}
#Override
public int getCount() {
return ArproductMap.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder = new ViewHolder();
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) con.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.cart_list_item, null);
}
viewHolder.addTowish = (Button) convertView.findViewById(R.id.addTowish);
viewHolder.remove = (Button) convertView.findViewById(R.id.remove);
viewHolder.cartProduct = (TextView) convertView.findViewById(R.id.cartProduct);
viewHolder.cartQuantity = (TextView) convertView.findViewById(R.id.cartQuantity);
viewHolder.cartCount = (TextView) convertView.findViewById(R.id.cartCount);
viewHolder.cartPrice = (TextView) convertView.findViewById(R.id.cartPrice);
viewHolder.cartPriceDum = (TextView) convertView.findViewById(R.id.cartPriceDum);
viewHolder.ivDecrease = (ImageView) convertView.findViewById(R.id.ivDecrease);
viewHolder.ivIncrease = (ImageView) convertView.findViewById(R.id.ivIncrease);
viewHolder.cardView = (CardView) convertView.findViewById(R.id.cardlist_item);
if (MYFRAGMENT == "CheckOutFragment") {
viewHolder.addTowish = (Button) convertView.findViewById(R.id.addTowish);
viewHolder.remove = (Button) convertView.findViewById(R.id.remove);
viewHolder.addTowish.setVisibility(View.GONE);
viewHolder.remove.setVisibility(View.GONE);
viewHolder.cardView.setCardElevation(0);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams
(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
viewHolder.cardView.setLayoutParams(layoutParams);
}
int CARTPRICE = Integer.parseInt(ArproductMap.get(position).get("Hash_Cart_Price"));
viewHolder.cartProduct.setText(ArproductMap.get(position).get("Hash_Product_Name"));
viewHolder.cartQuantity.setText(ArproductMap.get(position).get("Hash_Cart_Category"));
viewHolder.cartCount.setText(ArproductMap.get(position).get("Hash_Cart_Quantity"));
viewHolder.cartPrice.setText(String.valueOf(CARTPRICE));
viewHolder.cartPriceDum.setText(String.valueOf(CARTPRICE));
viewHolder.Quantity = Integer.parseInt(viewHolder.cartCount.getText().toString());
viewHolder.addTowish.setOnClickListener(this);
viewHolder.remove.setOnClickListener(this);
viewHolder.ivDecrease.setTag(position);
viewHolder.ivIncrease.setTag(position);
viewHolder.ivDecrease.setOnClickListener(this);
viewHolder.ivIncrease.setOnClickListener(this);
return convertView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivIncrease:
viewHolder.Quantity++;
viewHolder.cartCount.setText(viewHolder.Quantity + "");
break;
case R.id.ivDecrease:
viewHolder.Quantity--;
if (viewHolder.Quantity <= 0) {
viewHolder.Quantity = 0;
viewHolder.cartCount.setText(viewHolder.Quantity + "");
} else {
viewHolder.cartCount.setText(viewHolder.Quantity + "");
}
break;
}
}
static class ViewHolder {
TextView cartProduct,
cartQuantity,
cartCount,
cartPrice,
cartPriceDum;
int Quantity;
ImageView ivDecrease;
ImageView ivIncrease;
Button addTowish;
Button remove;
CardView cardView;
}
}
You should never put any data in your view holder. Put data in any data type like Arraylist. then get the position in your on click and based on that position modify the data
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.ivIncrease:
int position = (int) v.getTag
datalist[position]++;
viewHolder.cartCount.setText(viewHolder.Quantity + "");
break;
case R.id.ivDecrease:
int position = (int) v.getTag
datalist[position]++;
if (viewHolder.Quantity <= 0) {
viewHolder.Quantity = 0;
viewHolder.cartCount.setText(viewHolder.Quantity + "");
} else {
viewHolder.cartCount.setText(viewHolder.Quantity + "");
}
break;
}
}
Also if you want to make any view related changes put your onclick interface inside viewholder class then use this object

list view repeating values several times and repeating check box selection every after 6th value

I am using a custom list view base adapter. while passing values to the adapter its repeating values. and in viewholder I am using a checkbox, while selecting that checkbox list auto select the every 6th checkbox after that.
here is my adapter full code.
public class CallLogAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater li;
List<CallLogInfo> callData;
HashMap<Integer, Integer> map = new HashMap<Integer, Integer>();
Context context;
static Boolean checkboxstate[];
ArrayList<MultipleSelectedContact> mainDataList;
int i = 0;
public CallLogAdapter(Activity activity, List<CallLogInfo> callData, ArrayList<MultipleSelectedContact> selectedContacts) {
this.activity = activity;
this.callData = callData;
this.mainDataList = selectedContacts;
context = activity;
checkboxstate = new Boolean[callData.size()];
}
// View lookup cache
private static class ViewHolder {
TextView phoneNo, date, addComment, duration;
CheckBox checkBox;
CardView card;
ImageView callTypeImage;
int count;
}
#Override
public int getCount() {
if (callData != null && callData.size() != 0) {
return callData.size();
}
return 0;
}
#Override
public Object getItem(int position) {
return callData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v = convertView;
final ViewHolder viewHolder; // view lookup cache stored in tag
if (v == null) {
li = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.single_card, parent, false);
viewHolder = new ViewHolder();
viewHolder.card = (CardView) v.findViewById(R.id.card_view);
viewHolder.callTypeImage = (ImageView) v.findViewById(R.id.callTypeImage);
viewHolder.phoneNo = (TextView) v.findViewById(R.id.phoneNoText);
viewHolder.date = (TextView) v.findViewById(R.id.dateText);
viewHolder.duration = (TextView) v.findViewById(R.id.callDurationText);
viewHolder.checkBox = (CheckBox) v.findViewById(R.id.checkBox);
viewHolder.addComment = (TextView) v.findViewById(R.id.addCommentText);
v.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) v.getTag();
}
viewHolder.count = position;
final CallLogInfo Info;
Info = callData.get(position);
switch (Info.callType) {
case "Outgoing":
viewHolder.callTypeImage.setImageResource(R.mipmap.up_arrow);
break;
case "Incoming":
viewHolder.callTypeImage.setImageResource(R.mipmap.down_arrow);
break;
case "Missed":
viewHolder.callTypeImage.setImageResource(R.mipmap.miss_arrow);
break;
}
viewHolder.phoneNo.setText(Info.phoneNo);
viewHolder.date.setText(Info.date);
viewHolder.duration.setText(Info.duration);
viewHolder.addComment.setTag(viewHolder.count);
viewHolder.checkBox.setTag(viewHolder.count);
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewHolder.checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
if (((CheckBox) view).isChecked()) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = true;
mainDataList.add(i, new MultipleSelectedContact());
mainDataList.get(i).phoneNoS = Info.phoneNo;
mainDataList.get(i).setIsSelected(viewHolder.checkBox.isSelected());
map.put(((int) viewHolder.checkBox.getTag()), i);
i++;
view.setSelected(true);
} else {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
mainDataList.remove(map.get(((int) viewHolder.checkBox.getTag())));
view.setSelected(false);
}
}
});
viewHolder.addComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.activity_add_comment);
dialog.setTitle("Add Comment Here..");
// set the custom dialog components - text, image and button
final EditText text = (EditText) dialog.findViewById(R.id.messageEditText);
Button dialogButton = (Button) dialog.findViewById(R.id.messageAddButton);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String comment = text.getText().toString();
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "CallLogDb", null);
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
DaoSession session = daoMaster.newSession();
CallCommentsDetailDao callCommentDao = session.getCallCommentsDetailDao();
CallCommentsDetail commentInfo = new CallCommentsDetail();
commentInfo.setCommentId(position);
commentInfo.setComments(comment);
callCommentDao.insertOrReplace(commentInfo);
session.clear();
db.close();
dialog.dismiss();
}
});
dialog.show();
}
});
viewHolder.card.setTag(position);
viewHolder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, MessageContentActivity.class);
intent.putExtra("callDetails", Info);
context.startActivity(intent);
}
});
return v;
}
}
Here in the code where I am using ((int) viewHolder.checkBox.getTag()) . I tried using position also. but still its not working..
can anyone please help me to find out where I am going wrong
Set your check box state on getView
if (checkboxstate[((int) viewHolder.checkBox.getTag())] == null) {
checkboxstate[((int) viewHolder.checkBox.getTag())] = false;
}
viewholder.checkbox.setChecked(checkboxstate[((int)viewHolder.checkBox.getTag())]);
You can use a SparseBooleanArray to save the states of the checkbox instead of setting it as tag and you are not setting the checkbox state in getView() method like
viewholder.checkbox.setChecked(booleanArray.valueAt(position))
then toggle the state on OnClick() something like
booleanArray.put(position,!booleanArray.valueAt(position));
notifyDataSetChanged();
Also listItemClick won't work properly if the list row contains checkboxes or buttons.Use Recyclerview for better customisation and performance.
Sample Implementation of recyclerview

how to update the text on click of listview items in adapter

enter image description hereI want that if user clicks + and - button then action performed to that particular list item in listview. In my program when I clicked first item's button then value increment and decrement also but when another items button clicked that time it consider previous items value and incerement and decrement action performed on that value .I want that each item perform their seperately. I don't know how to implement this.
Here my code:
public static class ViewHolder {
TextView tv_qty;
}
public class ProductAdapter extends ArrayAdapter<Product> {
ImageLoader imageLoader;
public ProductAdapter(Context context, int resource) {
super(context, resource);
imageLoader = new ImageLoader(context);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Product product = getItem(position);
// Product product=ge
View view;
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
view = layoutInflater.inflate(R.layout.product_row, null);
} else {
view = convertView;
}
final ViewHolder viewHolder = new ViewHolder();
tv_row_product_name = (TextView) view.findViewById(R.id.pname);
tv_row_product_rate = (TextView) view.findViewById(R.id.price);
tv_row_product_qty = (TextView) view.findViewById(R.id.productqty);
viewHolder. tv_qty = (TextView) view.findViewById(R.id.userqty);
tv_value = (TextView) findViewById(R.id.textView_value);
tv_totalprice = (TextView) findViewById(R.id.textview_totalprice);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
Log.d(Config.tag, "url : " + "uploads/product/" + product.image1);
Picasso.with(ListViewProduct.this)
.load("http://www.sureshkirana.com/uploads/product/" + product.image1)
.into(imageView);
imgbtnp = (ImageButton) view.findViewById(R.id.imageButton2);
imgbtnm = (ImageButton) view.findViewById(R.id.imageButton);
imgbtnp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count++;
viewHolder. tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
imgbtnm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (count > 0)
count--;
viewHolder.tv_qty.setText(String.valueOf(count));
notifyDataSetChanged();
}
});
view.setTag(viewHolder);
tv_row_product_name[enter image description here][1].setText(product.productTitle);
tv_row_product_rate.setText("Rs. " + product.productPrice + "/-");
tv_row_product_qty.setText(product.quantity + "kg");
tv_totalprice.setText("Rs." + product.product_amount);
return view;
}
}
}
You cannot use a single variable for this purpose. Set the count as tag to your list item viewHolder.tv_qty.setTag(count);
and retrieve the value like viewHolder.tv_qty.getTag();.
on clicking on the + or - sign get the position of the clicked item in getView and get the product object at that position and modify with the new values and again put the modified object inside same list at same position and call notifyDatasetChanged() . Hope it helps.
Using Interface you can solve this problem. You need to update your object and then refresh you list adapter using notifyDataSetChanged().
Custom Adapter
public interface QuantityClickListener {
void onIncrementClickListner(int position);
void onDecrementClickListner(int position);
}
/*
* (non-Javadoc)
*
* #see android.widget.ArrayAdapter#getView(int, android.view.View,
* android.view.ViewGroup)
*/
#SuppressLint("InflateParams")
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ListViewWrapper wrapper = null;
LayoutInflater inflater = LayoutInflater.from(mContext);
if (null == convertView) {
convertView = inflater.inflate(R.layout.custom_list_item, null);
wrapper = new ListViewWrapper(convertView);
convertView.setTag(wrapper);
} else {
wrapper = (ListViewWrapper) convertView.getTag();
}
// Schedule schedule = objects.get(position);
Products product = mProducts.get(position);
if (null != product) {
wrapper.getTxtQuantity().setText("" + product.quantity);
wrapper.getNegativeBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onDecrementClickListner(position);
}
});
wrapper.getPositiveBtn().setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
quantityClickListener.onIncrementClickListner(position);
}
});
}
return convertView;
}
Activity
/**
* Initialize UI elements
*/
private void initialize() {
listView = (ListView) findViewById(R.id.listview);
dummyData();
adapters = new CustomAdapters(this, 0, products);
adapters.setQuantityClickListener(quantityClickListener);
listView.setAdapter(adapters);
}
private QuantityClickListener quantityClickListener = new QuantityClickListener() {
#Override
public void onIncrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
product.quantity++;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
#Override
public void onDecrementClickListner(int position) {
if (null != products && products.size() > 0) {
Products product = products.get(position);
if (product.quantity > 0) {
product.quantity--;
product.totalPrice = product.quantity * product.price;
adapters.notifyDataSetChanged();
}
}
}
};

Categories

Resources