Add new cardview dynamically on button click in android - android

I am using a cardview with recyclerview with hardcoded values such as string arrays. But now i want to add new cardview on each button click with user enter values and user select image and keep remain all cardviews on app exit.I mean to say that cardview should be added one by one only.Any solution plz guide me.
cardview Adapter class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeddProperties> dataSet;
private static Context context;
public CardViewDataAdapter(Context context, ArrayList<FeddProperties> os_versions) {
this.context = context;
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeddProperties fp = dataSet.get(i);
viewHolder.vehicleNumber.setText(fp.getTitle());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView vehicleNumber;
public ImageView iconView;
public FeddProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
vehicleNumber = (TextView) itemLayoutView
.findViewById(R.id.vehiclenumber);
iconView = (ImageView) itemLayoutView
.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), InformingUser.class);
v.getContext().startActivity(intent);
((MainActivity) context).getSupportFragmentManager().beginTransaction().replace
(R.id.containerView, new InformingUser()).commit();
//Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
Java file....
private void initContrls()
{
SharedPreferences prefs = context.getSharedPreferences(MY_PREFS_NAME, 0);
vehiclecatory = prefs.getString("vehicle_category", "");
vehicletype = prefs.getString("vehicle_type", "");
String versions = prefs.getString("city", "")+" "+prefs.getString("dis", "")+" "+prefs.getString("number", "");
String vehicleCompany = prefs.getString("company", "")+" "+prefs.getString("model", "");
if(vehiclecatory.equals("1"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.contwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.comfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.comheavy;
}
}
else if (vehiclecatory.equals("2"))
{
if (vehicletype.equals("1"))
{
icons = R.drawable.nontwowheel;
}
else if (vehicletype.equals("2"))
{
icons = R.drawable.nonfourwheel;
}
else if (vehicletype.equals("3"))
{
icons = R.drawable.nonheavy;
}
}
os_versions = new ArrayList<FeddProperties>();
for (int i = 0; i < 2; i++) {
FeddProperties feed = new FeddProperties();
feed.setTitle(versions);
feed.setVehicleCompany(vehicleCompany);
feed.setThumbnail(icons);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
mAdapter = new CardViewDataAdapter(context,os_versions);
recyclerView.setAdapter(mAdapter);
}

here there is an example to add cardview dinamically
In this example cardview are create with for:
for (int index = 0; index < 20; index++) {
DataObject obj = new DataObject("Some Primary Text " + index,
"Secondary " + index);
results.add(index, obj);
}
but you can inser into onClick action :)

Related

RecyclerView list Limited at one fragment and no Limit another fragment

hi I want to make a recycler view in two different fragments in which one fragment has limit recycler view list which is shown only 4 lists and another fragment in which all the list item is shown, thanks in advance.
main class code,
private void populatelist() {
List<reviewModel> reviewModelList = new ArrayList<>();
for (int i = 1; i < 20; i++) {
int imges = R.drawable.ic_userlogin;
String names = "User Name is " + i;
String dates = "New Dates is " + i;
String detail = "User details about is " + i;
reviewModel models = new reviewModel(names, dates, detail, 4, imges);
reviewModelList.add(models);
}
setupRecycle(reviewModelList);
}
private void setupRecycle(List<reviewModel> reviewModelList) {
if (adaptOverView == null)
adaptOverView = new reviewAdapt(this, 5);
adaptOverView.setReviewList(reviewModelList);
LinearLayoutManager layout = new LinearLayoutManager(this);
layout.setSmoothScrollbarEnabled(true);
recyclerOverView.setLayoutManager(layout);
recyclerOverView.setHasFixedSize(true);
recyclerOverView.setAdapter(adaptOverView);
}
adapter class code,
private Context mContext;
private List<reviewModel> reviewList;
private int limit;
public void setReviewList(List<reviewModel> list){
this.reviewList = list;
this.notifyDataSetChanged();
}
public reviewAdapt(Context mContext, int limit) {
this.mContext = mContext;
this.limit = limit;
}
public reviewAdapt(Context mContext, List<reviewModel> reviewList, int limit) {
this.mContext = mContext;
this.reviewList = reviewList;
this.limit = limit;
}
#NonNull
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.review_design, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
if (position < limit) {
reviewModel model = reviewList.get(position);
Log.d("TAG", "onBindViewHolder_Limit: "+limit);
Log.d("TAG", "onBindViewHolder_Position_Is_InLimit: "+position);
holder.textViewName.setText(model.getName());
holder.textViewDate.setText(model.getDate());
holder.ratingBarRecycle.setRating(model.getRatingBar());
holder.textViewDetails.setText(model.getDetails());
holder.imageViewRecycle.setImageResource(model.getImg());
}
}
#Override
public int getItemCount() {
return reviewList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textViewName, textViewDate, textViewDetails;
RatingBar ratingBarRecycle;
ImageView imageViewRecycle;
public ViewHolder(#NonNull View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.name_review);
textViewDate = itemView.findViewById(R.id.date_review);
textViewDetails = itemView.findViewById(R.id.details_review);
ratingBarRecycle = itemView.findViewById(R.id.review_ratingsBar);
imageViewRecycle = itemView.findViewById(R.id.profile_image);
}
}
}
As per my understanding , You are using limit variable for restricting listing size for fragment. But you are not using it rightly. If I am not wrong, Try to restrict item count for in adapter as below -
#Override
public int getItemCount() {
return limit;
}

Unable to show sum of custom Recylerview data

In my app I fetch all data from database and show in recycler view. And I want to show sum of that amount in another textview.
customcartlist.java
public class CustomCartList extends RecyclerView.Adapter<CustomCartList.ViewHolder>{
private Context mCtx;
private List<Cart> cartList;
private int Price,Qty;
private String Total;
public CustomCartList(Context mCtx, List<Cart> cartList) {
this.mCtx = mCtx;
this.cartList = cartList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(R.layout.custom_cart_list,null);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Cart cart = cartList.get(position);
Price = Integer.parseInt(cart.getPrice());
Qty = Integer.parseInt(cart.getQty());
Total = String.valueOf((Price*Qty)); // I want to show sum of this.
holder.product.setText(cart.getProductName());
holder.qty.setText(cart.getQty());
holder.price.setText(Total);
}
#Override
public int getItemCount() {
return cartList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView product,qty,price;
Button wishlist,remove;
public ViewHolder(View view) {
super(view);
product = (TextView) view.findViewById(R.id.PRODUCT);
price = (TextView) view.findViewById(R.id.PRODUCT_PRICE);
qty = (TextView) view.findViewById(R.id.QTY);
wishlist = (Button) view.findViewById(R.id.WISHLIST);
remove = (Button) view.findViewById(R.id.REMOVE);
wishlist.setOnClickListener(this);
remove.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.WISHLIST:
Toast.makeText(view.getContext(),"Wishlist",Toast.LENGTH_LONG).show();
break;
case R.id.REMOVE:
Toast.makeText(view.getContext(),"Remove",Toast.LENGTH_LONG).show();
break;
}
}
}
}
cartFragment.java
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.activity_cart, container,false);
User user = SharedPrefManager.getInstance(getActivity()).getUser();
userid = user.getUserid();
recyclerView = (RecyclerView) rootView.findViewById(R.id.cart);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
total = (TextView) rootView.findViewById(R.id.total);
checkout = (Button) rootView.findViewById(R.id.checkout);
cartList = new ArrayList<>();
loadCart();
customCartList = new CustomCartList(getActivity(),cartList);
recyclerView.setAdapter(customCartList);
return rootView;
}
private void loadCart() {
String CART_URL = "http://192.168.0.101/cart/cart/cart_view.php?vuserid="+userid;
Log.e("url",CART_URL+"");
StringRequest stringRequest = new StringRequest(Request.Method.GET, CART_URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("cart");
for (int i = 0; i < array.length(); i++){
//getting the user from the response
JSONObject userJson = array.getJSONObject(i);
Cart cart = new Cart();
cart.setCartid(userJson.getInt("cartid"));
cart.setProductName(userJson.getString("productname"));
cart.setPrice(userJson.getString("productprice"));
cart.setQty(userJson.getString("quantity"));
cartList.add(cart);
Log.e("product",userJson+"");
}
customCartList.notifyDataSetChanged();
Log.e("cart",customCartList+"");
//customCategoryList = new CustomCategoryList(getActivity(),categoryList);
//recyclerView.setAdapter(customCategoryList);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
Volley.newRequestQueue(getActivity()).add(stringRequest);
}
I want to show sum in total.I am fetch quantity and price from database.I am able to show multiplication for each row but I am unable to show sum to that list.Please help me.
Declare a variable in CartFragment
int totalPrice;
In loadCart() :
private void loadCart() {
...
cart.setPrice(userJson.getString("productprice"));
totalPrice += Integer.parseInt(userJson.getString("productprice"));
...
}
In onCreateView:
total = (TextView) rootView.findViewById(R.id.total);
checkout = (Button) rootView.findViewById(R.id.checkout);
cartList = new ArrayList<>();
loadCart();
total.setText(totalPrice + ""); // ADD THIS LINE
EDIT:
In loadCart():
cart.setPrice(userJson.getString("productprice"));
cart.setQty(userJson.getString("quantity"));
int price = Integer.parseInt(userJson.getString("productprice"));
int qty = Integer.parseInt(userJson.getString("quantity"));
totalPrice += price*qty;
EDIT 2
for (int i = 0; i < array.length(); i++){
...
}
total.setText(totalPrice + "");
customCartList.notifyDataSetChanged();
...

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.

i have used boolean concept to swap the text field in recycler items,

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ContactViewHolder> {
static final String myTag = "DocsUpload";
ArrayList<RecyclerItem> listItems = new ArrayList<>();
RecyclerView.ViewHolder holder;
int clickcount=0;
private Context mContext;
List list = new ArrayList();
Boolean signUpModeActive = true;
public MyAdapter(ArrayList<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view, mContext, listItems);
return contactViewHolder;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtTitle;
public CheckBox checkBox;
public TextView txtDescription;
public ImageView txtOptionDigit;
ArrayList<RecyclerItem> listitems = new ArrayList<RecyclerItem>();
Context ctx;
public ContactViewHolder(View view, Context ctx, ArrayList<RecyclerItem> listitems) {
super(view);
this.listitems = listitems;
this.ctx = ctx;
view.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBoxxml);
}
boolean m=false;
#Override
public void onClick(View v) {
clickcount=clickcount+1;
Log.e("count", String.valueOf(clickcount));
int position = getAdapterPosition();
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle();
if (signUpModeActive=true) {
signUpModeActive = false;
listItems.get(position).setTitle("");
listItems.get(position).setTitle(getname + " " +"absent");
} else {
signUpModeActive = true;
listItems.get(position).setTitle("");
listItems.get(position).setTitle(getname + " " +"present");
}
notifyDataSetChanged();
}
}
public void getsetadapt(String pos) {
list.add(pos);
Log.e("listdata", String.valueOf(list));
for (int i=0;i < list.size();i++)
{
Log.i("Value "+i, String.valueOf(list.get(i)));
i++;
}
}
when I click any list items it want add absent to existing text and if I click it again it want to replace absent with present..can any one know where iam going wrong ...and if run this code at my emulator it works and it is adding the text it is not replacing. For example the if I click student oviya its adding text absent near to oviya but if I click it again it is not replacing its is adding present next to that again and again
Just change your adapter to the following adapter and it will work fine
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ContactViewHolder> {
static final String myTag = "DocsUpload";
ArrayList<RecyclerItem> listItems = new ArrayList<>();
RecyclerView.ViewHolder holder;
int clickcount = 0;
private Context mContext;
List list = new ArrayList();
Boolean signUpModeActive = true;
public MyAdapter(ArrayList<RecyclerItem> listItems, Context mContext) {
this.listItems = listItems;
this.mContext = mContext;
}
#Override
public ContactViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_item_2, parent, false);
ContactViewHolder contactViewHolder = new ContactViewHolder(view, mContext, listItems);
return contactViewHolder;
}
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem itemList = listItems.get(position);
holder.txtTitle.setText(itemList.getTitle());
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ContactViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView txtTitle;
public CheckBox checkBox;
public TextView txtDescription;
public ImageView txtOptionDigit;
ArrayList<RecyclerItem> listitems = new ArrayList<RecyclerItem>();
Context ctx;
public ContactViewHolder(View view, Context ctx, ArrayList<RecyclerItem> listitems) {
super(view);
this.listitems = listitems;
this.ctx = ctx;
view.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txtTitle);
checkBox = (CheckBox) itemView.findViewById(R.id.checkBoxxml);
}
boolean m = false;
#Override
public void onClick(View v) {
clickcount = clickcount + 1;
Log.e("count", String.valueOf(clickcount));
int position = getAdapterPosition();
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle().replace(" absent" , "").replace(" present" , "");
if (signUpModeActive ) {
signUpModeActive = false;
listItems.get(position).setTitle(getname + " " + "absent");
} else {
signUpModeActive = true;
listItems.get(position).setTitle(getname + " " + "present");
}
notifyDataSetChanged();
}
}
public void getsetadapt(String pos) {
list.add(pos);
Log.e("listdata", String.valueOf(list));
for (int i = 0; i < list.size(); i++) {
Log.i("Value " + i, String.valueOf(list.get(i)));
i++;
}
}
}
Actually the problem was in line
final RecyclerItem listitems = this.listitems.get(position);
final String getname = listitems.getTitle();
you were setting text as
listItems.get(position).setTitle(getname + " " + "absent");
OR
listItems.get(position).setTitle(getname + " " + "present");
This will result as Name absent or Name present as result and will add a new absent or present to it
There are different problems in your code.
1
First of all, your variables are not named correctly so it's very confusing. For example you use listitems and listItems which are almost exactly the same. Plus listitems is used twice for 2 different variables with the exact same case in the same scope!
A variable should describe its content (you should understand what it is when you read the name, for example a list of students will not be named 'list' but 'students' or 'studentsList') AND you should avoid to have 2 variables with the exact same name in the same scope (if you have to start doing something like this.myvariable = myvariable it means something is wrong in your implementation).
2 Manage your title differently
What you want is the name + a status depending on if present or not.
So when you do that:
listItems.get(position).setTitle("");
you just loose the name as listItems and listitems are the exact same list.
So I'd suggest to have a getName() method on RecyclerItem to return the name. Remove the set/getTitle ones.
Then you manage the present/absent with a boolean.
Basically, like that:
if (signUpModeActive = true) {
signUpModeActive = false;
item.setIsPresent(false);
} else {
signUpModeActive = true;
item.setIsPresent(true);
}
It means you need to add a setIsPresent method to the RecyclerItem.
Then you, in the onBindViewHolder you do:
#Override
public void onBindViewHolder(final ContactViewHolder holder, final int position) {
RecyclerItem item = mListItems.get(position);
String name = item.getName();
String status = item.isPresent() ? "present" : "absent";
String title = name + " " + status;
holder.txtTitle.setText(title);
}
It'd be even better to use a string resource with a placeholder to manage the text of the status.

RecyclerView items positions change or removed when scrolling

I have a problem that I have been trying to solve for too long but I can't know what causes the problem.
I have a marks list that contains Test objects and subject strings that I use as sections between marks, I use getClass() method to determine if an object is a string or Test, if it is a string, I hide the test's RelativeLayout, if it is a test then I hide the RelativeLayout of the subject. But when scrolling, items get removed and and re-added randomly.
my adapter's class:
public class MarksAdapter extends RecyclerView.Adapter<MarksAdapter.MyHolder>{
public class MyHolder extends RecyclerView.ViewHolder{
RelativeLayout card;
TextView title;
TextView total;
View divider;
int posito;
RelativeLayout group;
TextView groupTitle;
TextView groupMark;
public MyHolder(View itemView) {
super(itemView);
this.card = (RelativeLayout)itemView.findViewById(R.id.card);
this.title = (TextView)itemView.findViewById(R.id.title);
this.total = (TextView)itemView.findViewById(R.id.mark);
this.divider = itemView.findViewById(R.id.item_divider);
this.group = (RelativeLayout)itemView.findViewById(R.id.group);
this.groupTitle = (TextView)itemView.findViewById(R.id.group_title);
this.groupMark = (TextView)itemView.findViewById(R.id.group_mark);
}
}
final ArrayList marks;
Context ctx;
String selectedSem;
TestDatabase db;
public MarksAdapter(Context c, ArrayList marks,String sem,TestDatabase db,ArrayList<Integer> sections){
this.marks = marks;
ctx = c;
selectedSem = sem;
this.db = db;
}
#Override
public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return new MyHolder(LayoutInflater.from(ctx).inflate(R.layout.mark_child, parent, false));
}
int lastPosition = -1;
int offset = 0;
#Override
public void onBindViewHolder(final MyHolder holder, final int positioner) {
holder.posito = positioner;
if(marks.get(holder.posito).getClass() == Test.class) {
holder.group.setVisibility(View.GONE);
//mark
final Test test = (Test)marks.get(positioner);
holder.title.setText(test.getName());
holder.total.setText(String.format(ctx.getString(R.string.new_m_sum), test.getMarkGot(), test.getMarkOver()));
//add here
holder.card.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(ctx,addTest.class);
Test mark = (Test)marks.get(holder.posito);
i.putExtra("t_name",mark.getName());
i.putExtra("subject",mark.getSubject());
i.putExtra("mark_got",mark.getMarkGot());
i.putExtra("mark_over",mark.getMarkOver());
i.putExtra("mode","edit");
i.putExtra("oldId", mark.getId());
ctx.startActivity(i);
}
});
holder.card.setLongClickable(true);
holder.card.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View v) {
final Dialog dialo = new Dialog(ctx);
dialo.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialo.setContentView(R.layout.material_dialog);
TextView title = (TextView) dialo.findViewById(R.id.title);
TextView body = (TextView) dialo.findViewById(R.id.body);
Button negative = (Button) dialo.findViewById(R.id.negative);
negative.setText(ctx.getString(R.string.cancel));
Button positive = (Button) dialo.findViewById(R.id.positive);
positive.setText(ctx.getString(R.string.Delete));
title.setText(ctx.getString(R.string.d));
body.setText(ctx.getString(R.string.q_delete) + " " + test.getName() + " " + ctx.getString(R.string.de_comp));
negative.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialo.dismiss();
}
});
positive.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View vir) {
TestDatabase tb = new TestDatabase(ctx);
SemesterDatabase semesterDatabase = new SemesterDatabase(ctx);
tb.deleteTest(holder.posito, semesterDatabase.getSelected().getName());
MarksAdapter.this.notifyItemRemoved(holder.posito);
marks.remove(holder.posito);
for (int i = 0; i < marks.size(); i++) {
if(!(marks.get(i) instanceof Test)) {
String sub = String.valueOf(marks.get(i));
if(db.isNoValue(sub,selectedSem)){
marks.remove(i);
notifyItemRemoved(i);
}
}
}
dialo.dismiss();
}
});
dialo.show();
return true;
}
});
}else {
holder.group.setVisibility(View.VISIBLE);
holder.card.setVisibility(View.GONE);
//group
if(holder.posito == 0) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)holder.group.getLayoutParams();
params.setMargins(0,0,0,0);
holder.group.setLayoutParams(params);
}
String sub = String.valueOf(marks.get(holder.posito));
holder.groupTitle.setText(sub);
holder.groupMark.setText(db.getTotalSubjectMarks(sub,selectedSem));
}
if(lastPosition < holder.posito) {
if(holder.card.getVisibility() == View.VISIBLE) {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.marks);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 100;
slide.setStartOffset(offset);
holder.card.startAnimation(slide);
} else {
Animation slide = AnimationUtils.loadAnimation(ctx, R.anim.mark_groups);
slide.setInterpolator(new AccelerateInterpolator());
slide.setDuration(700);
offset += 50;
slide.setStartOffset(offset);
holder.group.startAnimation(slide);
}
lastPosition = holder.posito;
}
}
#Override
public int getItemCount() {
return marks.size();
}
}
Note: I already tried the itemViewType method but it didn't work for me
Thanks in advance!
I believe you missed to set holder.card back to visible, like this
if(marks.get(holder.posito).getClass() == Test.class) {
holder.card.setVisibility(View.Visible); //add back this
holder.group.setVisibility(View.GONE);

Categories

Resources