Get button call from another class - java

I have the two classes OrderAdapter.java OrderActivity.java. In the class OrderAdapter.java is a button and when i click it has to change a textview in the class OrderActivity.java. When i run the app the textview changes one time because of this line which is intend:
textView_order_price.setText(adapter.totalAmount + "");
but when i press the button again it should change the text again but it doesn't. Can you guys help me?
OrderActivity.java
package com.nfc.netvision;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.util.ArrayList;
public class OrderActivity extends AppCompatActivity {
RecyclerView recyclerView;
TextView textView_order_price;
ArrayList<ModelOrder> orderArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
recyclerView.setAdapter(adapter);
textView_order_price.setText(adapter.totalAmount + "");
System.out.println(adapter.totalAmount + "TOASBTORT");
}
}
OrderAdapter.java
package com.nfc.netvision;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.google.firestore.v1.StructuredQuery;
import java.util.ArrayList;
public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.ViewHolder> {
public int totalAmount;
private Context mContext;
private ArrayList<ModelOrder> nList;
OrderAdapter(Context context, ArrayList<ModelOrder> list) {
mContext = context;
nList = list;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
System.out.println(totalAmount);
}
}

2 ways to solve your problem:
1st way - very simple - just add your textView from activity to constructor adapter;
private TextView orderPrice;
OrderAdapter(Context context, ArrayList<ModelOrder> list,TextView orderPrice) {
mContext = context;
nList = list;
this.orderPrice = orderPrice;
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
//here you add totalAmount to your textView in activity
orderPrice.setText(totalAmount.toString)
System.out.println(totalAmount);
}
2d way create interface in your adapter and implement it in your activity;
//1st create interface in your adapter like this:
public class OrderAdapter extends
RecyclerView.Adapter<OrderAdapter.ViewHolder> {
public int totalAmount;
private Context mContext;
private ArrayList<ModelOrder> nList;
private TotalListener listener;
interface TotalListener{
void onTotalChanged(String result);
}
OrderAdapter(Context context, ArrayList<ModelOrder> list,TotalListener listener) {
mContext = context;
nList = list;
this.listener = listener;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(mContext);
View view = layoutInflater.inflate(R.layout.recyclerview_order_items, parent, false);
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ViewHolder holder, int position) {
final ModelOrder orderItem = nList.get(position);
ImageView image = holder.item_image;
final TextView name, place, price;
name = holder.item_name;
place = holder.item_place;
price = holder.item_price;
image.setImageResource(orderItem.getImage());
name.setText(orderItem.getName());
place.setText(orderItem.getPlace());
price.setText(orderItem.getPrice());
holder.order_item_minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() > 0) {
orderItem.setCounter(orderItem.getCounter()-1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), false);
}
}
});
holder.order_item_plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(orderItem.getCounter() < 9) {
orderItem.setCounter(orderItem.getCounter() + 1);
holder.order_item_count.setText("" + orderItem.getCounter());
calculatePrice(Integer.parseInt((String) price.getText()), true);
}
}
});
}
#Override
public int getItemCount() {
return nList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
ImageView item_image;
TextView item_name, item_place, item_price,order_item_minus,order_item_count, order_item_plus;
public ViewHolder(#NonNull View itemView) {
super(itemView);
item_image = itemView.findViewById(R.id.order_item_image);
item_name = itemView.findViewById(R.id.order_item_name);
item_place = itemView.findViewById(R.id.order_item_place);
item_price = itemView.findViewById(R.id.order_item_price);
order_item_minus = itemView.findViewById(R.id.order_item_minus);
order_item_plus = itemView.findViewById(R.id.order_item_plus);
order_item_count = itemView.findViewById(R.id.order_item_count);
}
}
public void calculatePrice(int pPrice, boolean pUpDown) {
if(pUpDown) {
totalAmount = totalAmount + pPrice;
}
else {
totalAmount = totalAmount - pPrice;
}
//this is callback to your activity
listener.onTotalChanged(totalAmount.toString)
System.out.println(totalAmount);
}
}
and this is your updated activity
public class OrderActivity extends AppCompatActivity impelemts OrderAdapter.TotalListener {
RecyclerView recyclerView;
TextView textView_order_price;
ArrayList<ModelOrder> orderArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order);
recyclerView = findViewById(R.id.recyclerview_order_scroll);
textView_order_price = findViewById(R.id.textView_order_price);
orderArrayList = new ArrayList<>();
orderArrayList.add(new ModelOrder(R.drawable.coke, "Coka Cola", "Eine Cola hält dich wach und schmeckt dazu.", "3",0));
orderArrayList.add(new ModelOrder(R.drawable.fastfood, "Pommes", "Fritten für die Titten.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.water, "Wasser", "Still und sanft, so mag ich es.", "5",0));
orderArrayList.add(new ModelOrder(R.drawable.burger, "Burger", "Ach mir fällt nichts ein.", "10",0));
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerView.LayoutManager recLiLayoutManager = layoutManager;
recyclerView.setLayoutManager(recLiLayoutManager);
OrderAdapter adapter = new OrderAdapter(this, orderArrayList,this);
recyclerView.setAdapter(adapter);
textView_order_price.setText(adapter.totalAmount + "");
System.out.println(adapter.totalAmount + "TOASBTORT");
}
#Override
public void onTotalChanged(String result) {
textView_order_price.setText(result);
}
}

add this listener to your adpater class and when you clik button listner call
private OnButtonClickListener listener;
public void setOnButtonClickListener(OnButtonClickListener listener){
this.listener=listener;
}
public interface OnButtonClickListener{
void OnButtonClick();
}
in Button click in your adapter :
listener.OnButtonClick();
in your activty class
OrderAdapter adapter = new OrderAdapter(this, orderArrayList);
adapter.setOnButtonClickListener(new OnButtonClickListener () {
#Override
public void OnButtonClick() {
//here you can do any thing on your text view
}
});

Related

I trying to do Expandable Recyclerview but have a bug Android/Java

I try to implement expandable RecyclerView as shown in this example :
https://github.com/CodingSTUFF070/Nested-RecyclerView-Inside-Expandable-RecyclerView
But I have bug :
When I implement the same for my app. Steps to reproduce - Click 1st item (Instant Food and Noodles) and scroll to last and click last item (Personal Care) without closing 1st opened item. Now, if you scroll-up and see the child items of 1st parent, you'll see child items of lastly opened parent (Personal Care).
Please tell me how to fix this?
MainActivity:
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private List<DataModel> mList;
private ItemAdapter adapter;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.main_recyclervie);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
mList = new ArrayList<>();
//list1
List<String> nestedList1 = new ArrayList<>();
nestedList1.add("Jams and Honey");
nestedList1.add("Pickles and Chutneys");
nestedList1.add("Readymade Meals");
nestedList1.add("Chyawanprash and Health Foods");
nestedList1.add("Pasta and Soups");
nestedList1.add("Sauces and Ketchup");
nestedList1.add("Namkeen and Snacks");
nestedList1.add("Honey and Spreads");
List<String> nestedList2 = new ArrayList<>();
nestedList2.add("Book");
nestedList2.add("Pen");
nestedList2.add("Office Chair");
nestedList2.add("Pencil");
nestedList2.add("Eraser");
nestedList2.add("NoteBook");
nestedList2.add("Map");
nestedList2.add("Office Table");
List<String> nestedList3 = new ArrayList<>();
nestedList3.add("Decorates");
nestedList3.add("Tea Table");
nestedList3.add("Wall Paint");
nestedList3.add("Furniture");
nestedList3.add("Bedsits");
nestedList3.add("Certain");
nestedList3.add("Namkeen and Snacks");
nestedList3.add("Honey and Spreads");
List<String> nestedList4 = new ArrayList<>();
nestedList4.add("Pasta");
nestedList4.add("Spices");
nestedList4.add("Salt");
nestedList4.add("Chyawanprash");
nestedList4.add("Maggie");
nestedList4.add("Sauces and Ketchup");
nestedList4.add("Snacks");
nestedList4.add("Kurkure");
List<String> nestedList5 = new ArrayList<>();
nestedList5.add("Jams and Honey");
nestedList5.add("Pickles and Chutneys");
nestedList5.add("Readymade Meals");
nestedList5.add("Chyawanprash and Health Foods");
nestedList5.add("Pasta and Soups");
nestedList5.add("Sauces and Ketchup");
nestedList5.add("Namkeen and Snacks");
nestedList5.add("Honey and Spreads");
List<String> nestedList6 = new ArrayList<>();
nestedList6.add("Pasta");
nestedList6.add("Spices");
nestedList6.add("Salt");
nestedList6.add("Chyawanprash");
nestedList6.add("Maggie");
nestedList6.add("Sauces and Ketchup");
nestedList6.add("Snacks");
nestedList6.add("Kurkure");
List<String> nestedList7 = new ArrayList<>();
nestedList7.add("Decorates");
nestedList7.add("Tea Table");
nestedList7.add("Wall Paint");
nestedList7.add("Furniture");
nestedList7.add("Bedsits");
nestedList7.add("Certain");
nestedList7.add("Namkeen and Snacks");
nestedList7.add("Honey and Spreads");
mList.add(new DataModel(nestedList1 , "Instant Food and Noodles"));
mList.add(new DataModel( nestedList2,"Stationary"));
mList.add(new DataModel( nestedList3,"Home Care"));
mList.add(new DataModel(nestedList4 ,"Grocery & Staples"));
mList.add(new DataModel(nestedList5,"Pet Care"));
mList.add(new DataModel(nestedList6,"Baby Care"));
mList.add(new DataModel(nestedList7 ,"Personal Care"));
adapter = new ItemAdapter(mList);
recyclerView.setAdapter(adapter);
}
}
DataModel:
public class DataModel {
private List<String> nestedList;
private String itemText;
private boolean isExpandable;
public DataModel(List<String> itemList, String itemText) {
this.nestedList = itemList;
this.itemText = itemText;
isExpandable = false;
}
public void setExpandable(boolean expandable) {
isExpandable = expandable;
}
public List<String> getNestedList() {
return nestedList;
}
public String getItemText() {
return itemText;
}
public boolean isExpandable() {
return isExpandable;
}
}
ItemAdapter:
public class ItemAdapter extends RecyclerView.Adapter<ItemAdapter.ItemViewHolder> {
private List<DataModel> mList;
private List<String> list = new ArrayList<>();
public ItemAdapter(List<DataModel> mList){
this.mList = mList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.each_item , parent , false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
DataModel model = mList.get(position);
holder.mTextView.setText(model.getItemText());
boolean isExpandable = model.isExpandable();
holder.expandableLayout.setVisibility(isExpandable ? View.VISIBLE : View.GONE);
if (isExpandable){
holder.mArrowImage.setImageResource(R.drawable.arrow_up);
}else{
holder.mArrowImage.setImageResource(R.drawable.arrow_down);
}
NestedAdapter adapter = new NestedAdapter(list);
holder.nestedRecyclerView.setLayoutManager(new LinearLayoutManager(holder.itemView.getContext()));
holder.nestedRecyclerView.setHasFixedSize(true);
holder.nestedRecyclerView.setAdapter(adapter);
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
model.setExpandable(!model.isExpandable());
list = model.getNestedList();
notifyItemChanged(holder.getAdapterPosition());
}
});
}
#Override
public int getItemCount() {
return mList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder{
private LinearLayout linearLayout;
private RelativeLayout expandableLayout;
private TextView mTextView;
private ImageView mArrowImage;
private RecyclerView nestedRecyclerView;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
linearLayout = itemView.findViewById(R.id.linear_layout);
expandableLayout = itemView.findViewById(R.id.expandable_layout);
mTextView = itemView.findViewById(R.id.itemTv);
mArrowImage = itemView.findViewById(R.id.arro_imageview);
nestedRecyclerView = itemView.findViewById(R.id.child_rv);
}
}
}
NestedAdapter:
public class NestedAdapter extends RecyclerView.Adapter<NestedAdapter.NestedViewHolder> {
private List<String> mList;
public NestedAdapter(List<String> mList){
this.mList = mList;
}
#NonNull
#Override
public NestedViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.nested_item , parent , false);
return new NestedViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull NestedViewHolder holder, int position) {
holder.mTv.setText(mList.get(position));
}
#Override
public int getItemCount() {
return mList.size();
}
public class NestedViewHolder extends RecyclerView.ViewHolder{
private TextView mTv;
public NestedViewHolder(#NonNull View itemView) {
super(itemView);
mTv = itemView.findViewById(R.id.nestedItemTv);
}
}
}

Scroll to a specific item in recyclerview when clicked on another recyclerView item

I have two recycler view one horizontal and one vertical
In my horizontal recycler view, there are categories and in vertical, there is items list. So I need to do that when I click on any category my vertical recycler view scroll to that specific item
Attaching the screenshot in the link - https://ibb.co/n67WdRn
https://ibb.co/P5CrjnH
I have tried using intent and it works but it starts a new activity
Please help
Mainactivity.java
package com.example.myapplication;
public class MainActivity extends AppCompatActivity {
DatabaseReference reference;
ArrayList<dish> list;
private static final String TAG = "MainActivity";
private ArrayList<String> mCategory = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getCategory();
menu();
}
private void getCategory(){
Log.d(TAG, "Preparing Categories");
mCategory.add("Vagetables");
mCategory.add("Indian Bread");
mCategory.add("Paranthas");
mCategory.add("Starters");
mCategory.add("Snacks");
mCategory.add("Salad");
mCategory.add("Noodles");
mCategory.add("Sandwiches");
mCategory.add("Rice");
mCategory.add("Soups");
mCategory.add("Beverages");
mCategory.add("Yoghurt");
mCategory.add("Papad");
initRecyclerView();
}
private void initRecyclerView(){
Log.d(TAG, "init RecyclerView");
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
RecyclerView recyclerView = findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(layoutManager);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, mCategory);
recyclerView.setAdapter(adapter);
}
private void menu(){
list = new ArrayList<dish>();
Log.d(TAG, "recycler MenuView : Firebase Initialized");
FirebaseApp.initializeApp(this);
reference = FirebaseDatabase.getInstance().getReference().child("dishes");
reference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange : called");
for (DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Log.d(TAG,"Adding Menu");
dish p = dataSnapshot1.getValue(dish.class);
Log.d(TAG, "called : " + p);
Log.d(TAG, " : " + dataSnapshot + " : " + dataSnapshot1);
list.add(p);
}
getmenu();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(MainActivity.this, " Opps....Somethinf Went wrong!", Toast.LENGTH_LONG).show();
}
});
}
private void getmenu(){
Log.d(TAG,"Setting adapter");
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this, RecyclerView.VERTICAL, false);
RecyclerView recyclerMenuView = findViewById(R.id.recyclerMenuView);
recyclerMenuView.setLayoutManager(linearLayoutManager);
MenuAdapter adapter = new MenuAdapter(MainActivity.this, list);
recyclerMenuView.setAdapter(adapter);
}
}
RecyclerViewAdapter.java - Category recyclerview (Click on this item)
package com.example.myapplication;
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>{
#NonNull
private static final String TAG = "RecyclerViewAdapter";
private ArrayList<String> mCategory = new ArrayList<>();
private Context context;
public RecyclerViewAdapter(Context context, ArrayList<String> category) {
this.context = context;
mCategory = category;
}
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG ,"On Create View Holder: called");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, final int position) {
Log.d(TAG, "OnBindViewHolder: called");
holder.category.setText(mCategory.get(position));
holder.category.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG,"onClick : Clicked on Text" + mCategory.get(position));
Toast.makeText(context, mCategory.get(position), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return mCategory.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder{
TextView category;
public ViewHolder(#NonNull View itemView) {
super(itemView);
category = itemView.findViewById(R.id.category);
}
}
}
MenuAdapter.java - Scroll the item rom this recycler view
package com.example.myapplication;
public class MenuAdapter extends RecyclerView.Adapter<MenuAdapter.menuViewHolder>{
Context context;
ArrayList<dish> dishes;
public MenuAdapter(Context c , ArrayList<dish> p)
{
context = c;
dishes = p;
}
#NonNull
#Override
public menuViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Log.d(TAG ,"On Create View Holder: called");
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.cardview, parent, false);
return new MenuAdapter.menuViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull menuViewHolder holder, final int position) {
holder.dishname.setText(dishes.get(position).getDishname());
holder.dishrate.setText(dishes.get(position).getDishrate());
Picasso.get().load(dishes.get(position).getDishImage()).placeholder(R.drawable.ic_launcher_background).into(holder.dishImage);
boolean flag = dishes.get(position).getPermission();
if (flag){
Log.d(TAG," recommended : " + dishes.get(position).getDishname());
holder.recommended.setVisibility(View.VISIBLE);
}
else{
holder.recommended.setVisibility(View.INVISIBLE);
}
}
#Override
public int getItemCount() {
return dishes.size();
}
class menuViewHolder extends RecyclerView.ViewHolder {
TextView dishname, dishrate, recommended;
ImageView dishImage;
public menuViewHolder(#NonNull View itemView)
{
super(itemView);
dishname = (TextView) itemView.findViewById(R.id.dishname);
dishrate = (TextView) itemView.findViewById(R.id.dishrate);
dishImage = (ImageView) itemView.findViewById(R.id.dishImage);
recommended = (TextView) itemView.findViewById(R.id.recommended);
}
}
}
Try using RecyclerView's scrollTo(position) or smoothScrollTo(position)

Getting Null Pointer exception in setting recycler item click listener [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I have searched a lot and didn't find any solution for my problem.I have created an interface for handling click listeners on particular item on recycler view.Logcat shows the error is occured in setting the listener in maiactivity
here is my MainActivity.java file
package com.example.mynotes;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import java.util.List;
public class MainActivity extends AppCompatActivity implements NoteAdapter.OnItemClickListener {
public static final int ADD_NOTE_REQUEST = 1;
public static final int EDIT_NOTE_REQUEST = 2;
NoteViewModel noteViewModel;
List<Note> allNotes;
RecyclerView rv;
NoteAdapter adapter;
FloatingActionButton floatingActionButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
floatingActionButton = (FloatingActionButton) findViewById(R.id.fab);
rv = (RecyclerView) findViewById(R.id.noterv);
rv.setLayoutManager(new LinearLayoutManager(this));
rv.setHasFixedSize(true);
noteViewModel = ViewModelProviders.of(this).get(NoteViewModel.class);
noteViewModel.getAllnotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
adapter = new NoteAdapter(notes);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
adapter.SetOnItemClickListener(this) ;
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddNoteActivity.class);
startActivityForResult(intent, ADD_NOTE_REQUEST);
}
});
ItemTouchHelper itemTouchHelper = 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) {
noteViewModel.delete(adapter.getAt(viewHolder.getAdapterPosition()));
Toast.makeText(MainActivity.this, "note has been deleted", Toast.LENGTH_SHORT).show();
}
});
itemTouchHelper.attachToRecyclerView(rv);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_NOTE_REQUEST && resultCode == RESULT_OK) {
String title = data.getStringExtra("EXTRA_TITLE");
String description = data.getStringExtra("EXTRA_DESCRIPTION");
String time = data.getStringExtra("EXTRA_TIME");
Note note = new Note(title, description, time);
noteViewModel.insert(note);
}
else if(requestCode == EDIT_NOTE_REQUEST && resultCode == RESULT_OK){
String title = data.getStringExtra("EXTRA_TITLE");
String description = data.getStringExtra("EXTRA_DESCRIPTION");
String time = data.getStringExtra("EXTRA_TIME");
Note note = new Note(title, description, time);
note.setId(data.getIntExtra("EXTRA_ID",-1));
noteViewModel.update(note);
Toast.makeText(this, "note has been updated", Toast.LENGTH_SHORT).show();
}
}
#Override
public void OnItemClick(Note note) {
Intent intent =new Intent(MainActivity.this,AddNoteActivity.class);
intent.putExtra("EXTRA_ID",note.getId());
intent.putExtra("EXTRA_TITLE",note.getTitle());
intent.putExtra("EXTRA_DESCRIPTION",note.getDescription());
intent.putExtra("EXTRA_TIME",note.getModified_time());
startActivityForResult(intent,EDIT_NOTE_REQUEST);
}
}
here is my NoteAdapter.java file
package com.example.mynotes;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.NoteViewHolder> {
OnItemClickListener listener;
List<Note> notes=new ArrayList<>();
public NoteAdapter(List<Note> notes) {
this.notes = notes;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View item_view = inflater.inflate(R.layout.single_note_item, parent, false);
// Return a new holder instance
NoteViewHolder viewHolder = new NoteViewHolder(item_view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note =notes.get(position);
holder.titletv.setText(note.getTitle());
holder.datetv.setText(note.getModified_time());
}
#Override
public int getItemCount() {
return notes.size();
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titletv ;
TextView datetv;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titletv=(TextView) itemView.findViewById(R.id.titletv);
datetv=(TextView) itemView.findViewById(R.id.datetv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener !=null && getAdapterPosition() != RecyclerView.NO_POSITION){
int position=getAdapterPosition();
listener.OnItemClick(notes.get(position));
}
}
});
}
}
Note getAt(int position){
return notes.get(position);
}
public interface OnItemClickListener{
void OnItemClick(Note note);
}
public void SetOnItemClickListener(OnItemClickListener onItemClickListener){
this.listener =onItemClickListener;
}
}
here is my Logcat message:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.mynotes.NoteAdapter.SetOnItemClickListener(com.example.mynotes.NoteAdapter$OnItemClickListener)' on a null object reference
at com.example.mynotes.MainActivity.onCreate(MainActivity.java:52)
at android.app.Activity.performCreate(Activity.java:7009)
at android.app.Activity.performCreate(Activity.java:7000)
Move this code to observer
adapter.SetOnItemClickListener(this) ;
So your code must be like this
noteViewModel.getAllnotes().observe(this, new Observer<List<Note>>() {
#Override
public void onChanged(List<Note> notes) {
adapter = new NoteAdapter(notes);
adapter.SetOnItemClickListener(this);
rv.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
});
do this in your adapter and where you will new your adapter in activity:
package com.example.mynotes;
public class NoteAdapter extends RecyclerView.Adapter {
OnItemClickListener listener;
List<Note> notes=new ArrayList<>();
public NoteAdapter(List<Note> notes, OnItemClickListener listener) {
this.notes = notes;
this.listener = listener;
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
// Inflate the custom layout
View item_view = inflater.inflate(R.layout.single_note_item, parent, false);
// Return a new holder instance
NoteViewHolder viewHolder = new NoteViewHolder(item_view);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull NoteViewHolder holder, int position) {
Note note =notes.get(position);
holder.titletv.setText(note.getTitle());
holder.datetv.setText(note.getModified_time());
}
#Override
public int getItemCount() {
return notes.size();
}
public class NoteViewHolder extends RecyclerView.ViewHolder{
TextView titletv ;
TextView datetv;
public NoteViewHolder(#NonNull View itemView) {
super(itemView);
titletv=(TextView) itemView.findViewById(R.id.titletv);
datetv=(TextView) itemView.findViewById(R.id.datetv);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(listener !=null && getAdapterPosition() != RecyclerView.NO_POSITION){
int position=getAdapterPosition();
listener.OnItemClick(notes.get(position));
}
}
});
}
}
Note getAt(int position){
return notes.get(position);
}
public interface OnItemClickListener{
void OnItemClick(Note note);
}
public void SetOnItemClickListener(OnItemClickListener onItemClickListener){
this.listener =onItemClickListener;
}
}
and now in your activity where you will new your adapter do this:
adapter = new NoteAdapter(notes, NoteAdapter.OnItemClickListener() {
#Override
public void OnItemClick(Note note) {
//DO WHATEVER YOU WANT HERE
}

my adapter of recycler view returning null

I am trying to use a RecyclerView with an adapter to call a specific
person. In the adapter I am using a call button and taking a reference from
PlaceCallActivity. The problem is that PlaceCallActivity is
using the above values which I can't access from the adapter. Thanks in advance for your help.
My PlaceCallActivity:
package techheromanish.example.com.videochatapp;
import com.sinch.android.rtc.calling.Call;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class PlaceCallActivity extends BaseActivity {
private Button mCallButton;
private EditText mCallName;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainn);
//initializing UI elements
//mCallName = (EditText) findViewById(R.id.callName);
mCallButton = (Button) findViewById(R.id.callButton);
//mCallButton.setEnabled(false);
//mCallButton.setOnClickListener(buttonClickListener);
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(buttonClickListener);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
// loadRecyclerViewData();
ListItem listItem = new ListItem(
R.drawable.user,
"Jawad",
"Android Developer");
listItems.add(listItem);
ListItem listItem1 = new ListItem(
R.drawable.user,
"Malik",
"Developer");
listItems.add(listItem1);
adapter = new MyAdapter(listItems, this);
recyclerView.setAdapter(adapter);
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
TextView userName = (TextView) findViewById(R.id.loggedInName);
userName.setText(getSinchServiceInterface().getUserName());
//mCallButton.setEnabled(true);
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
//to kill the current session of SinchService
private void stopButtonClicked() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finish();
}
//to place the call to the entered name
public void callButtonClicked(String user) {
//String userName = mCallName.getText().toString();
if (user.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
Call call = getSinchServiceInterface().callUserVideo(user);
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
}
private OnClickListener buttonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.callButton:
String str = MyAdapter.getStr();
Toast.makeText(PlaceCallActivity.this, "" + str, Toast.LENGTH_SHORT).show();
//callButtonClicked(str);
break;
case R.id.stopButton:
stopButtonClicked();
break;
}
}
};
}
and MyAdapter Class:
package techheromanish.example.com.videochatapp;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private static String str;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
PlaceCallActivity placeCallActivity = new PlaceCallActivity();
placeCallActivity.callButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}
In this adapter I am using button to call from PlaceCallActivity.
Please change this:
private RecyclerView.Adapter adapter;
to this:
private MyAdapter adapter;
creating an instance of an activity wouldn't make it go through its lifecycle; if the declaration of the properties which are necessary to make the code run is dependent on your activity's lifecycle then calling the method on the properly initialized activity instance should solve this.
MyAdapter class:
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private PlaceCallActivity placeCallActivity;
private static String str;
public MyAdapter(List<ListItem> listItems, Context context) {
this.listItems = listItems;
this.context = context;
// this.placeCallActivity now references the parent activity instance
this.placeCallActivity=(PlaceCallActivity)context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
placeCallActivity.callButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}
you can create an interface:
public interface CallButtonClickListener{
void onButtonClicked(String name);
}
Edit
public class PlaceCallActivity extends BaseActivity {
private Button mCallButton;
private EditText mCallName;
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
//new code
private CallButtonClickListener buttonListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainn);
//initializing UI elements
//mCallName = (EditText) findViewById(R.id.callName);
mCallButton = (Button) findViewById(R.id.callButton);
//mCallButton.setEnabled(false);
//mCallButton.setOnClickListener(buttonClickListener);
Button stopButton = (Button) findViewById(R.id.stopButton);
stopButton.setOnClickListener(buttonClickListener);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
listItems = new ArrayList<>();
// loadRecyclerViewData();
ListItem listItem = new ListItem(
R.drawable.user,
"Jawad",
"Android Developer");
listItems.add(listItem);
ListItem listItem1 = new ListItem(
R.drawable.user,
"Malik",
"Developer");
listItems.add(listItem1);
//implement the logic there
adapter = new MyAdapter(listItems, this, new CallButtonClickListener(){
#Override
public void onButtonClicked(String name){
//your code here.
}
});
recyclerView.setAdapter(adapter);
}
// invoked when the connection with SinchServer is established
#Override
protected void onServiceConnected() {
TextView userName = (TextView) findViewById(R.id.loggedInName);
userName.setText(getSinchServiceInterface().getUserName());
//mCallButton.setEnabled(true);
}
#Override
public void onDestroy() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
super.onDestroy();
}
//to kill the current session of SinchService
private void stopButtonClicked() {
if (getSinchServiceInterface() != null) {
getSinchServiceInterface().stopClient();
}
finish();
}
//to place the call to the entered name
public void callButtonClicked(String user) {
//String userName = mCallName.getText().toString();
if (user.isEmpty()) {
Toast.makeText(this, "Please enter a user to call", Toast.LENGTH_LONG).show();
return;
}
Call call = getSinchServiceInterface().callUserVideo(user);
String callId = call.getCallId();
Intent callScreen = new Intent(this, CallScreenActivity.class);
callScreen.putExtra(SinchService.CALL_ID, callId);
startActivity(callScreen);
}
private OnClickListener buttonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.callButton:
String str = MyAdapter.getStr();
Toast.makeText(PlaceCallActivity.this, "" + str, Toast.LENGTH_SHORT).show();
//callButtonClicked(str);
break;
case R.id.stopButton:
stopButtonClicked();
break;
}
}
};
}
Adapter
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private List<ListItem> listItems;
private Context context;
private static String str;
private CallButtonClickListener buttonListener;
public MyAdapter(List<ListItem> listItems, Context context, CallButtonClickListener buttonListener) {
this.listItems = listItems;
this.context = context;
this.buttonListener = buttonListner;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.list_item_view, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
final ListItem listItem = listItems.get(position);
holder.imageViewProfile.setImageResource(listItem.getImage());
holder.textViewName.setText(listItem.getName());
holder.textViewBio.setText(listItem.getBio());
/*Picasso.with(context)
.load(listItem.getImageUrl())
.into(holder.imageView);
*/
// str = listItem.getName();
holder.callButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "You Clicked " + listItem.getName(), Toast.LENGTH_SHORT).show();
buttonListener.onButtonClicked(listItem.getName());
}
});
}
#Override
public int getItemCount() {
return listItems.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewName, textViewBio;
public ImageView imageViewProfile;
public Button callButton;
ViewHolder(View itemView) {
super(itemView);
textViewName = (TextView) itemView.findViewById(R.id.textViewName);
textViewBio = (TextView) itemView.findViewById(R.id.textViewBio);
imageViewProfile = (ImageView) itemView.findViewById(R.id.imageViewProfile);
callButton = (Button) itemView.findViewById(R.id.callButton);
}
}
public static String getStr() {
return str;
}
}

Blank between item's recyclerView when scrollToPositionWithOffset with layoutManager

I have a little problem with one of my RecyclerView.
In fact, it contains another RecyclerView in each of his items, and when I tried to scroll using LinearLayoutManager on my global RecyclerView (listener onClick on row), a blank space appears between second RecyclerView's item of the first and last item.
A screen of the problem (sorry for my crappy english).
My first RecyclerView adapter :
package com.ylly.hypred.process.adapter;
/**
* Created by YLLY on 24/06/2015.
*/
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.ylly.hypred.R;
import com.ylly.hypred.custom.HypredToast;
import com.ylly.hypred.custom.MyTextView;
import com.ylly.hypred.custom.RecyclerItemClickListener;
import com.ylly.hypred.dao.Etape;
import com.ylly.hypred.dao.Produit;
import com.ylly.hypred.dao.Protocole;
import com.ylly.hypred.db.HypredDbManager;
import com.ylly.hypred.process.atelierProcess.AtelierProcessModeleUn;
import com.ylly.hypred.process.recyclerView.SpacesItemDecoration;
import org.solovyev.android.views.llm.LinearLayoutManager;
import java.util.ArrayList;
import java.util.List;
public class AdapterProtocole extends RecyclerView.Adapter<AdapterProtocole.ViewHolder> implements AdapterEtape.clickOnProductListener {
private ArrayList<Protocole> protocoleArrayList;
private Context context;
private clickOnProductListener mCallback;
public AdapterProtocole(ArrayList<Protocole> protocoleArrayList, Context context) {
this.protocoleArrayList = protocoleArrayList;
this.context = context;
}
public interface clickOnProductListener {
void appelProduit(long productId);
void ajouterAllProduit(ArrayList<Produit> produitArrayList);
void ajouterProduit(Produit produit);
}
// Create new views (invoked by the layout manager)
#Override
public AdapterProtocole.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout_process_protocole, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
View view = new View(context);
viewHolder.labelProtocoleTextView.setText(protocoleArrayList.get(position).getName());
viewHolder.produitsRecyclerView.addItemDecoration(new SpacesItemDecoration(0, 0, 0, 10));
viewHolder.produitsRecyclerView.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));
final ArrayList<Etape> fEtapeArrayList = new ArrayList<>();
Log.d("AdapterProtocole", "id des étapes du protocole " + protocoleArrayList.get(position).getName() + " = " +
protocoleArrayList.get(position).getEtapeId() + "," +
protocoleArrayList.get(position).getEtapeTwoId() + "," +
protocoleArrayList.get(position).getEtapeThreeId() + "," +
protocoleArrayList.get(position).getEtapeFourId() + "," +
protocoleArrayList.get(position).getEtapeFiveId() + "," +
protocoleArrayList.get(position).getEtapeSixId() + ".");
String test = "listes etapes dispo :";
List<Etape> etapes = HypredDbManager.getDbManager().getEtapeDbManager().getAllEtape();
for(int i=0; i<etapes.size(); i++) {
test += etapes.get(i).getId() + ",";
}
Log.d("AdapterProtocole", test);
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeId()));
}
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeTwoId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeTwoId()));
}
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeThreeId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeThreeId()));
}
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFourId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFourId()));
}
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFiveId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeFiveId()));
}
if (HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeSixId()) != null) {
fEtapeArrayList.add(HypredDbManager.getDbManager().getEtapeDbManager()
.getEtapeById(protocoleArrayList.get(position).getEtapeSixId()));
}
Log.d("AdapterProtocole", Integer.toString(fEtapeArrayList.size()));
final AdapterEtape etapeAdapter = new AdapterEtape(fEtapeArrayList, view.getContext());
etapeAdapter.setClickOnProductListener(new AdapterEtape.clickOnProductListener() {
#Override
public void appelerProduit(long produitId) {
mCallback.appelProduit(produitId);
}
#Override
public void ajouterProduitSelection(Produit produit) {
mCallback.ajouterProduit(produit);
}
});
viewHolder.produitsRecyclerView.setAdapter(etapeAdapter);
viewHolder.imageViewPanierSelectionAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ArrayList<Produit> produits = new ArrayList<>();
for (int i = 0; i < fEtapeArrayList.size(); i++) {
produits.add((fEtapeArrayList.get(i).getProduit()));
}
mCallback.ajouterAllProduit(produits);
HypredToast.makeText(context, "Produits ajoutés au panier avec succès.", Toast.LENGTH_SHORT).show();
}
});
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public MyTextView labelProtocoleTextView;
public RecyclerView produitsRecyclerView;
public ImageView imageViewPanierSelectionAll;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
labelProtocoleTextView = (MyTextView) itemLayoutView.findViewById(R.id.item_layout_protocole_label_text_view);
produitsRecyclerView = (RecyclerView) itemLayoutView.findViewById(R.id.item_layout_protocole_recycler_view);
imageViewPanierSelectionAll = (ImageView) itemLayoutView.findViewById(R.id.item_layout_process_protocole_panier_rouge);
}
}
// Return the size of your itemsData (invoked by the layout manager)
#Override
public int getItemCount() {
return protocoleArrayList.size();
}
#Override
public void appelerProduit(long produitId) {
}
public void setClickOnProductListener(clickOnProductListener callback) {
mCallback = callback;
}
#Override
public void ajouterProduitSelection(Produit produit) {
}
}
My inside RecyclerView :
package com.ylly.hypred.process.adapter;
/**
* Created by YLLY on 20/07/2015.
*/
import android.content.Context;
import android.graphics.Paint;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.Toast;
import com.ylly.hypred.R;
import com.ylly.hypred.custom.HypredToast;
import com.ylly.hypred.custom.MyTextView;
import com.ylly.hypred.dao.Etape;
import com.ylly.hypred.dao.Produit;
import com.ylly.hypred.db.HypredDbManager;
import com.ylly.hypred.process.atelierProcess.AtelierProcessModeleUn;
import java.util.ArrayList;
public class AdapterEtape extends RecyclerView.Adapter<AdapterEtape.ViewHolder> {
private ArrayList<Etape> etapeArrayList;
private Context context;
private clickOnProductListener mCallback;
public interface clickOnProductListener {
void appelerProduit(long produitId);
void ajouterProduitSelection(Produit produit);
}
public AdapterEtape(ArrayList<Etape> etapeArrayList, Context context) {
this.etapeArrayList = etapeArrayList;
this.context = context;
}
// Create new views (invoked by the layout manager)
#Override
public AdapterEtape.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout_process_etape, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(final ViewHolder viewHolder, final int position) {
// - get data from your itemsData at this position
// - replace the contents of the view with that itemsData
viewHolder.labelEtapeTextView.setText(etapeArrayList.get(position).getTexte_etape());
if(HypredDbManager.getDbManager().getProductDbManager().
getProduitById(etapeArrayList.get(position).getProduitId())!=null) {
viewHolder.labelProduitTextView
.setText(HypredDbManager.getDbManager().getProductDbManager().
getProduitById(etapeArrayList.get(position).getProduitId()).getNom_produit());
}
viewHolder.labelProduitTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.appelerProduit(etapeArrayList.get(position).getProduitId());
}
});
viewHolder.descriptifTextView.setText(etapeArrayList.get(position).getTemps() + "/" +
etapeArrayList.get(position).getConcentration() + "/" + etapeArrayList.get(position).getTemperature());
int temp = 1 + position;
if (etapeArrayList.size() == temp && etapeArrayList.get(position).getRincage()) {
viewHolder.imageViewEtapeSuivante.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.hypred_protocole_vague_finale));
} else if(etapeArrayList.get(position).getRincage()) {
viewHolder.imageViewEtapeSuivante.setImageDrawable(ContextCompat.getDrawable(context, R.drawable.hypred_protocole_vague));
}
viewHolder.imageViewPanierSelection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCallback.ajouterProduitSelection(etapeArrayList.get(position).getProduit());
HypredToast.makeText(context, "Produit ajouté au panier avec succès.", Toast.LENGTH_SHORT).show();
}
});
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public MyTextView labelEtapeTextView;
public MyTextView labelProduitTextView;
public MyTextView descriptifTextView;
public ImageView imageViewEtapeSuivante;
public ImageView imageViewPanierSelection;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
labelEtapeTextView = (MyTextView) itemLayoutView.findViewById(R.id.item_layout_etape_label_etape_text_view);
labelProduitTextView = (MyTextView) itemLayoutView.findViewById(R.id.item_layout_etape_label_produit_text_view);
descriptifTextView = (MyTextView) itemLayoutView.findViewById(R.id.item_layout_etape_descriptif_text_view);
labelProduitTextView.setPaintFlags(labelProduitTextView.getPaintFlags() | Paint.UNDERLINE_TEXT_FLAG);
imageViewEtapeSuivante = (ImageView) itemLayoutView.findViewById(R.id.item_layout_etape_vague_image_view);
imageViewPanierSelection = (ImageView) itemLayoutView.findViewById(R.id.item_layout_etape_panier_image_view);
}
}
public Etape getEtape(int position) {
Etape etape = etapeArrayList.get(position);
return etape;
}
// Return the size of your itemsData (invoked by the layout manager)
#Override
public int getItemCount() {
return etapeArrayList.size();
}
public void setClickOnProductListener(clickOnProductListener callback) {
mCallback = callback;
}
}
My function which define the Protocole RecyclerView and the rows for scrolling :
public void initProtocole(View v, final FragmentProtocoles protocoleFragment, ArrayList<Protocole> protocoleArrayList) {
super.initProtocole(v, protocoleFragment, protocoleArrayList);
initFrameLayout(v, R.id.fragment_protocole_container, R.layout.view_process_protocole_rep);
ArrayList<Protocole> fProtocoleArrayList = new ArrayList<>();
for (int i = 0; i < protocoleArrayList.size(); i++) {
fProtocoleArrayList.add(protocoleArrayList.get(i));
}
final RecyclerView recyclerView = (RecyclerView) v.findViewById(R.id.protocole_rep_recycler_view);
recyclerView.addItemDecoration(new SpacesItemDecoration(25, 25, 25, 25));
final LinearLayoutManager mLayoutManager = new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(mLayoutManager);
AdapterProtocole adapterProtocole = new AdapterProtocole(fProtocoleArrayList, v.getContext());
adapterProtocole.setClickOnProductListener(new AdapterProtocole.clickOnProductListener() {
#Override
public void appelProduit(long productId) {
protocoleFragment.appelProduit(HypredDbManager.getDbManager().getProductDbManager().getProduitById(productId));
}
#Override
public void ajouterAllProduit(ArrayList<Produit> produitArrayList) {
for (int i = 0; i < produitArrayList.size(); i++) {
SelectionManager.getInstance().addProductToSelection(produitArrayList.get(i));
}
}
#Override
public void ajouterProduit(Produit produit) {
SelectionManager.getInstance().addProductToSelection(produit);
}
});
recyclerView.setAdapter(adapterProtocole);
ImageView imageViewProtocoleFlecheGauche = (ImageView) v.findViewById(R.id.protocole_rep_fleche_gauche);
imageViewProtocoleFlecheGauche.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerViewPositionHelper recyclerViewPositionHelper = RecyclerViewPositionHelper.createHelper(recyclerView);
int firstVisibleItem = recyclerViewPositionHelper.findFirstCompletelyVisibleItemPosition();
if (firstVisibleItem != 0) {
mLayoutManager.scrollToPositionWithOffset(firstVisibleItem - 1, 0);
}
}
});
ImageView imageViewProtocoleFlecheDroite = (ImageView) v.findViewById(R.id.protocole_rep_fleche_droite);
imageViewProtocoleFlecheDroite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RecyclerViewPositionHelper recyclerViewPositionHelper = RecyclerViewPositionHelper.createHelper(recyclerView);
int lastVisibleItem = recyclerViewPositionHelper.findLastCompletelyVisibleItemPosition();
int firstVisibleItem = recyclerViewPositionHelper.findFirstCompletelyVisibleItemPosition();
if (lastVisibleItem != recyclerViewPositionHelper.getItemCount() - 1) {
mLayoutManager.scrollToPositionWithOffset(firstVisibleItem + 1, 0);
}
}
});
}
Thanks in advance :)
I also face the same problem, you need to change your RecyclerView adapter::
Now it is like this in your code::
// Create new views (invoked by the layout manager)
#Override
public AdapterEtape.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout_process_etape, null);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
You need to change like this::
// Create new views (invoked by the layout manager)
#Override
public AdapterEtape.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View itemLayoutView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_layout_process_etape, parent, false);
// create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}

Categories

Resources