RecyclerView and SQLite Custom OnClickListener - java

Hello everyone I am trying to create fitness app where user can create their custom workout. I am trying to create that via Recycler View and SQLite database. So far I was able to create successful system of adding workout to database and delete the same one.
What I was unable to do is OnClickListener for item of Recycler View.
I was able to create OnClickListener for position,but what I really want is to save previously edited activity as onlclicklistener for particular item of recyler view.
This is what I've created so far and I want to create :
What I really need here is to save red plus icon instead of blue (picture 3 & 4) and load it
when I click on "first". I also want to make it reusable so I can add workout again.
This is code for my Adapter :
private Context mContext;
private Cursor cursor;
private ListItemClickListener listItemClickListener;
public WorkoutsAdapter (Context mContext,Cursor cursor,ListItemClickListener listItemClickListener)
{
this.mContext = mContext;
this.cursor = cursor;
this.listItemClickListener = listItemClickListener;
}
#NonNull
#Override
public WorkoutsAdapter.WorkoutsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.recyclerview_item,parent,false);
return new WorkoutsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull WorkoutsAdapter.WorkoutsViewHolder holder, int position) {
if(!cursor.moveToPosition(position))
{
return;
}
long id = cursor.getLong(cursor.getColumnIndex(WorkoutsContract.WorkoutsEntry._ID));
holder.itemView.setTag(id);
String name = cursor.getString(cursor.getColumnIndex(WorkoutsContract.WorkoutsEntry.WORKOUT_NAME));
holder.workout_name.setText(name);
}
#Override
public int getItemCount() {
return cursor.getCount();
}
public class WorkoutsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView workout_name;
public WorkoutsViewHolder(#NonNull View itemView) {
super(itemView);
workout_name = itemView.findViewById(R.id.word);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
listItemClickListener.onClick(v,getAdapterPosition());
}
}
public void swapCursor (Cursor newCursor) {
if (cursor != null)
{
cursor.close();
}
cursor = newCursor;
if (newCursor != null)
{
this.notifyDataSetChanged();
}
}
This is my second fragment where view is stored and where I want to apply clicklistener to create saved activity :
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.frag_2_layout, container, false);
recyclerView = v.findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
fab = (FloatingActionButton) v.findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getActivity(),SecondActivity.class));
}
});
DbHelper dbHelper = new DbHelper(getActivity());
mydatabase = dbHelper.getWritableDatabase();
Cursor cursor = getAllTasks();
adapter = new WorkoutsAdapter(getActivity(),cursor,this);
recyclerView.setAdapter(adapter);
new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
#Override
public boolean onMove(#NonNull RecyclerView recyclerView, #NonNull RecyclerView.ViewHolder viewHolder, #NonNull RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(#NonNull RecyclerView.ViewHolder viewHolder, int direction) {
long id = (long) viewHolder.itemView.getTag();
removeTask(id);
adapter.swapCursor(getAllTasks());
}
}).attachToRecyclerView(recyclerView);
return v;
}
private void removeTask(long id) {
mydatabase.delete(WorkoutsContract.WorkoutsEntry.TABLE_NAME,
WorkoutsContract.WorkoutsEntry._ID + "=" +id,null);
Toast.makeText(getActivity(),"Wokrout Is Deleted Successfully",Toast.LENGTH_SHORT).show();
}
private Cursor getAllTasks ()
{
return mydatabase.query(WorkoutsContract.WorkoutsEntry.TABLE_NAME,
null,
null,
null,
null,
null,
WorkoutsContract.WorkoutsEntry.COLUMN_TIMESTAMP);
}
#Override
public void onStart() {
super.onStart();
adapter.swapCursor(getAllTasks());
}
#Override
public void onClick(View view, int position) {
long id = (long) view.getTag();
System.out.println(position);

Related

RecyclerView only shows items after Swipe Refresh

I am trying to fetch data from my Parse database and display it into my RecyclerView. Upon entering the Fragment, the RecyclerView displays no data. It isn't until I Swipe Refresh the feed that the items are accurately displayed in the RecyclerView. How can I make the RecyclerView have the items already initialized upon entering the Fragment?
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
placeName = view.findViewById(R.id.profileEstablishmentName);
placeAddress = view.findViewById(R.id.restroomAddressInfo);
placeRating = view.findViewById(R.id.ratingBar);
rvFeed = view.findViewById(R.id.rvRestaurant);
swipeContainer = view.findViewById(R.id.swipeContainer);
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() { queryPosts(); }
});
allPosts = new ArrayList<>();
adapter = new PostsAdapter(getContext(), allPosts);
rvFeed.setAdapter(adapter);
rvFeed.setLayoutManager(new LinearLayoutManager(getContext()));
queryPosts();
setHasOptionsMenu(true);
}
Parse Query:
protected void queryPosts(){
ParseQuery<Post> query = ParseQuery.getQuery(Post.class);
query.include(Post.KEY_USER);
query.include(Post.KEY_PLACE_NAME);
//Constraint to only see posts of the selected Restaurant
query.whereEqualTo(Post.KEY_PLACE_NAME, placeName.getText().toString());
query.setLimit(20);
//Filters the order of the posts based on the time created key (newest on top)
query.addDescendingOrder(Post.KEY_CREATED_KEY);
query.findInBackground(new FindCallback<Post>() {
#Override
public void done(List<Post> posts, ParseException e) {
if (e != null) {
Log.e(TAG, "Issue with getting posts", e);
return;
}
for(Post post : posts){
Log.i(TAG, "Post: " + post.getPlaceName());
}
adapter.clear();
allPosts.addAll(posts);
adapter.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
}
});
}
PostAdapter:
public class PostsAdapter extends RecyclerView.Adapter<PostsAdapter.ViewHolder>{
private Context context;
private List<Post> posts;
public PostsAdapter(Context context, List<Post> posts){
this.context = context;
this.posts = posts;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.item_post, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
Post post = posts.get(position);
holder.bind(post);
}
#Override
public int getItemCount() {
return posts.size();
}
public void clear() {
posts.clear();
notifyDataSetChanged();
}
// Add a list of items -- change to type used
public void addAll(List<Post> list) {
posts.addAll(list);
notifyDataSetChanged();
}
class ViewHolder extends RecyclerView.ViewHolder{
private TextView tvUsername;
private TextView tvDescription;
private TextView tvPlaceName;
private ImageView ivImage;
public ViewHolder(#NonNull View itemView) {
super(itemView);
tvUsername = itemView.findViewById(R.id.username);
tvPlaceName = itemView.findViewById(R.id.placeName);
tvDescription = itemView.findViewById(R.id.reviewDescription);
ivImage = itemView.findViewById(R.id.ivImage);
}
public void bind(Post post) {
//Bind the post data to the view elements
tvDescription.setText(post.getDescription());
tvUsername.setText("#" + post.getUser().getUsername());
tvPlaceName.setText(post.getPlaceName());
ParseFile image = post.getImage();
if (image != null) {
Glide.with(context).load(post.getImage().getUrl()).into(ivImage);
}
}
}

How to block particular Position in Adapter class ANDROID JAVA

I have an adapter class Where i Want to show a BLOCK USER dialog on particular position.
for example if i want to block position 1 of recyclerView .
So can any one help me porgrammatically?
Given below is the Code Of adapter Please check
I want to block user profile based on Recycler View position
if someone could help me in it please;
public class TableProfileAdapter extends RecyclerView.Adapter<TableProfileAdapter.MyViewHolder> {
Context context;
Activity getActivity;
List<TableProfile> profileUser;
OnRecItemClick onRecItemClick;
private boolean isScaleAnimationDone = false;
private boolean isTimerTextViewActionUpCalled = false;
public TableProfileAdapter(List<TableProfile> profileUser, Context context) {
this.profileUser = profileUser;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.profile_item, parent, false);
return new MyViewHolder(view, onRecItemClick);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TableProfile data = profileUser.get(position);
holder.tvUserName.setText(data.getProfileName());
Bitmap image = BitmapManager.byteToBitmap(data.getProfileImage());
holder.profilePic.setImageBitmap(image);
if (context instanceof AccessProfileManagementActivity) {
context.startActivity(new Intent(context,HomeActivity.class));
} else if (context instanceof ProfileManagement) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProfileDetailsActivity.class);
TableProfile model = profileUser.get(holder.getAdapterPosition());
intent.putExtra("DATA", model);
context.startActivity(intent);
notifyDataSetChanged();
((Activity) context).finish();
}
});
}
}
#Override
public int getItemCount() {
return profileUser.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView profilePic;
TextView tvUserName, birthday;
OnRecItemClick onRecItemClick;
RelativeLayout relativeLayout;
public MyViewHolder(#NonNull View itemView, OnRecItemClick onRecItemClick) {
super(itemView);
profilePic = itemView.findViewById(R.id.profileImage);
tvUserName = itemView.findViewById(R.id.userName);
relativeLayout = itemView.findViewById(R.id.relTop);
this.onRecItemClick = onRecItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onRecItemClick.onItemClick(getAdapterPosition());
}
}
public interface OnRecItemClick {
void onItemClick(int position);
}
}

How do I pass data from adapter to mainactivity when a button is clicked

I Uploaded some data to sqlite and I want to delete each data from the recyclerview by pressing a button. so how can I achieve this? I want to get the id from recyclerview to the mainactivity then delete the data from sqlite and update reyclerview. How can I achieve this?
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
MainActivity
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); // Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), listener);
mRecyclerView.setAdapter(selectedProblemsAdapter);
Button remove = findviewbyid(R.id.remove);
remove.setOnClickListener(new View.OnClickListener() {
}
}
SelectedProblemsAdapter
public SelectedProblemsAdapter(Context context, Cursor cursor, OnItemClick listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
// it will call your interface method which is implemented in Activity
holder.yourView_name.setOnClickListener(new View.OnClickListener() {
listener.yourmethod();
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
You can achieve it by implementing an interface.
Step 1: Create an interface with an abstract function that takes in the type of data as its parameters.
public interface OnDataItemClickListener {
void onItemClick(YourItem yourItem);
}
Step 2: Make the activity implement the interface and override its methods.
public class SelectedProblems extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_selecte_problem_drawal);
mRecyclerView = (RecyclerView) findViewById(R.id.selected_problem_recycle_view); //
//Instantiate Recyclerview
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(linearLayoutManager);
mRecyclerView.setHasFixedSize(true);
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems());
mRecyclerView.setAdapter(selectedProblemsAdapter);
}
#Override
public void onItemClick(YourItem yourItem) {
}
Step 3: Pass the interface through the adapter's constructor.
//Global variable of the interface
private onDataItemClickListener onclickListner;
// while instatiating the adapter
selectedProblemsAdapter = new SelectedProblemsAdapter(this, getAllItems(), onClickListener);
Step 4: In the onBindViewHolder method, use the interface instance(received through the constructor) to call the methods, which will help pass the data to the main activity/ activity.
public SelectedProblemsAdapter(Context context, Cursor cursor, OnDataItemClickListener listener) {
this.context = context;
this.cursor = cursor;
listener = listener;
}
#Override
public SelectedProblemsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.activity_selected_problems_content, null, false);
return new SelectedProblemsViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull SelectedProblemsViewHolder holder, final int position) {
if (this.cursor != null){
holder.yourView.setOnClickListener(new View.OnClickListener() {
// onItemClick is the abstract function present in the interface.
listener.onItemClicked(" your data item ");
// here the data item/position etc, which you want to delete will be passed on to the main acticity.
}
}
}
#Override
public int getItemCount() {
return (null != cursor ? cursor.getCount(): 0);
}
public void update(Cursor cursor) {
this.cursor = cursor;
notifyDataSetChanged();
}
class SelectedProblemsViewHolder extends RecyclerView.ViewHolder{
TextView selectedProblems, selectedProblemPrice, selectedProblemTotal;
Button remove_problem_from_cart;
public SelectedProblemsViewHolder(View itemView) {
super(itemView);
selectedProblems = itemView.findViewById(R.id.selected_problems);
selectedProblemPrice = itemView.findViewById(R.id.selected_problem_price);
selectedProblemTotal = itemView.findViewById(R.id.selectedProblemTotal);
remove_problem_from_cart = itemView.findViewById(R.id.remove_problem_from_cart);
}
}
}
Step 5: Finally write the code to delete the object through the overridden interface method, in the main activity.
#Override
public void onItemClick(YourItem yourItem) {
yourItem.delete();
// you can use any number of functions to perform with your dataItem here.
selectedProblemsAdapter.update()
//call your update function here to change the list in recycler view.
}
Note: If you are using a view model and live data, you do not need to write the notifyDataSetChanged() function.The data gets updated automatically.
This will help you to delete or perform any number of operations on your data, which is passed from your adapter to the main activity.

How to remove the data from activity immediately after closing it

I'm creating an Android app, the data that i'm sending through intent is being retrieved every time i click on the item.
I'm sending the retrieved data(which it's a subcollection that is being retrieved every time i click on item) through the intent,and all data receives in an arraylist, so the listener don't know if the same data existed in the arraylist,because the data are in the other activity.
when i click for the first time the data displayed normally in ItemMarkerActivity but when i go back and click again on the same item i see the data load again in the recycler view,and added to the previous same data, i'm using the technique of removing the data onStop but it didn't work perfectly,because i need to close all activities to see that the data removed, i tried to send the CollectionReference through intent but i couldn't do. so I need a way of removing the data immediately after closing the activity, and if anyone has another approach for solving this problem it would better.
Thanks in advance
adapter.setOnItemClickListener(new MarketAdapterRecyclerView.OnItemClickListener() {
#Override
public void onItemClick(DocumentSnapshot documentSnapshot, int position) {
CollectionReference path = documentSnapshot.getReference().collection("ShoppingItems");
listener = path.addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot queryDocumentSnapshots, #Nullable FirebaseFirestoreException e) {
if (e != null) {
return;
}
for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
if (dc.getType() == DocumentChange.Type.ADDED) {
item = dc.getDocument().toObject(Item.class);
itemList.add(item);
}
}
Intent intent = new Intent (shoppingActivity.this, ItemMarkerActivity.class);
Log.v(TAG,"###################################" + itemList.toString());
intent.putExtra("keyName", itemList);
startActivity(intent);
}
});
}
}
The Activity That Receives The data
The Manifest
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ViewHolder> implements Parcelable{
public ArrayList<Item> ItemList;
public Context mContext;
private onMallListener mOnMallListener;
private static final int NO_POSITION = -1;
public ItemAdapter(ArrayList<Item> ItemList, Context mContext, onMallListener mOnMallListener) {
this.ItemList = ItemList;
this.mContext = mContext;
this.mOnMallListener = mOnMallListener;
}
protected ItemAdapter(Parcel in) {
ItemList = in.createTypedArrayList(Item.CREATOR);
}
public static final Creator<ItemAdapter> CREATOR = new Creator<ItemAdapter>() {
#Override
public ItemAdapter createFromParcel(Parcel in) {
return new ItemAdapter(in);
}
#Override
public ItemAdapter[] newArray(int size) {
return new ItemAdapter[size];
}
};
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_card_view_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(view, mOnMallListener);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder viewHolder, int i) {
Item item = ItemList.get(i);
viewHolder.itemType.setText(ItemList.get(i).getItemType());
Picasso.with(mContext)
.load(item.getImageUrl())
.fit()
.centerCrop().into(viewHolder.imageUrl);
}
#Override
public int getItemCount() {
return ItemList.size();
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedList(ItemList);
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
View mView;
public TextView price;
public TextView description;
public TextView itemType;
public ImageView imageUrl;
onMallListener onMallListener;
public ViewHolder(#NonNull View itemView, onMallListener mOnMallListener) {
super(itemView);
mView = itemView;
itemType = (TextView) mView.findViewById(R.id.card_view_image_title);
imageUrl = (ImageView) mView.findViewById(R.id.card_view_image);
this.onMallListener = mOnMallListener;
mView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(mOnMallListener != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION){
mOnMallListener.onMallClick(position);
}
}
}
}
public interface onMallListener{
void onMallClick(int position);
}
}
Save data using Room database in first activity and retrieve it in second.
In any place of your code (and in any activity's callback) you can clean db and all lists/recyclers which listen this data.
https://developer.android.com/training/data-storage/room
Hope it'll help

How to add a recyclerview item dynamically when click a button in another activity?

I have a recyclerview in ShoppingCartActivity and a button in ProductDetailActivity. I want to send some data to ShoppingCartActivity when a button clicked in ProductDetailActivity and display them in recyclerview item that creates dynamically in ShoppingCartActivity.
I added addData method to recyclerview Adapter but it doesn't work and app crashes.
shop_btn = findViewById(R.id.add_to_shopping_cart);
shop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addToCart = new Intent(ProductDetailActivity.this, ShoppingCartActivity.class);
startActivity(addToCart);
}
});
//HERE IS MY RECYCLERVIEW ADAPTER
public class RecyclerViewAdapter_ShoppingCart extends RecyclerView.Adapter<RecyclerViewAdapter_ShoppingCart.MyViewHolder> {
private Context context;
List<CartItems> cartItemsList;
public RecyclerViewAdapter_ShoppingCart(Context context, List<CartItems> cartItemsList) {
this.context = context;
this.cartItemsList = cartItemsList;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view;
LayoutInflater layoutInflater = LayoutInflater.from(context);
view = layoutInflater.inflate(R.layout.card_cart, parent, false);
return new MyViewHolder(view);
}
#NonNull
#Override
public void onBindViewHolder(#NonNull final MyViewHolder holder, final int position) {
holder.cart_title.setText(cartItemsList.get(position).getTitle());
holder.cart_price.setText(cartItemsList.get(position).getPrice());
Picasso.get().load(cartItemsList.get(position).getImageUrl()).into(holder.cart_img);
}
#Override
public int getItemCount() {
return cartItemsList.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView cart_title, cart_price;
ImageView cart_img;
public MyViewHolder(View itemView) {
super(itemView);
cart_title = itemView.findViewById(R.id.cart_title);
cart_price = itemView.findViewById(R.id.cart_price);
//cart_delete = itemView.findViewById(R.id.cart_delete);
cart_img = itemView.findViewById(R.id.cart_image);
}
}
public void addItem(List<CartItems> cartItems) {
CartItems newValue = new CartItems();
newValue.setTitle("123");
newValue.setPrice("123");
newValue.setImageUrl("");
cartItems.add(newValue);
notifyDataSetChanged();
}
}
My goal is adding recyclerview items dynamically to ShoppingCartActivity when a button clicked in ProductDetailActivity but app crashes.

Categories