Iam working on a simple invoice app which invloes methods like selecting products. Im having the problem where i use custom adapter to listview to view my product details and since i use custom adapter listview onclicklistner is not working.
All i need is to close the alertdialog while i click and select a product from the listview.
I used customadapter to make listview dynamic.
Here is my code for alertdialog box,
public void selectProduct(View v) {
showProducts();
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
LayoutInflater inflater = getLayoutInflater();
View convertView = (View) inflater.inflate(R.layout.select_product_list, null);
alertDialog.setView(convertView);
ArrayList<String> categoryListReverce = reverse(categoryList);
categorySpinner = (Spinner) convertView.findViewById(R.id.spinner1);
ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.orderlist_spinner_row, categoryListReverce);
arrayAdapter.setDropDownViewResource(R.layout.orderlist_spinner_row);
categorySpinner.setAdapter(arrayAdapter);
categorySpinner.setOnItemSelectedListener((AdapterView.OnItemSelectedListener) this);
ListView lv = (ListView) convertView.findViewById(R.id.listView);
listAdapter = new CustomNewInvoiceAdapter(this, R.layout.batch_sales_list, new ArrayList<OrderListModel>());R.id.productprice});
lv.setAdapter(listAdapter);
textPartySearch = (EditText) convertView.findViewById(R.id.searchContainer);
textContactSearch = (EditText) convertView.findViewById(R.id.contactno);
footer = (LinearLayout) convertView.findViewById(R.id.footer1);
getCashPartyName = (TextView) convertView.findViewById(R.id.partyname);
getCashPartyContact = (TextView) convertView.findViewById(R.id.contactno);
submit = (Button) convertView.findViewById(R.id.submit);
final AlertDialog ad = alertDialog.show();
textPartySearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter2.getFilter()
.filter(textPartySearch.getText().toString());
}
});
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
}
});
footer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ad.dismiss();
}
});
}
And here is my customAdapter getView,
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
CustomNewInvoiceAdapter.Holder holder = null;
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
holder = new CustomNewInvoiceAdapter.Holder();
holder.pack = items.get(position);
if (items.get(position).getType().equals("header")) {
row = inflater.inflate(headerLayoutResourceId, parent, false);
holder.itemName = row.findViewById(R.id.productName);
holder.itemName.setText(String.valueOf(holder.pack.getItemName()));
row.setTag(holder);
} else {
row = inflater.inflate(itemLayoutResourceId, parent, false);
holder.itemCode = row.findViewById(R.id.itemCode);
holder.itemName = row.findViewById(R.id.productName);
holder.CostTxt = row.findViewById(R.id.ed_cost);
holder.ItemDis = row.findViewById(R.id.ed_ItemDis);
holder.unitBtn = row.findViewById(R.id.unitbtn);
holder.stockTxt = row.findViewById(R.id.stock);
clickUnitBtn(holder);
if(Constants.isPriceEdit){
holder.price = row.findViewById(R.id.productprice);
holder.price.setClickable(false);
holder.price.setFocusable(false);
holder.price.setCursorVisible(false);
}else {
holder.price = row.findViewById(R.id.productprice);
holder.price.setSelectAllOnFocus(true);
}
row.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
}
});
row.setTag(holder);
setupItem(holder);
}
return row;
}
And here is a screenshot for reference
enter image description here
Are you able to dismiss alert dialog on your footer click as given on your code?
Related
I have a listview containing items name and price i made my code so when i click on one item it displays its price in a small dialog box at the bottom of the screen but now when i click another item i want to add that item's price to the first one and so on..
Here is my code for now:
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.price);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
LayoutInflater inflater2 = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final Dialog mBottomSheetDialog = new Dialog(context, R.style.MaterialDialogSheet);
View content = inflater2.inflate(R.layout.activity_main2, null);
mBottomSheetDialog.setContentView(content);
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
final Dialog mBottomSheetDialog2 = new Dialog(context, R.style.MaterialDialogSheet);
final View content2 = inflater2.inflate(R.layout.smalldialog, null);
final TextView total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
total.setText(null);
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
total.setText(String.valueOf(last));
mBottomSheetDialog2.show();
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
}
});
return rowView;
}
I tried using boolean but it didn't go as well as i expected.
I will appreciate any help!
Is all of your code (the getView() method) within your ArrayAdapter class? If so, move you listener register out into your Activity, and then the listener needs only pull the required value from the selected item and append it to a property of your Activity class, and then raise the view to show the running total.
Android How to refresh or reload listview data and final totaling data that is total of the all price of the cart
check image i want the blue circle price add and show on the red circle and but if i delete or change quantity of product then also update the price in red circle
this is my code
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolderItem viewHolder;
if(convertView==null){
inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolderItem();
viewHolder.toptext = (TextView) convertView.findViewById(R.id.cartname);
viewHolder.prc = (TextView) convertView.findViewById(R.id.textView76);
viewHolder.shp = (TextView) convertView.findViewById(R.id.textView77);
viewHolder.subtotal = (TextView) convertView.findViewById(R.id.textView79);
//viewHolder.textView80 = (TextView) convertView.findViewById(R.id.textView80);
viewHolder.img = (ImageView) convertView.findViewById(R.id.imageView7);
viewHolder.imageView2 = (ImageView) convertView.findViewById(R.id.imageView2);
viewHolder.spinner = (Spinner)convertView.findViewById(R.id.spinner);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolderItem) convertView.getTag();
}
final CartResponse response = getItem(position);
int subtotal1=0;
mydb = new DBHelper(getContext());
if(response != null) {
/* ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(),
R.array.qty, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
viewHolder.spinner.setAdapter(adapter);*/
viewHolder.spinner.setSelection(Integer.parseInt(response.getQty())-1);
viewHolder.spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
response.setQty(viewHolder.spinner.getSelectedItem()+"");
if(mydb.updateContact(Integer.parseInt(response.getid()),response.getPname(),Integer.parseInt(response.getPrice()),Integer.parseInt(response.getCutPrice()),++pos,Integer.parseInt(response.getShipping()),response.getPhoto())){
Log.d("key",""+response.getQty());
updateResults();
//Toast.makeText(getContext(),"updated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
});
viewHolder.imageView2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mydb.deleteContact(Integer.parseInt(response.getid()));
//int index =callback.indexOf(response.getid());
callback.remove(response);
updateResults();
Toast.makeText(getContext(),"Remove", Toast.LENGTH_SHORT).show();
}
});
int tamount=0,tship=0,gt=0;
tamount=tamount+(Integer.parseInt(response.getPrice())* Integer.parseInt(response.getQty()));
tship=tship+(Integer.parseInt(response.getShipping())* Integer.parseInt(response.getQty()));
gt=tamount+tship;
subtotal1=Integer.parseInt(response.getPrice()) + Integer.parseInt(response.getShipping());
viewHolder.toptext.setText(response.getPname());
viewHolder.prc.setText("Rs."+tamount);
//Log.d("key",""+response.getPrice());
viewHolder.shp.setText("Rs."+tship);
viewHolder.subtotal.setText("Sub total Rs."+gt);
Picasso.get().load("https://www.exmple.com/photos/"+response.getPhoto()+".png").placeholder(R.drawable.placeholder).memoryPolicy(MemoryPolicy.NO_CACHE).networkPolicy(NetworkPolicy.NO_CACHE).into(viewHolder.img);
}
Cart class
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_cart, container, false);
mydb = new DBHelper(getContext());
cart_list = mydb.getAllCotacts();
cartitems=cart_list.size();
int amount=0,shping=0;
for(int i=0;i<cartitems;i++){
int price = (Integer.parseInt(cart_list.get(i).getPrice())*Integer.parseInt(cart_list.get(i).getQty()));
int shp=(Integer.parseInt(cart_list.get(i).getShipping())*Integer.parseInt(cart_list.get(i).getQty()));
amount=amount+price;
shping=shping+shp;
}
TextView cout=(TextView)view.findViewById(R.id.textView75);
TextView gprice=(TextView)view.findViewById(R.id.textView87);
TextView gship=(TextView)view.findViewById(R.id.textView88);
gprice.setText("Rs."+amount);
gship.setText("Rs."+shping);
if(cartitems>0){
cout.setText("Your Cart Item");
}else{
cout.setText("Shopping Cart is Empty");
}
final CartAdapter adapter = new CartAdapter(getContext(), R.layout.cart_item, cart_list);
final ListView order_list = (ListView)view.findViewById(R.id.cartlist);
order_list.setAdapter(adapter);
adapter.notifyDataSetChanged();
order_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
adapter.notifyDataSetChanged();
//mydb.deleteContact(cart_list.get(position).getid());
//Log.d("key",""+cart_list.get(position).getQty());
//cart_list.get(position).getid();
}});
return view;
}
I created an imageviewer app. Its working fine but when I select a gridview item to delete it, it stops working. On selecting the item, delete button appears . On clicking the delete button ,an alert dialog appears asking for confirmation.I want the file to get deleted after cliking the YES button. But it does not happen. Instead it throws an indexoutofbounds exception. How can I delete selected file succesfully ?
PhotosActivity.java
import static com.example.dell_1.myapp3.ImageViewer.ImageGallery.al_images;
public class PhotosActivity extends AppCompatActivity {
int int_position;
private GridView gridView;
GridViewAdapter adapter;
ArrayList<Model_images> al_menu = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
gridView = (GridView) findViewById(android.R.id.list);
int_position = getIntent().getIntExtra("value", 0);
adapter = new GridViewAdapter(this, al_images, int_position);
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String abc = "file://" + al_images.get(int_position).getAl_imagepath().get(position);
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
i.putExtra("folderPosition", int_position);
i.putExtra("abc", abc);
startActivity(i);
}
});
gridView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
for (int j = 0; j < parent.getChildCount(); j++)
parent.getChildAt(j).setBackgroundColor(Color.TRANSPARENT);
// change the background color of the selected element
view.setBackgroundColor(Color.LTGRAY);
button1.setVisibility(View.VISIBLE);
button2.setVisibility(View.VISIBLE);
button3.setVisibility(View.VISIBLE);
button4.setVisibility(View.VISIBLE);
button5.setVisibility(View.VISIBLE);
button3.setOnClickListener(
new View.OnClickListener() {
public void onClick(View view) {
AlertDialog.Builder builder1 = new AlertDialog.Builder(PhotosActivity.this);
builder1.setMessage("Are you sure you want to delete it ?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
File file = new File( al_menu.get(int_position).getAl_imagepath().get(position));
file.delete();
al_menu.remove(position);
adapter.notifyDataSetChanged();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
});
return true;
}
});
}
}
ImageGallery.java:
public class ImageGallery extends AppCompatActivity {
public static ArrayList<Model_images> al_images = new ArrayList<>();
boolean boolean_folder;
Adapter_PhotosFolder obj_adapter;
GridView gv_folder;
private static final int REQUEST_PERMISSIONS = 100;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
gv_folder = (GridView) findViewById(android.R.id.list);
final ImageButton button1 = (ImageButton) findViewById(R.id.button1);
final ImageButton button2 = (ImageButton) findViewById(R.id.button2);
final ImageButton button3 = (ImageButton) findViewById(R.id.button3);
final ImageButton button4 = (ImageButton) findViewById(R.id.button4);
final ImageButton button5 = (ImageButton) findViewById(R.id.button5);
button1.setVisibility(View.GONE);
button2.setVisibility(View.GONE);
button3.setVisibility(View.GONE);
button4.setVisibility(View.GONE);
button5.setVisibility(View.GONE);
gv_folder.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent = new Intent(getApplicationContext(), PhotosActivity.class);
intent.putExtra("value",i);
startActivity(intent);
}
});
GridViewAdapter.java:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu = new ArrayList<>();
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
this.al_menu = al_menu;
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
LOGCAT:
10-20 17:27:02.769 24402-24402/com.example.dell_1.Myapp3 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dell_1.Myapp3, PID: 24402
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.get(ArrayList.java:411)
at com.example.dell_1.myapp3.ImageViewer.PhotosActivity$2$1$1.onClick(PhotosActivity.java:85)
at android.support.v7.app.AlertController$ButtonHandler.handleMessage(AlertController.java:161)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Based on your code, I don't see where the ArrayList al_menu is ever loaded with data. So when your onClick executes and attempts to get item at index 0, you get an IndexOutOfBoundsException exception. Looks like you for got to provide it with default values. Also inside of GridViewAdapter you the declare and instantiate al_menu at the top of the file and then overwrite it inside of the constructor. That is unnecessary and causing an extra object to be used and thrown away and doesn't protect against a NullPointerException later in the adapter because null could be passed into the GridViewAdapter' constructor and you don't check to make sure of that. I recommend adding a condition that checks if the passed in ArrayList is not null and add the values to your ArrayList using a for loop or even removed the instantiation line from the top of the file and do it in the GridViewAdapter's constructor and use in the ArrayList argument as a parameter if it isn't null as parameter when you instantiate your al_menu.
Example:
public class GridViewAdapter extends ArrayAdapter<Model_images> {
Context context;
ViewHolder viewHolder;
ArrayList<Model_images> al_menu;
int int_position;
public GridViewAdapter(Context context, ArrayList<Model_images> al_menu,int int_position) {
super(context, R.layout.activity_adapter__photos_folder, al_menu);
if(al_menu != null) {
this.al_menu = new ArrayList(al_menu);
}
this.context = context;
this.int_position = int_position;
}
#Override
public int getCount() {
Log.e("ADAPTER LIST SIZE", al_menu.get(int_position).getAl_imagepath().size() + "");
return al_menu.get(int_position).getAl_imagepath().size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getViewTypeCount() {
if (al_menu.get(int_position).getAl_imagepath().size() > 0) {
return al_menu.get(int_position).getAl_imagepath().size();
} else {
return 1;
}
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_adapter__photos_folder, parent, false);
viewHolder.tv_foldern = (TextView) convertView.findViewById(R.id.tv_folder);
viewHolder.tv_foldersize = (TextView) convertView.findViewById(R.id.tv_folder2);
viewHolder.iv_image = (ImageView) convertView.findViewById(R.id.iv_image);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_foldern.setVisibility(View.GONE);
viewHolder.tv_foldersize.setVisibility(View.GONE);
Glide.with(context).load("file://" + al_menu.get(int_position).getAl_imagepath().get(position))
.diskCacheStrategy(DiskCacheStrategy.NONE)
.skipMemoryCache(true)
.into(viewHolder.iv_image);
return convertView;
}
private static class ViewHolder {
TextView tv_foldern, tv_foldersize;
ImageView iv_image;
}
}
This question already has an answer here:
Button inside SimpleCursorAdapter
(1 answer)
Closed 5 years ago.
I'm fresh n funky in android dev. I start learning and got stoped by clickable button in listview!
`public class Test2 extends AppCompatActivity {
private static final String TAG = "Test2";
Button btnEdytuj;
DatabaseHelper myDb;
SimpleCursorAdapter dataAdapter;`
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test2);
myDb = new DatabaseHelper(this);
displayList();
}
private void displayList() {
Cursor cursor = myDb.getAllData();
String from[] = new String[]{myDb.COL_ID, myDb.COL_NAZWA, myDb.COL_LAT, myDb.COL_LON};
int to[] = new int[]{R.id.textView10, R.id.textView1, R.id.textView2, R.id.textView3};
dataAdapter = new SimpleCursorAdapter(this, R.layout.row_item_edit, cursor, from, to, 0);
ListView lv = (ListView) findViewById(R.id.listViewId);
lv.setAdapter(dataAdapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
btnEdytuj = (Button) view.findViewById(R.id.buttonEE);
btnEdytuj.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Do something
Intent intent = new Intent(Test2.this,Edytuj.class);
startActivity(intent);`
And my wish is to open new activity from list by intent trigger by pressing a row or a button and passing an id to handle editing.
I have found an error maybe it will helps to figure it out:
android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
in your list adapter do this :
this for get view function :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_note, null);
btnEdytuj = (Button) convertView.findViewById(R.id.buttonEE);
btnEdytuj.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
// Do something
}
});
}
return convertView;
}
this other for bind view:
#Override
public void bindView(View view, Context context, Cursor cursor){
int row_id = cursor.get('_id'); //Your row id (might need to replace)
Button button = (Button) view.findViewById(R.id.buttonEE);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//ADD STUFF HERE you know which row is clicked. and which button
}
});
}
Here you go :
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//Write your code here
}
});
Hope this helps.
You have to put the button onClick method inside Adapter class.
As you have used SimpleCursorAdapter, use button-inside-simplecursoradapter for reference.
Kindly write following code in your activity class.
MainActivity.java
ArrayList<MobileData> searchResults = getMobileData();
final ListView lv1 = (ListView) findViewById(R.id.ListView01);
lv1.setAdapter(new MobileAdapter(this, searchResults));
Add all list item by using adapter class and also add button event in adaptaer class.
MobileAdapter.java
public class MobileAdapter extends BaseAdapter {
private static ArrayList<MobileData> searchArrayList;
private LayoutInflater mInflater;
private Context context;
MobilezonDAO dao;
public MobileAdapter(Context context, ArrayList<MobileData> results) {
this.context = context;
searchArrayList = results;
mInflater = LayoutInflater.from(context);
dao = new MobilezonDAO(this.context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mobile_row_view, null);
holder = new ViewHolder();
holder.mobileImage = (ImageView) convertView.findViewById(R.id.mobileImage);
holder.mobileName = (TextView) convertView.findViewById(R.id.mobileName);
holder.mobilePrice = (TextView) convertView.findViewById(R.id.mobilePrice);
holder.mobileBrand = (TextView) convertView.findViewById(R.id.mobileBrand);
holder.viewDetails = (Button) convertView.findViewById(R.id.viewDetails);
holder.addToCart = (Button) convertView.findViewById(R.id.addToCart);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.mobileImage.setImageBitmap(searchArrayList.get(position).getMobileImage());
holder.mobileName.setText(searchArrayList.get(position).getMobileName());
holder.mobilePrice.setText("Price: $"+searchArrayList.get(position).getMobilePrice());
holder.mobileBrand.setText("Brand: "+searchArrayList.get(position).getMobileBrand());
holder.viewDetails.setBackgroundResource(R.drawable.view_details);
holder.viewDetails.setId(position);
holder.addToCart.setBackgroundResource(R.drawable.addtocart);
holder.viewDetails.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MobileData mobileData = searchArrayList.get(holder.viewDetails.getId());
Intent intent= new Intent(context, MobileViewDetailsActivity.class);
intent.putExtra("ModelNumber", mobileData.getModelNumber());
context.startActivity(intent);
}
});
holder.addToCart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MobileData mobileData = searchArrayList.get(holder.viewDetails.getId());
CartData cartData = new CartData();
cartData.setUsername(emailid);
cartData.setModelNumber(mobileData.getModelNumber());
cartData.setPrice(mobileData.getMobilePrice());
cartData.setQuantity("1");
CartData tempCartData = dao.searchParticularCartData(cartData.getUsername(), cartData.getModelNumber());
if(tempCartData!=null && tempCartData.getQuantity()!=null && Integer.valueOf(tempCartData.getQuantity())>0){
Snackbar.make(view, "Selected Mobile already added in your cart.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}else{
dao.insertCartData(cartData);
Snackbar.make(view, "Mobile has been successfully added in your cart.", Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
}
});
return convertView;
}
static class ViewHolder {
ImageView mobileImage;
TextView mobileName;
TextView mobilePrice;
TextView mobileBrand;
Button viewDetails;
Button addToCart;
}
}
here is the code for custom listview using BaseAdapter in android its working fine:
public class CustomListAdapter extends BaseAdapter {
private ArrayList<TaskClass> _listData;
Context _c;
public CustomListAdapter(Context context, ArrayList<TaskClass> listData) {
_listData = listData;
_c = context;
}
#Override
public int getCount() {
return _listData.size();
}
#Override
public Object getItem(int position) {
return _listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
return v;
}
}
and in activity i m binding listview with custom adapter :
listViewInstance.setAdapter(new CustomListAdapter(getApplicationContext(),taskClasslistInstance));
where "taskclasslistinstance" is my arraylist conatining data from DB its working fine
now i need to write function for listitemclick so that when user click on any listitem i can get rowid of that listitem record from Database.so after getting rowwid I can delete records from listview and from db and can edit informations
Well, we don't know about your TaskClass, but I expect you want something like this:
listViewInstance.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
TaskClass taskClass = taskClasslistInstance.get(pos);
Log.d(TAG, "Clicked on: " + taskClass)
// Do stuff with taskClass
}});
Here a small example from my project:
list = (ListView) rootView.findViewById(R.id.list);
adapter = new LazyAdapterAlbum(getActivity(), songs);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i = new Intent(getActivity(), AlbumActivity.class);
Bundle args = new Bundle();
args.putString(AlbumActivity.ALBUM_NAME, adapter.getItem(position).getName());
i.putExtras(args);
startActivity(i);
}
});
You have to set an onClickListener on your ListView.
you can also set in getView method like below:
public View getView(int position,View convertView,ViewGroup parent) {
View v = convertView;
if (v == null)
{
LayoutInflater layoutInflator = (LayoutInflater) _c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = layoutInflator.inflate(R.layout.listview_row, null);
}
TextView titleText = (TextView)v.findViewById(R.id.holdTitleText);
TextView catText = (TextView)v.findViewById(R.id.holdCatText);
TextView descText = (TextView)v.findViewById(R.id.holdDescText);
TextView dateText = (TextView)v.findViewById(R.id.holdDateText);
//CheckBox checkBoxForEachItem = (CheckBox)v.findViewById(R.id.)
TaskClass taskClassInstance = _listData.get(position);
titleText.setText(taskClassInstance.getTitle());
catText.setText(taskClassInstance.getTaskCategory());
descText.setText(taskClassInstance.getDescription());
dateText.setText(taskClassInstance.getTaskDate());
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Perform an action when this list item is clicked
}
});
return v;
}