I have a custom listview that contains two buttons on each line, what I am struggling with is the Listener for these buttons. My Listview is contained within a AlertDialog and this is the code I have
#Override
public void displayUnders(List<UndersLM> ulm) {
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
ArrayList<UndersLM> undersreturn = new ArrayList<UndersLM>();
final ListView L = new ListView(ctx);
final UndersLM y = new UndersLM();
for (UndersLM aulm : ulm) {
final UndersLM s = new UndersLM();
s.set_id(aulm.get_id());
s.set_cartonid(aulm.get_cartonid());
s.set_sku(aulm.get_sku());
s.set_sentqty(aulm.get_sentqty());
s.set_scannedqty(aulm.get_scannedqty());
undersreturn.add(s);
}
uadaptor = new Unders(ctx, undersreturn);
L.setAdapter(uadaptor);
builder.setView(L);
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
builder.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
L.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object rid = parent.getAdapter().getItem(position);
}
});
AlertDialog d;
d = builder.create();
d.show();
}
As you can see I have tried the ItemClickListerner on the ListView its self, and the itemSelected on the AlertDialog.
What am I missing? Neither one of these ever hits the Object rid = parent.... lines
EDIT - ACTUALLY IGNORE THIS - ITS CRAP!
Ok, worked it out.
You basically have to do this (as far as I can work out) in your Custom Adaptor, so in my case this worked:
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.unders, null);
holder = new ViewHolder();
holder.id = (TextView) vi.findViewById(R.id.id);
holder.cartonID = (TextView) vi.findViewById(R.id.cartonID);
holder.Sku = (TextView) vi.findViewById(R.id.Sku);
holder.Sent = (TextView) vi.findViewById(R.id.Sent);
holder.add = (Button) vi.findViewById(R.id.add);
holder.Scanned = (TextView) vi.findViewById(R.id.Scanned);
holder.subtract = (Button) vi.findViewById(R.id.subtract);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (Lines.size() < -0) {
holder.id.setText("No Unprocessed Deliveries");
} else {
tempValues = null;
tempValues = (UndersLM) Lines.get(position);
holder.id.setText(String.valueOf(tempValues.get_id()));
holder.cartonID.setText(String.valueOf(tempValues.get_cartonid())+ " | ");
holder.Sku.setText(String.valueOf(tempValues.get_sku()) + " | ");
holder.Sent.setText(String.valueOf(tempValues.get_sentqty()) + " | ");
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()));
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new underCorrections(ctx,true,tempValues.get_cartonid(),tempValues.get_sku()).execute();
holder.Scanned.setText(String.valueOf(tempValues.get_scannedqty()+1));
}
});
}
return vi;
}
Related
In my listview, when I long press row 1 it should change the amount of a textview in row 1. However I have a problem, when I try to change the amount of the specific row (example: row 1), the 5th row of the listview also changes. Also, when the listview is recycled, the textview returns to its old value. Been trying to solve this for a day already but to no luck.
Any help is appreciated!
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final 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.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}
try this. please add this two methods if not added
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
Add notifyDataSetChange on positive button click listener.
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
txAmt.setText(zzx);
holder.tx_status.setText(zzx);
holder.tx_amount.setText(zzx);
adapter.notifyDataSetChanged();
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
you should learn the listview lifecycle. however if you want to do that you have to change the item data from the datasource which in this case , its mData. and after updateting the item call notifyItemchanged() on adapter to apply the item in listview. the reason for after recycling you see the old data is that the list gets data from mData and you just updated the View. so instead of geting the viewholder. get item by position in longclick and after you updated the item just call notifyItemChanged(position);
First you missed }); in your code before mView.setTag(holder);, so your code will have compile issues which I think you should have seen.
Second, you should not call listView.setOnItemLongClickListener in getView. Because this will repeat many times depends on how many items visible in your screen.
Finally, you should update the data source, i.e.: mData in your code, with the latest data, and then call adapter.notifyDatasetChanged() to update the UI.
So your code should be something like below:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
TextView txAmt = view.findViewById(R.id.tx_amount);
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity.this);
alert.setTitle("Enter New Amount:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
input.setRawInputType(Configuration.KEYBOARD_12KEY);
alert.setView(input);
alert.setPositiveButton("enter", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String zzx = input.getText().toString();
// Remove codes below
// txAmt.setText(zzx);
// holder.tx_status.setText(zzx);
// holder.tx_amount.setText(zzx);
mData.get(position).setXXX(zzx); // call the setter of your data model
adapter.notifyDatasetChanged(); // call this will update the listview with the latest data
}
});
alert.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//Put actions for CANCEL button here, or leave in blank
}
});
alert.show();
return true;
}
});
public View getView(int i, View convertView, ViewGroup viewGroup) {
View mView = convertView;
String betid = mData.get(i).get("id");
final 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.checkBox = (CheckBox) mView.findViewById(R.id.checkmark);
holder.tx_status = (TextView) mView.findViewById(R.id.tx_status);
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.isChecked()) {
checked.add((Integer) holder.checkBox.getTag());
holder.tx_amount.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_number.setBackgroundColor(getResources().getColor(R.color.bluelim));
holder.tx_status.setBackgroundColor(getResources().getColor(R.color.bluelim));
} else {
holder.tx_amount.setBackgroundColor(Color.WHITE);
holder.tx_number.setBackgroundColor(Color.WHITE);
holder.tx_status.setBackgroundColor(Color.WHITE);
}
}
});
mView.setTag(holder);
holder.checkBox.setTag(i);
} else {
holder = (ViewHolder) mView.getTag();
((ViewHolder) mView.getTag()).checkBox.setTag(i);
}
if (betid != null) {
String betnumber = mData.get(i).get("betnumber");
String amountTarget = mData.get(i).get("betamount");
String status = mData.get(i).get("status");
holder.tx_amount.setText(amountTarget);
holder.tx_number.setText(betnumber);
holder.tx_status.setText(status);
}
ViewHolder holde2r = (ViewHolder) mView.getTag();
for (int k = 0; k < checked.size(); k++) {
if (checked.get(k) == i) {
holde2r.checkBox.setChecked(true);
} else if (checked.get(k) != i) {
holde2r.checkBox.setChecked(false);
}
}
return mView;
}
private class ViewHolder {
TextView tx_number;
TextView tx_amount;
TextView tx_status;
CheckBox checkBox;
}
}
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);
}
}
I've been trying to figure this out for about 2 weeks but no luck at all. I'm trying to add a confirmation message in my onClickListener by using AlertDialog, and the setPositiveButton of AlertDialog will be the one to do the things that I want to happen, but it messes up the int position value in getView . Instead of getting the position of the item I clicked on, it gets the position of the last item. I tried doing Toast message inside the onClick(NOT inside the AlertDialog) and it returns the proper position, but when I try to Toast message inside the AlertDialog it changes the position value. I stuck and don't how to make this work.
Here is my Adapter.Class
public class myOrderAdapter extends ArrayAdapter<myOrder> {
AlertDialog.Builder builder;
AlertDialog ad;
public class ViewHolder{
TextView tableNum;
TextView itemName;
TextView itemQuantity;
TextView custName;
Button btnStatus;
}
public myOrderAdapter(Context context, ArrayList<myOrder> orderList) {
super(context, 0,orderList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final myOrder orderList = getItem(position);
ViewHolder viewHolder;
viewHolder = new ViewHolder();
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout,parent,false);
viewHolder.tableNum = (TextView)convertView.findViewById(R.id.tableNum);
viewHolder.itemName = (TextView)convertView.findViewById(R.id.itemName);
viewHolder.custName = (TextView)convertView.findViewById(R.id.custName);
viewHolder.itemQuantity = (TextView)convertView.findViewById(R.id.itemQuantity);
viewHolder.btnStatus = (Button)convertView.findViewById(R.id.statusButton);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.tableNum.setText("Order for Table: "+orderList.getTable_id());
viewHolder.itemName.setText(orderList.getItem_name());
viewHolder.custName.setText("Customer Name: " + orderList.getCust_name());
viewHolder.itemQuantity.setText("QTY: " + orderList.getQuantity());
builder = new AlertDialog.Builder(Order.context);
builder.setTitle("Confirmation");
builder.setIcon(R.drawable.ic_confirm);
builder.setMessage("Is this Ready to Serve?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
ad = builder.create();
viewHolder.btnStatus.setText("Ready");
viewHolder.btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
ad.show();
}
});
return convertView;
}
}
NOTE :
I set the Toast message the same way as Button.onClickListener in the builder.setPositiveButton to check if the value changes, and yes it does change. Need some help and guidance, thank you.
The problem here is that you are creating the AlertDialog for every view created even to the last view(for the last item) which is the reason why you are getting the position to be the last index of your item list. Try something like below, this will only create the dialog when you click on the button from one of the view.
public class myOrderAdapter extends ArrayAdapter<myOrder> {
public class ViewHolder{
TextView tableNum;
TextView itemName;
TextView itemQuantity;
TextView custName;
Button btnStatus;
}
public myOrderAdapter(Context context, ArrayList<myOrder> orderList) {
super(context, 0,orderList);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final myOrder orderList = getItem(position);
ViewHolder viewHolder;
viewHolder = new ViewHolder();
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_layout,parent,false);
viewHolder.tableNum = (TextView)convertView.findViewById(R.id.tableNum);
viewHolder.itemName = (TextView)convertView.findViewById(R.id.itemName);
viewHolder.custName = (TextView)convertView.findViewById(R.id.custName);
viewHolder.itemQuantity = (TextView)convertView.findViewById(R.id.itemQuantity);
viewHolder.btnStatus = (Button)convertView.findViewById(R.id.statusButton);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder)convertView.getTag();
}
viewHolder.tableNum.setText("Order for Table: "+orderList.getTable_id());
viewHolder.itemName.setText(orderList.getItem_name());
viewHolder.custName.setText("Customer Name: " + orderList.getCust_name());
viewHolder.itemQuantity.setText("QTY: " + orderList.getQuantity());
viewHolder.btnStatus.setText("Ready");
viewHolder.btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position,Toast.LENGTH_SHORT).show();
createDialog(position);
}
});
return convertView;
}
private void createDialog(final int position) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("Confirmation " + position);
builder.setIcon(R.drawable.pencil);
builder.setMessage("Is this Ready to Serve? " + position);
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
Toast.makeText(getContext(),orderList.getOrder_id()+ "+" + orderList.getItem_name() + "+" + position, Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
}
}
Adapter Class:
public List<TSPDataModel> employeeData;
private Context mContext;
private LayoutInflater mInflater;
RadioGroup radiogroupbutton;
String[] data = {"Document not clear","Adress is not Visibile","Photo is not pasted","Signature is not Avilable"};
String value;
public TSPListDocumentadapter(Context context, int textViewResourceId,
List<TSPDataModel> objects)
{
this.employeeData = objects;
this.mContext = context;
mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.tspdocumentlistitem, null);
holder.relatvie1=(RelativeLayout)convertView.findViewById(R.id.relatvie1);
holder.txtName = (TextView) convertView.findViewById(R.id.textView1);
holder.accecpt = (ImageView) convertView.findViewById(R.id.imageButton);
holder.reject = (ImageView) convertView.findViewById(R.id.imageButton2);
holder.statustextview = (TextView) convertView.findViewById(R.id.statustextview);
holder.poaedittext=(TextView) convertView.findViewById(R.id.poieditext);
holder.poaedittext=(TextView)convertView.findViewById(R.id.poaedittext);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(employeeData.get(position).getName());
holder.poaedittext.setText(employeeData.get(position).getPoa());
holder.accecpt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.statustextview.setText("Accepted");
employeeData.get(position).setSelected(true);
employeeData.get(position).getOrderId();
holder.relatvie1.setBackgroundResource(R.color.acceptedcolor);
}
});
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog();
holder.statustextview.setText("Rejected");
employeeData.get(position).setSelected(false);
employeeData.get(position).setReasone(value);
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
return convertView;
}
static class ViewHolder {
TextView txtName;
ImageView reject;
ImageView accecpt;
TextView statustextview;
TextView poiedittext;
TextView poaedittext;
RelativeLayout relatvie1;
}
public int getCount() {
return employeeData.size();
}
public TSPDataModel getItem(int position) {
return employeeData.get(position);
}
public long getItemId(int position) {
return 0;
}
public void showdilog() {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
This Button click in my actvity class :
#Override
public void onClick(View view) {
if (view.getId() == R.id.button1) {
try {
List<TSPDataModel> empData = adapter.employeeData;
System.out.println("Total Size :" + empData.size());
for (TSPDataModel employeeModel : empData) {
if (employeeModel.isSelected()) {
Toast.makeText(TSPDocumentListActvity.this, employeeModel.getName(), Toast.LENGTH_LONG).show();
} else {
String Reasonse= employeeModel.getresonse() ;
Toast.makeText(TSPDocumentListActvity.this, "false" + employeeModel.getName(), Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
First i Print data in Listview then each list view item there is accept and reject Button is there when we click on accept then no alert will asked only reject button reason will ask which is come on listitem on popup i want to get that selected reason on Button click in actvity but i always get null value please help me where i am doing wrong
change your reject button and showDialog code to
holder.reject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showdilog(position);
holder.statustextview.setText("Rejected");
holder.relatvie1.setBackgroundResource(R.color.rejectcolor);
}
});
and showDualog to
public void showdilog(int list_position) {
final Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.layoutpopup);
radiogroupbutton = (RadioGroup) dialog.findViewById(R.id.radio_gp_day);
ListView listview = (ListView) dialog.findViewById(R.id.radio_slot_list);
Button setbutton = (Button) dialog.findViewById(R.id.setbutton);
List<String> list = new ArrayList<String>();
ArrayAdapter<String> myadpter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_single_choice, data);
for (int i = 0; i < data.length; i++) {
list.add(data[i]);
}
listview.setAdapter(myadpter);
listview.setItemsCanFocus(false);
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
value = data[position];
employeeData.get(list_position).setSelected(false);
employeeData.get(list_position).setReasone(value);
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
}
});
setbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(mContext, value, Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
I read many more realted to this problem but not getting more idea. After this, i am trying to post, here in this picture I have 3 items on list, I have 2 item click. So I want to delete these two checked item. But i am the newbie for android, So could not get more idea behind this.
Code
public class CountryList extends Activity implements OnClickListener,
OnItemClickListener {
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return tempCountry.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.bookmarks_list_item,
null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView
.findViewById(R.id.country);
holder.checkBox = (CheckedTextView) convertView
.findViewById(android.R.id.checkbox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtcnt.setText(country[position]);
return convertView;
}
static class ViewHolder {
TextView txtcnt;
CheckBox checkBox;
}}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bokmarksjoks);
try {
db = (new DatabaseHelper(this)).getWritableDatabase();
} catch (IOException e) {
e.printStackTrace();
}
lv = (ListView) findViewById(R.id.list);
btn_delete = (Button) findViewById(R.id.delete);
btn_delete.setOnClickListener(this);
checkbox = (CheckBox) findViewById(R.id.checkbox);
txtname= (TextView) findViewById(R.id.body);
String name= pref.getString("name", "");
country= name.split(",");
lv.setAdapter(new EfficientAdapter(this));
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setOnItemClickListener(this);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.delete:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder .setMessage("Are you Sure want to delete checked country ?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// how to remove country
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.setTitle("Delete Country");
alert.show();
case R.id.checkbox:
//What is the procedue in this section
default:
break;
}
}
public void onItemClick(AdapterView<?> pareant, View view, int position,
long id) {
try {
// I have trying this but could not proper output or only errors
SparseBooleanArray sp = lv.getCheckedItemPositions();
/*String str = "";
for (int i = 0; i < sp.size(); i++) {
str += country[sp.keyAt(i)] + ",";
}*/
} catch (Exception e) {
e.printStackTrace();
}}}
This is the only three country, actually, I have more then hundreds countries.
Delete items from tempCountry and then call adapter.notifyDataSetChanged().
Have a button on list and let it onclick feature in xml
like to get postion first
public void OnClickButton(View V){
final int postion = listView.getPositionForView(V);
System.out.println("postion selected is : "+postion);
Delete(postion);
}
public void Delete(int position){
if (adapter.getCount() > 0) {
//Log.d("largest no is",""+largestitemno);
//deleting the latest added by subtracting one 1
comment = (GenrricStoring) adapter.getItem(position);
//Log.d("Deleting item is: ",""+comment);
dbconnection.deleteComment(comment);
List<GenrricStoring> values = dbconnection.getAllComments();
//updating the content on the screen
this.adapter = new UserItemAdapter(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
}
else
{
int duration = Toast.LENGTH_SHORT;
//for showing nothing is left in the list
Toast toast = Toast.makeText(getApplicationContext(),"Db is empty", duration);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}