not update ListView scrolling - android

I do not understand how to perform this operation that you mention.
When I press the button I want to change the amount of food orders
I just want to update the button on the selected topic or, if it does not, activate the entire list
public class AdapterFood extends ArrayAdapter<Charola.Producto> {
ImageView imgFood;
private String nameService = "AgregarItemCharola";
private String usuarioId = "UsuarioId";
private String productoId = "ProductoId";
private String cantidad = "Cantidad";
private String especificaciones = "Especificaciones";
private String urlComplete = Constantes.URLMAIN + nameService + "?";
private Fragment fragment;
private List<Charola.Producto> productoList;
public AdapterFood(Context context, List<Charola.Producto> productoList, Fragment fragment) {
super(context, 0, productoList);
this.fragment = fragment;
this.productoList = productoList;
}
#Override
public View getView(final int position, View convertView, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater)
getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View listViewInflate = convertView;
if (convertView == null) {
listViewInflate = inflater.inflate(R.layout.item_menu, viewGroup, false);
}
imgFood = (ImageView) listViewInflate.findViewById(R.id.imageFood);
TextView tituloFood = (TextView) listViewInflate.findViewById(R.id.tittleFood);
TextView descricionFood = (TextView) listViewInflate.findViewById(R.id.descriptionFood);
TextView precio = (TextView) listViewInflate.findViewById(R.id.priceFood);
final Button btnAnadir = (Button) listViewInflate.findViewById(R.id.buttonAnadir);
final Charola.Producto producto = getItem(position);
tituloFood.setText(producto.getNombre().toString());
descricionFood.setText(producto.getDescripcion());
precio.setText("$" + producto.getPrecio() + ".00");
if (producto.getCantidad() != 0) {
btnAnadir.setText("+ Añadir (" + producto.getCantidad() + ")");
btnAnadir.setBackgroundResource(R.drawable.btns_dialogs);
} else {
btnAnadir.setText("+ Añadir");
btnAnadir.setBackgroundResource(R.drawable.btn_anadir);
}
btnAnadir.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new consumeServiceAgregarProductoACharola().execute(urlComplete + "#" + producto.getIdProducto());
}
});
Glide.with(getContext()).
load(producto.getUrlFoto()).placeholder(R.drawable.place_holder)
.into(imgFood);
return listViewInflate;
}
//recuperar id usuario
public int recuperarIdUsario() {
SharedPreferences sharedPreferences = getContext().getSharedPreferences("MIS_PREFRENCIAS", Context.MODE_PRIVATE);
int valor = sharedPreferences.getInt("id", 1);
return valor;
}
//Asynta
}

Related

findLastVisibleItemPosition() returns -1

Create an adapter object, find recycler view id to set adapter and then set layout manager. In scroll listener, unable to get correct LastVisibleItemPosition, it return -1 to me. findFirstVisibleItemPosition() also returning -1.
//Here is Adapter
public class CategoryProduct extends RecyclerView.Adapter<RecyclerView.ViewHolder>
`enter code here`{
private static final int ITEM = 0;
private static final int LOADING = 1;
public String vertical = "";
Context context;
private boolean isLoadingAdded = false;
private boolean retryPageLoad = false;
private List<com.example.it.camanagement.model.CategoryProduct> dataSet;
public CategoryProduct(ArrayList<com.example.it.camanagement.model.CategoryProduct> data, Context context, String vertical) {
this.dataSet = data;
this.context = context;
this.vertical = vertical;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
RecyclerView.ViewHolder viewHolder = null;
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case ITEM:
View viewLoading;
if (vertical.equals("vertical")) {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list, parent, false);
} else {
viewLoading = LayoutInflater.from(parent.getContext())
.inflate(R.layout.category_product_list_grid, parent, false);
}
viewHolder = new MyViewHolder(viewLoading);
break;
case LOADING:
View viewLoading1 = inflater.inflate(R.layout.item_progress, parent, false);
viewHolder = new LoadingVH(viewLoading1);
break;
}
return viewHolder;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, final int listPosition) {
if (listPosition == dataSet.size() - 1) {
CategoryDetails categoryDetails = (CategoryDetails) context;
categoryDetails.onBottomReached(listPosition);
}
switch (getItemViewType(listPosition)) {
case ITEM:
final MyViewHolder myViewHolder = (MyViewHolder) holder;
TextView textViewName = myViewHolder.productName;
// TextView textViewVersion = holder.textViewVersion;
ImageView imageView = myViewHolder.productImage;
RatingBar productRating = myViewHolder.productRasting;
TextView productCost = myViewHolder.productCost;
TextView productDiscount = myViewHolder.productDistCount;
TextView productCOLOR = myViewHolder.productColor;
TextView productId = myViewHolder.product_id;
TextView productModel = myViewHolder.productModel;
TextView productQuantity = myViewHolder.productQuantity;
productModel.setText(dataSet.get(listPosition).getModel());
productQuantity.setText(dataSet.get(listPosition).getQuantity());
productId.setText(dataSet.get(listPosition).getProduct_id());
textViewName.setText(dataSet.get(listPosition).getName());
Glide.with(context).load(dataSet.get(listPosition).getImage()).into(imageView);
productRating.setRating(Float.parseFloat(String.valueOf(dataSet.get(listPosition).getRating())));
productCost.setText("RM " + dataSet.get(listPosition).getPrice());
productDiscount.setText(dataSet.get(listPosition).getDiscount());
if (dataSet.get(listPosition).getSpecial().trim().length() != 0) {
myViewHolder.special.setText("RM " + dataSet.get(listPosition).getSpecial());
strikeThroughText(productCost);
}
break;
case LOADING:
LoadingVH loadingVH = (LoadingVH) holder;
if (retryPageLoad) {
loadingVH.mErrorLayout.setVisibility(View.VISIBLE);
loadingVH.mProgressBar.setVisibility(View.GONE);
loadingVH.mErrorTxt.setText(
errorMsg != null ?
errorMsg :
context.getString(R.string.error_msg_unknown));
} else {
loadingVH.mErrorLayout.setVisibility(View.GONE);
loadingVH.mProgressBar.setVisibility(View.VISIBLE);
}
break;
}
}
private void strikeThroughText(TextView price) {
price.setPaintFlags(price.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
}
#Override
public int getItemCount() {
return dataSet == null ? 0 : dataSet.size();
//return dataSet.size();
}
#Override
public int getItemViewType(int position) {
return (position == dataSet.size() - 1 && isLoadingAdded) ? LOADING : ITEM;
}
public com.example.it.camanagement.model.CategoryProduct getItem(int position) {
return dataSet.get(position);
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView productName, productColor, productCost, productDistCount, product_id, productModel, productQuantity, special;
RatingBar productRasting;
ImageView productImage;
public MyViewHolder(View itemView) {
super(itemView);
this.productName = (TextView) itemView.findViewById(R.id.product_name);
this.productColor = (TextView) itemView.findViewById(R.id.product_color);
this.productCost = (TextView) itemView.findViewById(R.id.cost);
this.productDistCount = (TextView) itemView.findViewById(R.id.discount);
this.productRasting = (RatingBar) itemView.findViewById(R.id.product_rating);
this.product_id = (TextView) itemView.findViewById(R.id.product_iid);
this.productQuantity = (TextView) itemView.findViewById(R.id.quantity);
this.productModel = (TextView) itemView.findViewById(R.id.modelProduct);
//this.textViewVersion = (TextView) itemView.findViewById(R.id.textViewVersion);
this.productImage = (ImageView) itemView.findViewById(R.id.product_image);
this.special = (TextView) itemView.findViewById(R.id.special);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
Intent i = new Intent(context, ProductDescription.class);
i.putExtra("productName", ((TextView) v.findViewById(R.id.product_name)).getText().toString());
i.putExtra("product_id", ((TextView) v.findViewById(R.id.product_iid)).getText().toString());
context.startActivity(i);
if (getPosition() == 0) {
// Toast.makeText(v.getContext(), " On CLick one", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 1) {
//Toast.makeText(v.getContext(), " On CLick Two", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 2) {
// Toast.makeText(v.getContext(), " On CLick Three", Toast.LENGTH_SHORT).show();
}
if (getPosition() == 3) {//
// Toast.makeText(v.getContext(), " On CLick Fore", Toast.LENGTH_SHORT).show();
}
}
});
}
}
protected class LoadingVH extends RecyclerView.ViewHolder {
private ProgressBar mProgressBar;
private ImageButton mRetryBtn;
private TextView mErrorTxt;
private LinearLayout mErrorLayout;
public LoadingVH(View itemView) {
super(itemView);
mProgressBar = (ProgressBar) itemView.findViewById(R.id.loadmore_progress);
mRetryBtn = (ImageButton) itemView.findViewById(R.id.loadmore_retry);
mErrorTxt = (TextView) itemView.findViewById(R.id.loadmore_errortxt);
mErrorLayout = (LinearLayout) itemView.findViewById(R.id.loadmore_errorlayout);
}
}
}
//Recycler View
categoryProduct = (RecyclerView) findViewById(R.id.categoryProductList);
categoryProductAdapter = new CategoryProduct(categoryProduct,categoryProductList, context);
categoryProduct.setAdapter(categoryProductAdapter);
categoryProduct.setNestedScrollingEnabled(false);
categoryProduct.setHasFixedSize(false);
girdLayoutManager = new GridLayoutManager(CategoryDetails.this, 2);
categoryProduct.setLayoutManager(girdLayoutManager);
//scroll Listener
scrollListener = new EndlessRecyclerViewScrollListener(girdLayoutManager) {
#Override
public void onLoadMore(int page, int totalItemsCount, RecyclerView view) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to the bottom of the list
Log.d("pageCount", "" + page);
Log.d("FirstVisibleITEM", "" + girdLayoutManager.findFirstVisibleItemPosition());
Log.d("LastVisibleITEM", "" + girdLayoutManager.findLastVisibleItemPosition());
}
};
categoryProduct.addOnScrollListener(scrollListener);
Finally solved it, Issue was: I was creating the object of layout manager two times. one in method(API response received and after notify the adapter) and another one in OnCreate() method of activity. after removing one object from method( API response received and after notify the adapter), fixed the issue.

mproduct.remove(position) or notifyDataSetChange() does not work inside getView method

I have checked most of the places but i could not get the precise answer for this question.
problem in function : getView
What is the problem : When if condition gets true,
mproduct.remove((position));
notifyDataSetChanged();
both statement suppose to work.
// here mproduct is object of ArrayList;
If i write Log.e(); It displays promt message.
Thanks in advance.
{
public class DataAdapterCheckOut extends BaseAdapter {
Context context;
ArrayList<CheckOutProduct> mproduct;
public DataAdapterCheckOut(Context context, ArrayList<CheckOutProduct>
product){
// super(context, R.layout.activity_list_product, product);
this.context=context;
this.mproduct=product;
}
public class Holder{
TextView nameFV, mrpFV, our_priceFV, weightFv, unitFV, countFV;
ImageView pic;
int countTemp=1,mrp=0,ourPrice=0;
String name;
Button btnAdd, btnSubstract, btnAddCart;
}
#Override
public int getCount() {
return mproduct.size();
}
#Override
public Object getItem(int position) {
return mproduct.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckOutProduct checkOutProduct = mproduct.get(position);
// Check if an existing view is being reused, otherwise inflate the view
SharedPreferences prefs = context.getSharedPreferences("MNA",
Context.MODE_PRIVATE);
String personalEmail = prefs.getString("personalEmail", null);
String mobTemp = prefs.getString("MNAF", null);
final Holder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.activity_list_product,
parent, false);
viewHolder.nameFV = (TextView)
convertView.findViewById(R.id.txtNameViewer);
//viewHolder.idFV = (TextView)
convertView.findViewById(R.id.txtIdViewer);
viewHolder.mrpFV = (TextView)
convertView.findViewById(R.id.txtMrpViewer);
viewHolder.our_priceFV = (TextView)
convertView.findViewById(R.id.txtOurPriceViewer);
viewHolder.weightFv = (TextView)
convertView.findViewById(R.id.txtWeightViewer);
viewHolder.unitFV = (TextView)
convertView.findViewById(R.id.txtUnitViewer);
viewHolder.countFV = (TextView)
convertView.findViewById(R.id.txtViewProductCount);
viewHolder.pic = (ImageView)
convertView.findViewById(R.id.imgView);
viewHolder.btnAdd = (Button)
convertView.findViewById(R.id.buttonAdd);
viewHolder.btnSubstract = (Button)
convertView.findViewById(R.id.buttonSubstract);
viewHolder.btnAddCart = (Button)
convertView.findViewById(R.id.buttonAddCart);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(checkOutProduct.get_name());
viewHolder.name = checkOutProduct.get_name();
viewHolder.mrpFV.setText("MRP : " +
checkOutProduct.getMrp());
viewHolder.mrp = checkOutProduct.getMrp();
viewHolder.our_priceFV.setText("Our Price : " +
checkOutProduct.getOurPrice());
viewHolder.ourPrice = checkOutProduct.getOurPrice();
viewHolder.weightFv.setText(checkOutProduct.getWeight());
viewHolder.unitFV.setText(" " + checkOutProduct.getUnit());
viewHolder.pic.setImageBitmap(convertToBitmap(checkOutProduct.getImage()));
viewHolder.countFV.setText("" +
checkOutProduct.get_quantity());
viewHolder.countTemp = checkOutProduct.get_quantity();
viewHolder.btnAdd.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp++;
viewHolder.countFV.setText("" +
viewHolder.countTemp);
}
});
viewHolder.btnSubstract.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp--;
if (viewHolder.countTemp >= 1)
viewHolder.countFV.setText("" +
viewHolder.countTemp);
else {
Toast.makeText(context, "Sorry Item Count at
least 1", Toast.LENGTH_LONG).show();
viewHolder.countTemp = 1;
}
}
});
viewHolder.btnAddCart.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("B", "Added into Cart");
SharedPreferences prefs =
context.getSharedPreferences("MNA", Context.MODE_PRIVATE);
String personalEmail =
prefs.getString("personalEmail", null);
CheckOutDBHelper checkOutDBHelper1 = new
CheckOutDBHelper(context);
checkOutDBHelper1.addCheckOutInformation(new
CheckOutProduct(personalEmail, checkOutProduct.get_name(),
checkOutProduct.getID(), checkOutProduct.getMrp(),
checkOutProduct.getOurPrice(), checkOutProduct.getWeight(),
checkOutProduct.getUnit(), checkOutProduct.getImage(),
viewHolder.countTemp));
}
});
UserDBHelper userDBHelper = new UserDBHelper(context);
if(personalEmail!=null&&!personalEmail.equals(checkOutProduct.get_gmail()))
{
mproduct.remove(position);
notifyDataSetChanged();
}
if (mobTemp!=null&&!userDBHelper.getEmailId(mobTemp).equals(checkOutProduct.get_gmail())){
mproduct.remove((`enter code here`position));
notifyDataSetChanged();
enter code here
}
return convertView;
}
//get bitmap image from byte array
private Bitmap convertToBitmap(byte[] b){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
}

How to update the value of the textview inside the fragment on the click of the button present in the adapter class in android?

I have two buttons: + and -. I want that when I click on the button +, the value of the textview present in the fragment class (outside the listview) is changed. How can I do this ?
This is my Adapter class:
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
public CartBaseAdapter(Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
// viewHolder.mImgDelete.setTag(pojoCart.getmCategoryId());
/* try {
URL url = new URL(pojoCart.getmItemImage());
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
viewHolder.mImgItem.setImageBitmap(bmp);
} catch (Exception e) {
e.printStackTrace();
// Log.e("exception", "" + e.getMessage());
}*/
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
mValue++;
viewHolder.mTvNumber.setText("" + mValue);
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
// viewHolder.Dish_rate.setVisibility(View.GONE);
Log.e("value1", value1);
Log.e("value2", value2);
z = x * y;
pojoCart.setmItemPrice(String.valueOf(z));
Log.e("z", "" + z);
if (x > 2) {
int n = x - 1;
int k = z / n;
Log.e("k", "" + k);
pojoCart.setmItemPrice(String.valueOf(k));
} else {
pojoCart.setmItemPrice(String.valueOf(z));
}
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
int total = dbh.getTotalOfAmount();
pojoCart.setmTotalPrice(total);
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PojoCart pojoCart = (PojoCart) v.getTag();
int mValue = pojoCart.getmQuantity();
if (mValue > 0) {
mValue--;
viewHolder.mTvNumber.setText("" + mValue);
value1 = viewHolder.mTvNumber.getText().toString();
value2 = pojoCart.getmItemPrice();
int x = Integer.parseInt(value1);
int y = Integer.parseInt(value2);
if (x >= 1) {
Log.e("value11", value1);
Log.e("value22", value2);
int n = x + 1;
Log.e("n", "" + n);
int k = y / n;
Log.e("k", "" + k);
z = k * x;
Log.e("z", "" + z);
pojoCart.setmItemPrice(String.valueOf(z));
} else {
pojoCart.setmItemPrice(pojoCart.getmItemPrice());
}
}
pojoCart.setmQuantity(mValue);
notifyDataSetChanged();
dbh.updateSingleRow(pojoCart.getmCategoryId(), pojoCart.getmItemPrice(), pojoCart.getmQuantity());
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
viewHolder.mImgDelete.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
int categoryId = pojoCart.getmCategoryId();
// int id = (Integer) view.getTag();
// id++;
Log.e("removeIdFromTheTable", "" + categoryId);
dbh.delete_byID(categoryId);
mList.remove(position);
notifyDataSetChanged();
pojoCart.setmTotalPrice(dbh.getTotalOfAmount());
}
}
);
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
This is my Fragment Class:
public class Cart extends Fragment implements View.OnClickListener {
private ArrayList<PojoCart> mCartList;
private ListView mListView;
private CartBaseAdapter mCartBaseAdapter;
private DataBaseHandler dbh;
private List<PojoCartDataBase> pojoCartDataBase;
private TextView mTvProcesscheck, mTvTotalPrice;
private String ItemName, ItemPrice;
private String ItemImage;
private ArrayList<String> mTotalPrice;
private Toolbar toolbar;
private int ItemQuantity;
int id = 1;
private String categoryId;
private int sumOfPrice;
private PojoCart pojoCart;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_cart, container, false);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initialize();
// addData();
displayTotalAmount();
try {
getDataFromDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
private void initialize() {
mTotalPrice = new ArrayList<String>();
mCartList = new ArrayList<PojoCart>();
mListView = (ListView) getActivity().findViewById(R.id.listview_cart);
mCartBaseAdapter = new CartBaseAdapter(getContext(), mCartList);
Parcelable state = mListView.onSaveInstanceState();
mListView.setAdapter(mCartBaseAdapter);
mListView.onRestoreInstanceState(state);
mTvProcesscheck = (TextView) getActivity().findViewById(R.id.tv_checkout);
mTvTotalPrice = (TextView) getActivity().findViewById(R.id.tv_total_price);
toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
dbh = new DataBaseHandler(getContext());
mTvProcesscheck.setOnClickListener(this);
toolbar.setTitle("Cart");
mCartBaseAdapter.notifyDataSetChanged();
final RippleView rippleView = (RippleView) getActivity().findViewById(R.id.ripple_view_cart);
rippleView.setOnRippleCompleteListener(new RippleView.OnRippleCompleteListener() {
#Override
public void onComplete(RippleView rippleView) {
Log.d("Sample", "Ripple completed");
Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();
toolbar.setTitle("Restaurant List");
}
});
}
/* private void addData() {
for (int i = 0; i < mItemName.length; i++) {
PojoCart pojoCart = new PojoCart();
pojoCart.setmItemName(mItemName[i]);
pojoCart.setmItemPrice(mItemPrice[i]);
pojoCart.setmItemImage(mItemImage[i]);
mCartList.add(pojoCart);
}
// mCartList.add(pojoCartDataBase);
}
*/
private void getDataFromDatabase() throws IOException {
Cursor c = dbh.getAllRows();
if (c.moveToFirst()) {
while (c.isAfterLast() == false) {
// int id = c.getInt(0);
int id = c.getInt(1);
Log.e("id.....", "" + id);
ItemName = c.getString(2);
ItemPrice = c.getString(3);
Log.e("itemname", ItemName);
Log.e("itemprice", ItemPrice);
ItemQuantity = c.getInt(4);
Log.e("itemquantity", "" + ItemQuantity);
ItemImage = c.getString(5);
Log.e("itemimage.........", ItemImage);
pojoCart = new PojoCart();
pojoCart.setmItemName(ItemName);
pojoCart.setmItemPrice(ItemPrice);
pojoCart.setmItemImage(ItemImage);
pojoCart.setmQuantity(ItemQuantity);
pojoCart.setmCategoryId(id);
mCartList.add(pojoCart);
mCartBaseAdapter.notifyDataSetChanged();
c.moveToNext();
}
}
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.tv_checkout:
/* Fragment fragment = new LogIn();
getFragmentManager().beginTransaction().replace(R.id.frame, fragment).addToBackStack(null).commit();*/
// toolbar.setTitle("Checkout");
}
}
public void displayTotalAmount() {
int total = dbh.getTotalOfAmount();
mTvTotalPrice.setText(String.valueOf(total));
}
}
I want to change the value of the mTvTotalPric (Textview) on click of the button + and -, which is present at the listview. And the textview which the value I want to change is outside the listview.
In your Adapter class create one interface
Adapter.class
public class CartBaseAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<PojoCart> mList;
private ViewHolder viewHolder;
private HashMap<String, Integer> mHashMap = new HashMap<String, Integer>();
private Integer total;
private DataBaseHandler dbh;
private int Id = 1;
private String value1, value2;
private int z;
private FragmentTransactionListener fragmentTransactionListener = (FragmentTransactionListener) new Cart();
private SendDataToFragment sendDataToFragment;
public CartBaseAdapter(FragmentCart fragmentCart, Context mContext, ArrayList<PojoCart> mList) {
this.mContext = mContext;
this.mList = mList;
dbh = new DataBaseHandler(mContext);
sendDataToFragment = (SendDataToFragment) fragmentCart;
}
//Interface to send data from adapter to fragment
public interface SendDataToFragment {
void sendData(String Data);
}
#Override
public int getCount() {
return mList.size();
}
#Override
public Object getItem(int position) {
return mList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.cart_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.mImgItem = (ImageView) convertView.findViewById(R.id.cart_image);
viewHolder.mTvItemName = (TextView) convertView.findViewById(R.id.tv_item_name);
viewHolder.mTvItemPrice = (TextView) convertView.findViewById(R.id.tv_item_price);
viewHolder.mTvNumber = (TextView) convertView.findViewById(R.id.tv_number);
viewHolder.mBtnAdd = (Button) convertView.findViewById(R.id.btn_add);
viewHolder.mBtnMinus = (Button) convertView.findViewById(R.id.btn_sub);
viewHolder.mImgDelete = (ImageView) convertView.findViewById(R.id.img_del);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
convertView.setTag(viewHolder);
final PojoCart pojoCart = (PojoCart) getItem(position);
viewHolder.mTvItemName.setText(pojoCart.getmItemName());
viewHolder.mTvItemPrice.setText(pojoCart.getmItemPrice());
viewHolder.mImgItem.setImageBitmap(Utility.StringToBitMap(pojoCart.getmItemImage()));
viewHolder.mBtnAdd.setTag(pojoCart);
viewHolder.mBtnMinus.setTag(pojoCart);
viewHolder.mTvItemPrice.setTag(pojoCart);
viewHolder.mTvNumber.setTag(pojoCart);
viewHolder.mImgDelete.setTag(position);
if (pojoCart.getmQuantity() > 0) {
viewHolder.mTvNumber.setText("" + pojoCart.getmQuantity());
} else {
viewHolder.mTvNumber.setText("" + 0);
}
viewHolder.mBtnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
viewHolder.mBtnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Send data via interface to your fragment
sendDataToFragment.sendData("Your Data");
//Your existing code
}
});
return convertView;
}
private class ViewHolder {
TextView mTvItemName, mTvItemPrice, mTvNumber;
ImageView mImgItem, mImgDelete;
Button mBtnAdd, mBtnMinus;
}
}
Inside your fragment implement that interface so as soon as your button is clicked in your adapter you will get the data inside your fragment.
Fragment.class
public class FragmentCart extends Fragment implements
View.OnClickListener, CartBaseAdapter.SendDataToFragment{
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.your_layout, null);
return rootView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
CartBaseAdapter adapter = new CartBaseAdapter(FragmentCart.this, getActivity(), yourList);
}
#Override
public void onClick(View v) {
}
#Override
public void sendData(String Data) {
//set this data to your textView
}
}
Create a interface :
public interface MyListener {
// you can define any parameter as per your requirement
public void callback(View view, int value);
}
In your listview adapter use interface like below on click of button + or - like :
MyListener ml;
ml = (MyListener) context;
ml.callback(this, "success");
In activity implements MyListener than callback method override there and than you get performed action from fragment to activity.

Android custom listview load slow when scrolled

In my custom listview, when i try to scroll down to view a new list item (either bottom or top) the scroll is becoming laggy. Im kinda new in android developement and database so i dunno what is the cause of this.
This is my MainActivity
public class MainActivity extends AppCompatActivity implements CustomAdapter.passing{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_loading);
db = new DBHandler(this,null,null,1);
namaDoctor = this.getResources().getStringArray(R.array.namaDokter);
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
setContentView(R.layout.activity_main);
searchSpesIcon = (ImageView) findViewById(R.id.buttonSearchSpesial);
searchRsIcon = (ImageView) findViewById(R.id.buttonSearchRs);
searchField = (EditText) findViewById(R.id.searchField);
searchDocIcon = (ImageView) findViewById(R.id.buttonSearchDoctor);
help = (LinearLayout) findViewById(R.id.help_view);
searchDocIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE nama LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian nama dokter " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchSpesIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor WHERE spesialisasi LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter spesialisasi " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
searchRsIcon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
keyword = searchField.getText().toString();
query = "SELECT * FROM doctor " +
"WHERE lokasia LIKE '%"+keyword+"%' OR lokasib LIKE '%"+keyword+"%' OR lokasic LIKE '%"+keyword+"%';";
namaDoctor = db.searchDoctor(query);
id = db.getDoctorId();
lokasia = db.getDoctorLokasiA();
lokasib = db.getDoctorLokasiB();
lokasic = db.getDoctorLokasiC();
alamata = db.getDoctorAlamatA();
alamatb = db.getDoctorAlamatB();
alamatc = db.getDoctorAlamatC();
if(tes != namaDoctor.length){
change();
Toast.makeText(getApplicationContext(),"Hasil pencarian dokter di rumah sakit " +keyword,Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),"Tidak ada hasil",Toast.LENGTH_SHORT).show();
}
}
});
}
},milis);
}
void change(){
if(help.getVisibility()==View.VISIBLE){help.setVisibility(View.GONE);}
cAdapter = new CustomAdapter(this,namaDoctor,id);
//use callback
cAdapter.setPass(this);
list = (ListView) findViewById(R.id.listContatiner);
list.setAdapter(cAdapter);
cAdapter.notifyDataSetChanged();
}
#Override
public void getTag1(int t){
p1=t;
}
#Override
public void getTag2(int t2) {
p2=t2;
setNewAct(p1,p2);
}
public void setNewAct(int x, int y){
//some method
}
My CustomAdapter class
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) v.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1,id[position]);
lokasi.setTag(R.id.tag2,position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}
My DBHandler class
public class DBHandler extends SQLiteOpenHelper {
public DBHandler(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
c=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
String query = "CREATE TABLE " + TABLE_DOCTOR + "(" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAMA + " TEXT, " +
COLUMN_DAERAH + " TEXT, " +
COLUMN_SPESIALISASI + " TEXT, " +
COLUMN_LOKASI_A + " TEXT, " +
COLUMN_LOKASI_B + " TEXT, " +
COLUMN_LOKASI_C + " TEXT, " +
COLUMN_ALAMAT_A + " TEXT, " +
COLUMN_ALAMAT_B + " TEXT, " +
COLUMN_ALAMAT_C + " TEXT " +");";
db.execSQL(query);
arrayNama = c.getResources().getStringArray(R.array.namaDokter);
arrayDaerah = c.getResources().getStringArray(R.array.daerahDokter);
arraySpesialisasi = c.getResources().getStringArray(R.array.spesialiasiDokter);
arrayLokasiA = c.getResources().getStringArray(R.array.lokasiA);
arrayLokasiB = c.getResources().getStringArray(R.array.lokasiB);
arrayLokasiC = c.getResources().getStringArray(R.array.lokasiC);
arrayAlamatA = c.getResources().getStringArray(R.array.alamatA);
arrayAlamatB = c.getResources().getStringArray(R.array.alamatB);
arrayAlamatC = c.getResources().getStringArray(R.array.alamatC);
ContentValues cv = new ContentValues();
for (int i = 0; i < arrayNama.length; i++) {
cv.put(COLUMN_NAMA, arrayNama[i]);
cv.put(COLUMN_DAERAH, arrayDaerah[i]);
cv.put(COLUMN_SPESIALISASI, arraySpesialisasi[i]);
cv.put(COLUMN_LOKASI_A, arrayLokasiA[i]);
cv.put(COLUMN_LOKASI_B, arrayLokasiB[i]);
cv.put(COLUMN_LOKASI_C, arrayLokasiC[i]);
cv.put(COLUMN_ALAMAT_A, arrayAlamatA[i]);
cv.put(COLUMN_ALAMAT_B, arrayAlamatB[i]);
cv.put(COLUMN_ALAMAT_C, arrayAlamatC[i]);
db.insert(TABLE_DOCTOR, null, cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_DOCTOR);
db.execSQL("DROP TABLE IF EXISTS " + TABLE_PATIENT);
onCreate(db);
}
public String[] searchDoctor(String qdoc){
SQLiteDatabase db = getWritableDatabase();
Cursor c= db.rawQuery(qdoc,null);
String selectedDoc[] = new String[c.getCount()];
Integer selectedId[] = new Integer[c.getCount()];
String selectedLokasiA[] = new String[c.getCount()];
String selectedLokasiB[] = new String[c.getCount()];
String selectedLokasiC[] = new String[c.getCount()];
String selectedAlamatA[] = new String[c.getCount()];
String selectedAlamatB[] = new String[c.getCount()];
String selectedAlamatC[] = new String[c.getCount()];
int i = 0;
while(c.moveToNext()){
String doc = c.getString(c.getColumnIndex(COLUMN_NAMA));
Integer id = c.getInt(c.getColumnIndex(COLUMN_ID));
String lokasia = c.getString(c.getColumnIndex(COLUMN_LOKASI_A));
String lokasib = c.getString(c.getColumnIndex(COLUMN_LOKASI_B));
String lokasic = c.getString(c.getColumnIndex(COLUMN_LOKASI_C));
String alamata = c.getString(c.getColumnIndex(COLUMN_ALAMAT_A));
String alamatb = c.getString(c.getColumnIndex(COLUMN_ALAMAT_B));
String alamatc = c.getString(c.getColumnIndex(COLUMN_ALAMAT_C));
selectedDoc[i]= doc;
selectedId[i] = id-1;
selectedLokasiA[i]= lokasia;
selectedLokasiB[i] = lokasib;
selectedLokasiC[i] = lokasic;
selectedAlamatA[i]= alamata;
selectedAlamatB[i]=alamatb;
selectedAlamatC[i]= alamatc;
i++;
}
this.doctorId=selectedId;
this.doctorLokasiA=selectedLokasiA;
this.doctorLokasiB=selectedLokasiB;
this.doctorLokasiC=selectedLokasiC;
this.doctorAlamatA=selectedAlamatA;
this.doctorAlamatB=selectedAlamatB;
this.doctorAlamatC=selectedAlamatC;
return selectedDoc;
}
public Integer[] getDoctorId(){
return doctorId;
}
public static String[] getDoctorLokasiA() {
return doctorLokasiA;
}
public static String[] getDoctorLokasiB() {
return doctorLokasiB;
}
public static String[] getDoctorLokasiC() {
return doctorLokasiC;
}
public static String[] getDoctorAlamatA() {
return doctorAlamatA;
}
public static String[] getDoctorAlamatB() {
return doctorAlamatB;
}
public static String[] getDoctorAlamatC() {
return doctorAlamatC;
}
And my Item_doctor.xml
<RelativeLayout
android:id="#+id/itemCLick"
android:background="#0E9EA1"
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="15dp">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:src="#drawable/doctor_1"
android:id="#+id/imageListDoctor"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/imageListDoctor"
android:layout_toEndOf="#+id/imageListDoctor"
android:id="#+id/linearLayout">
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nama"
android:id="#+id/namaDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Spesialis"
android:id="#+id/spesialisasiDoctor"/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Daerah"
android:id="#+id/daerahPraktekDoctor"/>
</LinearLayout>
<Button
android:layout_width="115dp"
android:layout_height="wrap_content"
android:text="Lihat lokasi praktek"
android:layout_alignBottom="#+id/linearLayout"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/lokasiPraktek"
android:onClick="LokasiPraktek"/>
Can someone tell me :
1.Does cursor inserting to array and Sqlite Query can cause big performance issue if not done correctly ?
2.Does the amount of view in the item of an list can affect the performance ?
3.What other things that affect listview performance ?
It will be good if someone tell me in which part of my code that i must change to increase the scroll speed.
Performance of list view can be increased if you use custom ViewHolder and implement in adapter
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.item_doctor, parent, false);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1, id[position]);
viewHolder.lokasi.setTag(R.id.tag2, position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return convertView;
}
private class ViewHolder {
private ImageView ImageDoc;
private Button lokasi;
private TextView nama;
private TextView spesial;
private TextView daerah;
}
Your adapter class's getView method is not properly implemented.
Change it to
#Override
public View getView(final int position, View v, ViewGroup parent) {
View row;
if (v == null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = li.inflate(R.layout.item_doctor, null);
} else {
row = v;
}
spesialisasi = c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
final TextView nama = (TextView) row.findViewById(R.id.namaDoctor);
TextView spesial = (TextView) row.findViewById(R.id.spesialisasiDoctor);
TextView daerah = (TextView) row.findViewById(R.id.daerahPraktekDoctor);
ImageView ImageDoc = (ImageView) row.findViewById(R.id.imageListDoctor);
Button lokasi = (Button) row.findViewById(R.id.lokasiPraktek);
nama.setText(s1[position]);
spesial.setText("Dokter " + spesialisasi[id[position]]);
daerah.setText(daerahPraktek[id[position]]);
ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
lokasi.setTag(R.id.tag1, id[position]);
lokasi.setTag(R.id.tag2, position);
lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return row;
}
getView function in adapter will called when you scrolled to make a item visible. As you write:
final LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
View v will be relayout while you scroll so that it make bad performace. You need check to reuse this view by:
if(v==null) {
final LayoutInflater li = (LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v= li.inflate(R.layout.item_doctor, null);
}
I recommend you use ViewHolder class with Adapter.
try the below adapter,and set the Tag for you each View of Listview.
public class CustomAdapter extends ArrayAdapter {
Context c1;
String s1[];
Integer id[];
String spesialisasi[] ;
String daerahPraktek[];
int arrayImageDoctor[] = {R.drawable.doctor_1...};
public CustomAdapter(Context c, String s[], Integer i[]) {
super(c,R.layout.item_doctor,s);
this.c1=c;
this.s1=s;
this.id=i;
}
private passing pass;
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder viewHolder = null;
if(v==null){
LayoutInflater li=(LayoutInflater) c1.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = li.inflate(R.layout.item_doctor,null);
viewHolder = new ViewHolder();
viewHolder.nama = (TextView) v.findViewById(R.id.namaDoctor);
viewHolder.spesial = (TextView) v.findViewById(R.id.spesialisasiDoctor);
viewHolder.daerah = (TextView) v.findViewById(R.id.daerahPraktekDoctor);
viewHolder.ImageDoc = (ImageView) v.findViewById(R.id.imageListDoctor);
viewHolder.lokasi = (Button) v.findViewById(R.id.lokasiPraktek);
convertView.setTag(viewHolder);
}else{
iewHolder = (ViewHolder) convertView.getTag();
}
spesialisasi= c1.getResources().getStringArray(R.array.spesialiasiDokter);
daerahPraktek = c1.getResources().getStringArray(R.array.daerahDokter);
viewHolder.nama.setText(s1[position]);
viewHolder.spesial.setText("Dokter " + spesialisasi[id[position]]);
viewHolder.daerah.setText(daerahPraktek[id[position]]);
viewHolder.ImageDoc.setImageResource(arrayImageDoctor[id[position]]);
viewHolder.lokasi.setTag(R.id.tag1,id[position]);
viewHolder.lokasi.setTag(R.id.tag2,position);
viewHolder.lokasi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int tag = (int) v.getTag(R.id.tag1);
int pos = (int) v.getTag(R.id.tag2);
pass.getTag1(tag);
pass.getTag2(pos);
}
});
return v;
}
class ViewHolder {
TextView nama,spesial,daerah;
Button lokasi;
ImageView ImageDoc;
}
public void setPass(passing pass){
this.pass=pass;
}
public interface passing{
void getTag1(int t1);
void getTag2(int t2);
}

Setting different color to each item in List ANDROID STUDIO

i've recently started learning android and came across this problem:
after clicking button im displaying new TextView to my ListView - it's a new payment for one of 3 ppl: Lukasz/Marcelina/Karolina - and I want to make every Lukasz' payment appear RED, every Marcelinas BLUE and Karolinas - GREEN
What I tried so far was putting value to a flag (1, 2 or 3) in every CASE in ONCLICK method and adding if statement
if(flag==1){
holder.osoba.setTextColor(Color.RED);
}
else if(flag==2){
holder.osoba.setTextColor(Color.BLUE);
}else if (flag == 3) {
holder.osoba.setTextColor(Color.GREEN);
}
but it turns out I dont set color to a particular item in my List but to all the items (for example when i press 'lukas' it will give me RED Lukasz's payment, but then when I do a Marcelina's new payment which should be BLUE (and Lukasz should star RED) it makes every payment in the list BLUE. Any ideas how to set different color of each List element ?
my Main Activity looks like this:
public class MainActivity extends ListActivity implements View.OnClickListener {
private int flag = 0;
private TextView sum;
private Button addButton;
private EditText addPrice;
private TextView sumPerPerson;
private EditText description;
private ListaWplat listaWplat;
private RadioGroup czlonek;
private RadioButton lukaszRadioButton;
private RadioButton marcelinaRadioButton;
private RadioButton karolinaRadioButton;
private TextView sumaLukasz;
private TextView sumaMarcelina;
private TextView sumaKarolina;
private float tempLukasz = 0;
private float tempMarcelina = 0;
private float tempKarolina = 0;
public float getTempMarcelina() {
return tempMarcelina;
}
public float getTempLukasz() {
return tempLukasz;
}
public float getTempKarolina() {
return tempKarolina;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sum = (TextView) findViewById(R.id.suma);
addButton = (Button) findViewById(R.id.addButton);
addPrice = (EditText) findViewById(R.id.dodajCene);
sumPerPerson = (TextView) findViewById(R.id.sumaNaOsobe);
description = (EditText) findViewById(R.id.description);
sumaLukasz = (TextView) findViewById(R.id.sumaLukasz);
sumaMarcelina = (TextView) findViewById(R.id.sumaMarcelina);
sumaKarolina = (TextView) findViewById(R.id.sumaKarolina);
czlonek = (RadioGroup) findViewById(R.id.czlonek);
lukaszRadioButton = (RadioButton) findViewById(R.id.lukaszRadioButton);
marcelinaRadioButton = (RadioButton) findViewById(R.id.marcelinaRadioButton);
karolinaRadioButton = (RadioButton) findViewById(R.id.karolinaRadioButton);
addButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
int checkedRadioButtonId = czlonek.getCheckedRadioButtonId();
switch (checkedRadioButtonId) {
case R.id.lukaszRadioButton:
if (lukaszRadioButton.isChecked()) {
try {
tempLukasz += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy lukasza
String sumaLukasza = getString(R.string.sumaLukasz);
sumaLukasza = String.format(sumaLukasza, getTempLukasz());
sumaLukasz.setText(sumaLukasza + " zl");
flag = 1;
NowaWplata nowaWplata = new NowaWplata(lukaszRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
listaWplat.setWplaty(nowaWplata);
setListAdapter(new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty()));
}
break;
case R.id.marcelinaRadioButton:
if (marcelinaRadioButton.isChecked()) {
try {
tempMarcelina += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy marceliny
String sumaMarceliny = getString(R.string.sumaMarcelina);
sumaMarceliny = String.format(sumaMarceliny, getTempMarcelina());
sumaMarcelina.setText(sumaMarceliny + " zl");
flag=2;
NowaWplata nowaWplata = new NowaWplata(marcelinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
listaWplat.setWplaty(nowaWplata);
setListAdapter(new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty()));
}
break;
case R.id.karolinaRadioButton:
if (karolinaRadioButton.isChecked()) {
try {
tempKarolina += valueOf(addPrice.getText().toString());
} catch (NumberFormatException e) {
}
// dodanie $ do sumy karoliny
String sumaKaroliny = getString(R.string.sumaKarolina);
sumaKaroliny = String.format(sumaKaroliny, getTempKarolina());
sumaKarolina.setText(sumaKaroliny + " zl");
flag=3;
NowaWplata nowaWplata = new NowaWplata(karolinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString());
ListaWplat.setWplaty(nowaWplata);
NewPaymentAdapter npa = new NewPaymentAdapter(this, R.layout.nowa_wplata, listaWplat.getWplaty());
setListAdapter(npa);
}
break;
}
String sumaCalkowita = getString(R.string.sumaCalkowita);
sumaCalkowita = String.format(sumaCalkowita, getTempKarolina() + getTempLukasz() + getTempMarcelina());
sum.setText(sumaCalkowita);
String sumaSrednia = getString(R.string.sumaSrednio);
sumaSrednia = String.format(sumaSrednia, (getTempKarolina() + getTempLukasz() + getTempMarcelina()) / 3);
sumPerPerson.setText(sumaSrednia);
}
class NewPaymentAdapter extends ArrayAdapter<NowaWplata> {
public LayoutInflater layoutInflater;
public NewPaymentAdapter(Context context, int textViewResourceId, List<NowaWplata> wplaty) {
super(context, textViewResourceId, wplaty);
layoutInflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
NowaWplata nowaWplata = getItem(position);
Holder holder = null;
if(view == null){
view = layoutInflater.inflate(R.layout.nowa_wplata, null);
TextView osobyWplata = (TextView) view.findViewById(R.id.osobaWplata);
TextView kwotaWplaty = (TextView) view.findViewById(R.id.kwotaWplata);
TextView opisWplaty = (TextView) view.findViewById(R.id.opisWplata);
holder = new Holder(osobyWplata, kwotaWplaty, opisWplaty);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
SpannableString spannableString = new SpannableString(nowaWplata.getOsoba().toString());
holder.osoba.setText("[" + nowaWplata.getDate() + "] " + spannableString);
holder.kwota.setText("- " + nowaWplata.getWplata() + "zł");
holder.opis.setText(nowaWplata.getOpis());
return view;
}
}
static class Holder{
public TextView osoba;
public TextView kwota;
public TextView opis;
public Holder(TextView osoba, TextView kwota, TextView opis) {
this.osoba = osoba;
this.opis = opis;
this.kwota = kwota;
}
}
}
Add this flag to the NowaWplata class:
class NowaWplata {
int flag;
public NowaWplata (String par1, String par2, String par3, int flag) {
this.flag = flag;
...
}
}
Then create the instance in next way:
flag=2;
NowaWplata nowaWplata = new NowaWplata(marcelinaRadioButton.getText().toString(), addPrice.getText().toString(), description.getText().toString(), flag);
And update your NewPaymentAdapter.getView() method
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
NowaWplata nowaWplata = getItem(position);
Holder holder = null;
if(view == null){
view = layoutInflater.inflate(R.layout.nowa_wplata, null);
TextView osobyWplata = (TextView) view.findViewById(R.id.osobaWplata);
TextView kwotaWplaty = (TextView) view.findViewById(R.id.kwotaWplata);
TextView opisWplaty = (TextView) view.findViewById(R.id.opisWplata);
holder = new Holder(osobyWplata, kwotaWplaty, opisWplaty);
view.setTag(holder);
}else{
holder = (Holder) view.getTag();
}
SpannableString spannableString = new SpannableString(nowaWplata.getOsoba().toString());
holder.osoba.setText("[" + nowaWplata.getDate() + "] " + spannableString);
holder.kwota.setText("- " + nowaWplata.getWplata() + "zł");
holder.opis.setText(nowaWplata.getOpis());
if(nowaWplata.flag==1){
holder.osoba.setTextColor(Color.RED);
}
else if(nowaWplata.flag==2){
holder.osoba.setTextColor(Color.BLUE);
}else if (nowaWplata.flag == 3) {
holder.osoba.setTextColor(Color.GREEN);
}
return view;
}

Categories

Resources