Recyclerview multi view items with button - java

I want to create a multi-view on Recylcerview by clicking the button(different view for each button). how to write code in Adapter Class or Condition to view it differently.
this is my code.
Adapter Class
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolderOne> {
private List trips = new ArrayList<>();
#NonNull
#Override
public TripHolderOne onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolderOne(itemView);
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
#Override
public void onBindViewHolder(#NonNull TripHolderOne holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewTripTitle.setText(currentTrip.getTripTitle());
holder.textViewDescription.setText(currentTrip.getDescription());
holder.textViewPriority.setText(String.valueOf(currentTrip.getPriority()));
holder.textViewStartDateTime.setText(currentTrip.getStartDateTime());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolderOne extends RecyclerView.ViewHolder {
private TextView textViewTripTitle;
private TextView textViewDescription;
private TextView textViewPriority;
private TextView textViewStartDateTime;
public TripHolderOne(#NonNull View itemView) {
super(itemView);
textViewTripTitle = itemView.findViewById(R.id.text_view_title);
textViewDescription = itemView.findViewById(R.id.text_view_description);
textViewPriority = itemView.findViewById(R.id.text_view_priority);
textViewStartDateTime = itemView.findViewById(R.id.text_view_start_date_time);
}
}
MainActivity Class
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter);
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
And inside MainActivity also have function onActivityResult.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_TRANSPORTATION && resultCode == Activity.RESULT_OK){
String title = data.getStringExtra(AddTripActivity.EXTRA_TITLE);
String description = data.getStringExtra(AddTripActivity.EXTRA_DESCRIPTION);
int priority = data.getIntExtra(AddTripActivity.EXTRA_PRIORITY, 1);
String startDate = data.getStringExtra(AddTripActivity.EXTRA_START_DATE);
String startTime = data.getStringExtra(AddTripActivity.EXTRA_START_TIME);
String startDateTime = data.getStringExtra(AddTripActivity.EXTRA_START_DATE_TIME);
Log.d("TAG", "Text from MainActivity2" + data.getStringExtra("text"));
Trip trip = new Trip(title, description, priority, startDate,startTime,startDateTime);
tripViewModel.insert(trip);
Toast.makeText(this, "trip saved", Toast.LENGTH_SHORT).show();
}

Related

Delete item in RecyclerView works only once

When I delete an item from the RecyclerView, I am no longer able to delete another item. When I make an item I am also unable to delete that item and any other item in the RecyclerView.
Below is the code.
Home.java:
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
itemImage = findViewById(R.id.image_holder);
itemName = findViewById(R.id.add_item_name);
itemPrice = findViewById(R.id.add_price);
itemDesc = findViewById(R.id.add_desc);
// Initialize Firebase Auth
mAuth = FirebaseAuth.getInstance();
addPhotoButton = findViewById(R.id.getCameraBtn);
addFileButton = findViewById(R.id.getGalleryBtn);
imageView = findViewById(R.id.image_holder);
addPhotoButton.setOnClickListener(this);
addFileButton.setOnClickListener(this);
itemList = new ArrayList<Item>();
// add item for testing
itemList.add(new Item(R.drawable.ic_logo, "Baby Stroller", "A stroller for baby", "59.99"));
recyclerView = findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
adapter = new ItemAdapter(itemList);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {
#Override
public void onDeleteClick(int position) {
removeItem(position);
}
#Override
public void onEditClick(int position) {
editItem(position);
}
});
}
// log out back to start page
public void goToStart(View view){
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.getCameraBtn:
//post a photo from the camera
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(takePictureIntent, CAMERA_CODE);
break;
case R.id.getGalleryBtn:
//post an image
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*"); //anything that is image related
startActivityForResult(galleryIntent, GALLERY_CODE);
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_CODE && resultCode == RESULT_OK) {
if (data != null) {
imageUri = data.getData(); //we have the actual path
imageView.setImageURI(imageUri); //show image
}
} else if (requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
}
public void addItem(View view){
if(itemName.getText().toString().trim().length() != 0 || itemPrice.getText().toString().trim().length() != 0 || itemDesc.getText().toString().trim().length() != 0){
itemList.add(new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString()));
adapter = new ItemAdapter(itemList);
recyclerView.setAdapter(adapter);
itemName.setText("");
itemPrice.setText("");
itemDesc.setText("");
}
else{
Toast.makeText(Home.this, "All fields must be filled when creating a new item.",
Toast.LENGTH_LONG).show();
}
}
public void removeItem(int position){
itemList.remove(position);
adapter.notifyItemChanged(position);
}
ItemAdapter.java:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder>{
private ArrayList<Item> ItemList;
private OnItemClickListener Listener;
public void setOnItemClickListener(OnItemClickListener listener) {Listener = listener;}
public interface OnItemClickListener{
void onDeleteClick(int position);
}
public static class ViewHolder extends RecyclerView.ViewHolder{
public ImageView item_image;
public TextView item_name;
public TextView item_desc;
public TextView item_price;
public ImageView deleteBtn;
public ImageView editBtn;
public ViewHolder(#NonNull View itemView, OnItemClickListener listener) {
super(itemView);
item_image = itemView.findViewById(R.id.item_image);
item_name = itemView.findViewById(R.id.item_name);
item_desc = itemView.findViewById(R.id.desc);
item_price = itemView.findViewById(R.id.price);
deleteBtn = itemView.findViewById(R.id.delete_item);
editBtn = itemView.findViewById(R.id.edit_item);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(listener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
listener.onDeleteClick(position);
}
}
}
});
}
}
public ItemAdapter(ArrayList<Item> itemList) {ItemList = itemList;}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
ViewHolder vh = new ViewHolder(v, Listener);
return vh;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Item currentItem = ItemList.get(position);
holder.item_image.setImageResource(currentItem.getItemImage());
holder.item_name.setText(currentItem.getItemName());
holder.item_desc.setText(currentItem.getItemDesc());
holder.item_price.setText(currentItem.getItemPrice());
}
#Override
public int getItemCount() {
return ItemList.size();
}
}
Item.java:
public class Item {
private int itemImage;
private String itemName;
private String itemDesc;
private String itemPrice;
public Item(int itemImage, String itemName, String itemDesc, String itemPrice){
this.itemImage = itemImage;
this.itemName = itemName;
this.itemDesc = itemDesc;
this.itemPrice = itemPrice;
}
public int getItemImage(){return itemImage;}
public String getItemName(){return itemName;}
public String getItemDesc(){return itemDesc;}
public String getItemPrice(){return itemPrice;}
}
When the user clicks the delete button, it will work the first time and remove that particular item but when another item needs to be removed, the button is not responding. The same happens when the user adds an item and is unable to delete any items. Not really sure what could cause this. Thanks.
Edit:
The delete function works correctly when I hardcode items into the RecyclerView. It is only when adding a new item, it doesn't work anymore including the hardcoded items.
In Home.java, you are setting the click listener:
adapter.setOnItemClickListener(new ItemAdapter.OnItemClickListener() {...}
In addItem(), you are creating a new adapter:
adapter = new ItemAdapter(itemList);
The problem is that you never set a click listener on this new adapter.
I would consider not creating a new adapter but calling a notify method to alert the adapter to a new item.
Try to change adapter.notifyItemChanged(position); to adapter.notifyItemRemoved(position);
You are telling the adapter that one item is changed, instead of that use:
notifyDataSetChanged()
this should reload all items

On Clicking one button, it Triggers another button in recycle view

I'm currently working on a attandance management Android app. In my recyclerview there are list of student detail being populated dynamically from database. When i click the first button in the list, it also change the button colour of the 11th button of the list Like wise to 2nd button click changes the colour of 12th View button
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
Context context;`enter code here`
List<StudentDetails> MainImageUploadInfoList;
public RecyclerViewAdapter(Context context, List<StudentDetails> TempList) {
this.MainImageUploadInfoList = TempList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
StudentDetails studentDetails = MainImageUploadInfoList.get(position);
holder.StudentNameTextView.setText(studentDetails.getName());
holder.StudentNumberTextView.setText(studentDetails.getPhoneNumber());
holder.st.setText(studentDetails.getRollno());
holder.cardView.setCardBackgroundColor(getcolor(position));
}
private int getcolor(int position) {
return Color.parseColor("#" + Integer.toHexString(ContextCompat.getColor(context, R.color.normal)));
}
#Override
public int getItemCount() {
return MainImageUploadInfoList.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView StudentNameTextView;
public TextView StudentNumberTextView;
public TextView st;
DatabaseReference databaseReference;
String se,wh,su,d;
Button b;
CardView cardView;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
StudentNameTextView = (TextView) itemView.findViewById(R.id.ShowStudentNameTextView);
StudentNumberTextView = (TextView) itemView.findViewById(R.id.ShowStudentNumberTextView);
st = (TextView) itemView.findViewById(R.id.studentrollno);
cardView=itemView.findViewById(R.id.cardview1);
se=Teacher.getInstance().getSe();
wh=Teacher.getInstance().getWh();
su=Teacher.getInstance().getSu();
d=Teacher.getInstance().getD();
b=itemView.findViewById(R.id.button3);
itemView.findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view ) {
int position=getAdapterPosition();
String message = String.valueOf(position) ;
databaseReference= FirebaseDatabase.getInstance().getReference("attandance").child(wh).child(se).child(su).child(d).child(message);
databaseReference.setValue("p");
itemView.findViewById(R.id.button3).setBackgroundColor(Color.GREEN);
itemView.findViewById(R.id.button4).setEnabled(false);
itemView.findViewById(R.id.button3).setEnabled(false);
Toast.makeText( context,"position is "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
itemView.findViewById(R.id.button4).setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(final View view ) {
int position=getAdapterPosition();
String message = String.valueOf(position) ;
databaseReference= FirebaseDatabase.getInstance().getReference("attandance").child(wh).child(se).child(su).child(d).child(message);
databaseReference.setValue("A");
itemView.findViewById(R.id.button4).setBackgroundColor(Color.RED);
itemView.findViewById(R.id.button3).setEnabled(false);
itemView.findViewById(R.id.button4).setEnabled(false);
}
});
}
#Override
public void onClick(View view) {
// int position=this.getAdapterPosition();
// Intent intent=new Intent(context,mark.class);
// String message = String.valueOf(position);
// intent.putExtra("attan",message);
// context.startActivity(intent);
// Intent intent = new Intent(context,mark.class);
//String message = String.valueOf(position) ;
//intent.putExtra("attan",message);
//context.startActivity(intent);
// Toast.makeText( context,"position is "+String.valueOf(position), Toast.LENGTH_SHORT).show();
}
}
}
}

RecyclerView: different ViewType by different button

I have a recycler view to show an activity timeline and three floating buttons that click to add activity. How can I code three buttons to a different view? How can I pass the condition to the Adapter?
Now I can show only one viewType.
thx a lot.
Adapter.java
public class TripAdapter extends RecyclerView.Adapter<TripAdapter.TripHolder> {
private List<Trip> trips = new ArrayList<>();
private OnItemClickListener listener;
#NonNull
#Override
public TripHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.trip_item, parent, false);
return new TripHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull TripHolder holder, int position) {
Trip currentTrip = trips.get(position);
holder.textViewLodgingTitle.setText(currentTrip.getLodgingTitle());
holder.textTextViewLodgingCheckInDateTime.setText(currentTrip.getLodgingCheckInDateTime());
holder.textTextViewLodgingCheckOutDateTime.setText(currentTrip.getLodgingCheckOutDateTime());
holder.textViewLodgingAddress.setText(currentTrip.getLodgingAddress());
}
#Override
public int getItemCount() {
return trips.size();
}
public void setTrips(List<Trip> trips) {
this.trips = trips;
notifyDataSetChanged();
}
public Trip getTripAt(int position) {
return trips.get(position);
}
class TripHolder extends RecyclerView.ViewHolder {
//lodging
private TextView textViewLodgingTitle;
private TextView textTextViewLodgingCheckInDateTime;
private TextView textTextViewLodgingCheckOutDateTime;
private TextView textViewLodgingAddress;
private TextView textViewLodgingPhone;
private TextView textViewLodgingWebsite;
private TextView textViewLodgingEmail;
public TripHolder(#NonNull View itemView) {
super(itemView);
context = itemView.getContext();
textViewLodgingTitle = itemView.findViewById(R.id.text_view_title);
textTextViewLodgingCheckInDateTime = itemView.findViewById(R.id.text_view_start_date_time);
textTextViewLodgingCheckOutDateTime = itemView.findViewById(R.id.text_view_end_date_time);
textViewLodgingAddress = itemView.findViewById(R.id.text_view_description);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null && position != RecyclerView.NO_POSITION) {
listener.onItemClick(trips.get(position));
}
}
});
}
}
public interface OnItemClickListener {
void onItemClick(Trip trip);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
MainActivity.java
//adapter
RecyclerView recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
final TripAdapter adapter = new TripAdapter();
recyclerView.setAdapter(adapter );
tripViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(TripViewModel.class);
tripViewModel.getAllTrips().observe(this, new Observer<List<Trip>>() {
#Override
public void onChanged(#Nullable List<Trip> trips) {
adapter.setTrips(trips);
}
});
//this on onActivityResult()
else if (requestCode == ADD_LODGING && resultCode == Activity.RESULT_OK) {
//get data from lodging activity
String lodgingTitle = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_TITLE);
String lodgingCheckInDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_IN_DATE_TIME);
String lodgingCheckOutDateTime = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_CHECK_OUT_DATE_TIME);
String lodgingDescription = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_DESCRIPTION);
String lodgingAddress = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_ADDRESS);
String lodgingPhone = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_PHONE);
String lodgingWebsite = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_WEBSITE);
String lodgingEmail = data.getStringExtra(LodgingEditActivity.EXTRA_LODGING_EMAIL);
String lodgingImagePath = "test";
Trip lodging = new Trip(lodgingTitle, lodgingCheckInDateTime, lodgingCheckOutDateTime,lodgingDescription, lodgingAddress, lodgingPhone, lodgingWebsite, lodgingEmail,lodgingImagePath);
tripViewModel.insert(lodging);
Toast.makeText(this, "lodging save", Toast.LENGTH_SHORT).show();
}
My application I adapt from codinginflow channel.
https://codinginflow.com/tutorials/android/room-viewmodel-livedata-recyclerview-mvvm/part-1-introduction

There is no compilation error but when running the code clicking the comment button, it is not leading to the activity I want

I did the code below, used the adapter to show the list, and a button to add a comment to list item, it shows the logcat "ViewPostIme pointer 0 and ViewPostIme pointer 1", upon clicking the comment button.
Upon compilation it doesn't show any error, I tried to use many references via google but nothing works out.
My basic idea is to call the comment button with an associated list item to perform the comment activity.
Adapter class
public class PostsAdapter extends FirestoreRecyclerAdapter<PostsModel, PostsAdapter.PostsHolder> {
private OnItemClickListener listener;
private View.OnClickListener buttonListener;
private String id;
private static final String TAG = "DocSnippets";
public PostsAdapter(#NonNull FirestoreRecyclerOptions<PostsModel> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull PostsHolder holder, int position, #NonNull PostsModel model) {
//retrieve the fields here
holder.textViewDescription.setText(model.getPostContent());
holder.textViewPriority.setText(String.valueOf(model.getSpinnerC()));
holder.textViewPriority.setText(String.valueOf(model.getTimestamp()));
}
#NonNull
#Override
public PostsHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_list_layout,
parent, false);
return new PostsHolder(v);
}
public void deleteItem(int position) {
getSnapshots().getSnapshot(position).getReference().delete();
}
public void setOnClickListener(OnClickListener postKey) {
}
class PostsHolder extends RecyclerView.ViewHolder {
//first declare here the elements to be displayed in the cardview.
TextView textViewTitle;
TextView textViewDescription;
TextView textViewPriority;
Button commentsbutton;
public PostsHolder(final View itemView) {
super(itemView);
textViewTitle = itemView.findViewById(R.id.post_etPostTitle);
textViewDescription = itemView.findViewById(R.id.post_description);
textViewPriority = itemView.findViewById(R.id.post_time);
commentsbutton = itemView.findViewById(R.id.commenting_button);
commentsbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION && buttonListener != null) {
buttonListener.onClick(itemView);
}
}
});
}
}
public interface OnClickListener
{
void OnClickListener(DocumentSnapshot documentSnapshot, int position);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
this.buttonListener = onClickListener;
}
public interface OnItemClickListener {
void onItemClick(DocumentSnapshot documentSnapshot, int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
this.listener = listener;
}
}
Fragment Class
public class HomeFragment extends Fragment {
RelativeLayout mParent;
//FloatingActionButton addButton;
private static final String TAG = "DocSnippets";
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference PostsRef = db.collection("posts");
private PostsAdapter adapter;
private FirestoreRecyclerOptions options;
private FirebaseAuth mAuth;
private String mUserId, id;
private Button commentsbutton;
RecyclerView recyclerView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
//just change the fragment_dashboard
//with the fragment you want to inflate
//like if the class is HomeFragment it should have R.layout.home_fragment
//if it is DashboardFragment it should have R.layout.fragment_dashboard
View view = inflater.inflate(R.layout.fragment_home, container, false);
final FragmentActivity c = getActivity();
LinearLayoutManager layoutManager = new LinearLayoutManager(c);
Query query = PostsRef.orderBy("timestamp", Query.Direction.DESCENDING);
FirestoreRecyclerOptions<PostsModel> options = new FirestoreRecyclerOptions.Builder<PostsModel>()
.setQuery(query, PostsModel.class)
.build();
adapter = new PostsAdapter(options);
recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(c));
recyclerView.setAdapter(adapter);
commentsbutton = (Button) view.findViewById(R.id.commenting_button);
mParent =view.findViewById(R.id.relative_home);
mAuth = FirebaseAuth.getInstance();
mUserId = mAuth.getUid();
adapter.setOnItemClickListener(new PostsAdapter.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
}
});
adapter.setOnClickListener(new PostsAdapter.OnClickListener() {
#Override
public void OnClickListener(DocumentSnapshot documentSnapshot, int position) {
PostsModel note = documentSnapshot.toObject(PostsModel.class);
id = documentSnapshot.getId();
String path = documentSnapshot.getReference().getPath();
Log.d(TAG, "String post Id is: " + id);
Intent toCommentActivity = new Intent(getContext(), CommentActivity.class);
toCommentActivity.putExtra("PostKey", id);
getContext().startActivity(toCommentActivity);
}
});
return view;
}
private String getTime(long timestamp){
long ts = timestamp*1000;
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm a");
String time = sdf.format(new Date(ts));
return time;
}
#Override
public void onStart() {
super.onStart();
adapter.startListening();
}
#Override
public void onStop() {
super.onStop();
adapter.stopListening();
}
}

Clicked item updates other items in the recyclerview?

I have a recycler view which contains a checkbox on click of the check
box I update the value for quantity.The problem is if I select the
first checkbox in my recycler view for some instances even the 5th
check box gets auto checked.
Following is my code for onActivityResult where I call updateBooks which is responsible for handling the click event.
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
mAdapter.notifyDataSetChanged();
search_info.clear();
book_type.clear();
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
getBookData(data);
if (books_list.size() > 0) {
books_list.clear();
mAdapter.swap(prepareData());
mAdapter.notifyDataSetChanged();
}
updateBooks(recyclerView);
mAdapter.notifyDataSetChanged();
}
}
}
Following is the code for updateBooks.
private void updateBooks(RecyclerView recyclerView) {
mAdapter = new DataAdapter(getApplicationContext(), prepareData(), recyclerView, qty, new DataAdapter.OnItemCheckListener() {
#Override
public void onItemCheck(BooksInfo item, DataAdapter.ViewHolder viewHolder) {
if (qty.equals("") || qty.equals(null)) {
viewHolder.tv_qty.setText("0");
} else {
viewHolder.tv_qty.setText(qty);
}
}
#Override
public void onItemUncheck(BooksInfo item, DataAdapter.ViewHolder viewHolder) {
viewHolder.tv_qty.setText("0");
}
});
recyclerView.setAdapter(mAdapter);
}
And this is my Adapter code.
public class DataAdapter extends RecyclerView.Adapter<DataAdapter.ViewHolder> {
private ArrayList<BooksInfo> books;
private Context ctx;
private String qty;
private RecyclerView recyclerView;
public DataAdapter()
{
}
#NonNull
public OnItemCheckListener onItemCheckListener;
public DataAdapter(Context context, ArrayList<BooksInfo> books, RecyclerView recyclerView,String qty, OnItemCheckListener onItemCheckListener) {
this.books = books;
this.ctx = context;
this.qty = qty;
this.onItemCheckListener =onItemCheckListener;
this.recyclerView = recyclerView;
}
public interface OnItemCheckListener {
void onItemCheck(BooksInfo item,ViewHolder viewHolder);
void onItemUncheck(BooksInfo item,ViewHolder viewHolder);
}
public void swap(ArrayList<BooksInfo> datas){
datas = new ArrayList<>();
recyclerView.removeAllViews();
books.clear();
books.addAll(datas);
notifyDataSetChanged();
}
#Override
public DataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_row, viewGroup, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(final DataAdapter.ViewHolder viewHolder, int i) {
final BooksInfo booksInfo = (BooksInfo) books.get(i);
viewHolder.tv_title.setText(booksInfo.getTitle());
viewHolder.tv_price.setText(booksInfo.getPrice());
viewHolder.tv_vol_no.setText(booksInfo.getVol_no());
viewHolder.tv_status.setText(booksInfo.getStatus());
viewHolder.tv_isbn.setText(booksInfo.getISBN());
viewHolder.tv_book_id.setText(booksInfo.getBook_id());
viewHolder.tv_brand.setText(booksInfo.getBrand());
viewHolder.tv_sku.setText(booksInfo.getSku());
viewHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
viewHolder.cb_selection.setChecked(!(viewHolder.cb_selection.isChecked()));
if (viewHolder.cb_selection.isChecked()){
onItemCheckListener.onItemCheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText(qty);
}else{
onItemCheckListener.onItemUncheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText("0");
}
}
});
}
public void updateNotes(ArrayList notesList) {
books = notesList;
}
public void updateQty(String q)
{
qty =q;
}
#Override
public int getItemCount() {
return books.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
public TextView tv_title,tv_price,tv_vol_no,tv_status,tv_isbn,tv_book_id,tv_brand,tv_sku,tv_qty;
public CheckBox cb_selection;
View itemView;
public ViewHolder(View itemView) {
super(itemView);
this.itemView = itemView;
tv_title = (TextView)itemView.findViewById(R.id.tv_title);
tv_price = (TextView) itemView.findViewById(R.id.tv_price);
tv_vol_no = (TextView) itemView.findViewById(R.id.tv_volno);
tv_status = (TextView) itemView.findViewById(R.id.tv_status);
tv_isbn = (TextView) itemView.findViewById(R.id.tv_isbn);
tv_book_id = (TextView) itemView.findViewById(R.id.tv_bookid);
tv_brand = (TextView) itemView.findViewById(R.id.tv_brand);
cb_selection = (CheckBox) itemView.findViewById(R.id.cb_selection);
cb_selection.setClickable(false);
tv_sku = (TextView) itemView.findViewById(R.id.tv_sku);
tv_qty = (TextView) itemView.findViewById(R.id.tv_qty);
}
public void setOnClickListener(View.OnClickListener onClickListener) {
itemView.setOnClickListener(onClickListener);
}
}
}
Views in RecyclerView are reusable and you must store checked state outside the view. Add boolean field to your BookInfo class like public boolean isCkecked. And change some code inside onBindViewHolder:
viewHolder.cb_selection.setChecked(booksInfo.isChecked);
viewHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
booksInfo.isChecked = !booksInfo.isChecked;
viewHolder.cb_selection.setChecked(booksInfo.isChecked);
if (booksInfo.isChecked){
onItemCheckListener.onItemCheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText(qty);
}else{
onItemCheckListener.onItemUncheck(booksInfo,viewHolder);
// viewHolder.tv_qty.setText("0");
}
}
});

Categories