I have a class like this:
public class ComponentMain implements Serializable {
private ArrayList<Integer> componentsIDs;
private int availableCount;
private String component_name;
private String component_desc;
and I'm using RecycleView.
In the activity the code looks like this
private List<ComponentMain> componentMains = new ArrayList<>();
recyclerView = (RecyclerView) v.findViewById(R.id.recycler_view);
mAdapter = new ComponentAdapter(getActivity(),componentMains);
recyclerView.setAdapter(mAdapter);
And I'm adding element to componentMains.
private List<Component> componentList = new ArrayList<>();
//adding data to componentList here.
String tmp = componentList.get(0).getComponent_name() ;
ArrayList<Integer> oneComponent = new ArrayList<>();
oneComponent.add(componentList.get(0).getComponent_id_Integer());
int i;
for (i = 1; i< componentList.size(); ++i) {
if(componentList.get(i).getComponent_name().equals(tmp)) {
oneComponent.add(componentList.get(i).getComponent_id_Integer());
tmp = componentList.get(i).getComponent_name();
} else {
//ArrayList<Integer> componentsIDs, String component_name, String component_desc
//
ComponentMain mainComp = new ComponentMain(oneComponent,componentList.get(i-1).getComponent_name(),componentList.get(i-1).getComponent_desc());
componentMains.add(mainComp);
oneComponent.clear();
oneComponent.add(componentList.get(i).getComponent_id_Integer());
tmp = componentList.get(i).getComponent_name();
}
}
ComponentMain mainComp = new ComponentMain(oneComponent,componentList.get(i-1).getComponent_name(),componentList.get(i-1).getComponent_desc());
componentMains.add(mainComp);
}
I'm grouping components by name and storing ArrayList of IDs for each name;
At the end I'm calling
mAdapter.notifyDataSetChanged();
The problem is after I call notifyDataSetChanged() , for every object in componentMains list, the value of componentsIDs list is same as the value of the last one in componentsMains list .
Here's the code od ComponentAdapter class
public class ComponentAdapter extends RecyclerView.Adapter<ComponentAdapter.MyViewHolder> {
private List<ComponentMain> componentList;
private Context context;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView name,description,availableCount;
public MyViewHolder(View view) {
super(view);
name = (TextView) view.findViewById(R.id.name);
description = (TextView) view.findViewById(R.id.description);
available = (TextView) view.findViewById(R.id.available);
}
}
public ComponentAdapter(Context context, List<ComponentMain> componentList) {
this.context = context;
this.componentList = componentList;
}
#Override
public ComponentAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.component_list_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final ComponentAdapter.MyViewHolder holder, int position) {
ComponentMain component = componentList.get(position);
holder.name.setText(component.getComponent_name());
holder.description.setText(component.getComponent_desc());
holder.available.setText(component.getAvailableCount()+"");
}
#Override
public int getItemCount() {
return componentList.size();
}
}
Related
I'm trying to change an ImageView in my RecyclerView. I need to change ImageView every time I click the RecyclerView. So, when I click it once it changes to a tick, then I click it again it changes again to be like the beginning, and when I click it again I want to bring up the tick like when I pressed it the first time.
public class RecyclerViewAdapter1 extends RecyclerView.Adapter<RecyclerViewAdapter1.ViewHolder> {
private LayoutInflater inflater;
private FragmentCommunication mCommunicator;
private static String LOG_TAG = "MyRecyclerViewAdapter";
private ArrayList<String> arrayList;
private ArrayList<Integer> IDList;
private ArrayList<Integer> polikhusus;
private int tekan = 0;
private GlobalClass globalVariable;
private static int lastClickedPosition = -1;// Variable to store the last clicked item position
RecyclerViewAdapter1(ArrayList<String> pintuMasuk, ArrayList<Integer> PoliID, ArrayList<Integer> poli, OnTextClickListener listener) {
this.arrayList = pintuMasuk;
this.IDList = PoliID;
this.polikhusus = poli;
this.mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View V = LayoutInflater.from(parent.getContext()).inflate(R.layout.view_poli_design, parent, false);
ViewHolder VH = new ViewHolder(V);
return VH;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private TextView PintuMasuk;
private ImageView Meme2;
private RelativeLayout ItemList3;
private int selectedIndex;
private Integer PoliID;
public ViewHolder(View itemView) {
super(itemView);
PintuMasuk = itemView.findViewById(R.id.poli);
Meme2 = itemView.findViewById(R.id.gbpoli);
ItemList3 = itemView.findViewById(R.id.item_list3);
}
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
final String PintuMasuk = arrayList.get(position);
final Integer PoliID = IDList.get(position);
final Integer poli = polikhusus.get(position);
holder.PintuMasuk.setText(PintuMasuk);
holder.ItemList3.setTag(position);
holder.Meme2.setImageResource(R.drawable.pintumasuk);
holder.ItemList3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
globalVariable = (GlobalClass) view.getContext().getApplicationContext();
globalVariable.PoliID = PoliID;
if(position != lastClickedPosition){
holder.Meme2.setImageResource(R.drawable.policheck);
Snackbar.make(view, "Anda memilih : "+PoliID+" "+PintuMasuk, Snackbar.LENGTH_SHORT).show();
Log.i(LOG_TAG," Clicked on Item " + position);
}else {
// for cancel
Snackbar.make(view, "Anda membatalkan pilihan Anda", Snackbar.LENGTH_SHORT).show();
globalVariable.PoliID = 0;
}
if (lastClickedPosition != -1)
notifyItemChanged(lastClickedPosition);
lastClickedPosition = position;
}
});
}
#Override
public int getItemCount () {
return this.arrayList.size();
}
}
enter image description here
I'm working on my code to generate the list of colors to store it in the ColorList array. Now I want to get access to the color from the ColorList array, but I dont know how I can get access to the colorList array when I have created the list in the fragement while I am using the adapter.
Here is my InboxFragement code:
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
mInboxAdapter = new InboxAdapter(getActivity(), mInbox);
int itemsCount = recyclerView.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = recyclerView.getChildAt(i);
GradientDrawable gradientDrawable = (GradientDrawable) view.findViewById(R.id.tvIcon).getBackground();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
int intColor = gradientDrawable.getColor().getDefaultColor();
String hexColor = Integer.toHexString(intColor).substring(2);
colors = "#" + hexColor;
colorList.add(index1, colors);
index1++;
}
}
recyclerView.setAdapter(mInboxAdapter);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
Here is the inboxApadater code:
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
inbox inbox = mInboxes.get(position);
holder.subject.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
int idx = holder.getAdapterPosition();
String id = mInboxes.get(idx).getId();
String color = color_list.get(idx).toString();
openEmailActivity(mailbox, id, color, short_name, subject1, from, from_email, datetime, isImportant);
}
});
Can you please show me an example how I can get access to the fragment colorList array when I am using the adapter to get the colorList array??
Thank you.
Edit: Here is my adapter:
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> {
private static final String LOG_TAG = InboxAdapter.class.getSimpleName();
private boolean reverseAllAnimations = false;
private SparseBooleanArray selectedItems;
public List<inbox> mInboxes;
public ArrayList<String> colorList;
public InboxAdapter(Context mContext, List<inbox> inboxes, List<String> colorList) {
this.mContext = mContext;
mInboxes = inboxes;
}
#Override
public InboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.recyclerview_mail_item, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
inbox inbox = mInboxes.get(position);
holder.subject.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
int idx = holder.getAdapterPosition();
String id = mInboxes.get(idx).getId();
String color = color_list.get(idx).toString();
openEmailActivity(mailbox, id, color, short_name, subject1, from, from_email, datetime, isImportant);
}
});
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvIcon;
public TextView from;
public TextView subject;
public TextView message;
public TextView time;
public ImageView iconImp;
public RelativeLayout layout1;
public ImageView attachment;
public Integer color1;
public ViewHolder(View itemView) {
super(itemView);
tvIcon = itemView.findViewById(R.id.tvIcon);
from = itemView.findViewById(R.id.from);
subject = itemView.findViewById(R.id.subject);
message = itemView.findViewById(R.id.message);
time = itemView.findViewById(R.id.time);
iconImp = itemView.findViewById(R.id.icon_star);
layout1 = itemView.findViewById(R.id.layout1);
attachment = itemView.findViewById(R.id.attachment);
}
}
private int getRandomMaterialColor(String typeColor) {
int returnColor = Color.GRAY;
int arrayId = mContext.getResources().getIdentifier("mdcolor_" + typeColor, "array", mContext.getPackageName());
if (arrayId != 0) {
TypedArray colors = mContext.getResources().obtainTypedArray(arrayId);
int index = (int) (Math.random() * colors.length());
returnColor = colors.getColor(index, Color.GRAY);
colors.recycle();
}
return returnColor;
}
public void openEmailActivity(String mailbox, String id, String color, String short_name, String subject1, String from, String from_email, String datetime, String isImportant) {
Intent intent = new Intent(mContext, MainActivity5.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra("mailbox", mailbox);
intent.putExtra("id", id);
intent.putExtra("bg_color", color);
intent.putExtra("short_name", short_name);
intent.putExtra("subject", subject1);
intent.putExtra("from_sender", from);
intent.putExtra("from_email", from_email);
intent.putExtra("datetime", datetime);
intent.putExtra("is_important", isImportant);
mContext.startActivity(intent);
}
adapter
public class InboxAdapter extends RecyclerView.Adapter<InboxAdapter.ViewHolder> {
private static final String LOG_TAG = InboxAdapter.class.getSimpleName();
private boolean reverseAllAnimations = false;
private SparseBooleanArray selectedItems;
public List<inbox> mInboxes;
public ArrayList<String> mColorList;
public InboxAdapter(Context mContext, List<inbox> inboxes, List<String> colorList) {
this.mContext = mContext;
mInboxes = inboxes;
mColorList = colorList;
}
#Override
public InboxAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context context = parent.getContext();
LayoutInflater inflater = LayoutInflater.from(context);
View contactView = inflater.inflate(R.layout.recyclerview_mail_item, parent, false);
ViewHolder viewHolder = new ViewHolder(contactView);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
inbox inbox = mInboxes.get(position);
holder.subject.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onClick(View v) {
int idx = holder.getAdapterPosition();
String id = mInboxes.get(idx).getId();
String color = mColorList.get(idx);
openEmailActivity(mailbox, id, color, short_name, subject1, from, from_email, datetime, isImportant);
}
});
}
InboxFragement
private void setupRecyclerView(#NonNull RecyclerView recyclerView) {
int itemsCount = recyclerView.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = recyclerView.getChildAt(i);
GradientDrawable gradientDrawable = (GradientDrawable) view.findViewById(R.id.tvIcon).getBackground();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
int intColor = gradientDrawable.getColor().getDefaultColor();
String hexColor = Integer.toHexString(intColor).substring(2);
colors = "#" + hexColor;
colorList.add(index1, colors);
index1++;
}
}
mInboxAdapter = new InboxAdapter(getActivity(), mInbox, colorList);
recyclerView.setAdapter(mInboxAdapter);
GridLayoutManager layoutManager = new GridLayoutManager(getContext(), 1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
}
I have recycler view in my activity and below there is a total cost field which shows the total value comes after adding the values from each row. As shown in the screen below:
In a recycler view, there is a spinner that shows quantity on selecting a value from spinner it will be multiplied by the MRP like this every same row have some values. I want to add this value and want to show it in the Lower left corner.
So far I am sending MRP value from adapter class to activity using LocalBroadcatManager class.
But every time I selecting data from another row it does not add cost with the previous value
but it replaces the older value.
Below is my code:
ProductAdapter.java
public class ProductAdapter extends RecyclerView.Adapter<ProductAdapter.ViewHolder> {
private Context context;
private List<ProductsModel> productList;
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
if (!item.equals("Select qty")) {
int qty = Integer.parseInt(item);
int cost = Integer.parseInt(model.getMrp());
int val = cost * qty;
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
SelectPack.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_pack);
fAuth = FirebaseAuth.getInstance();
ActionBar ab = getSupportActionBar();
assert ab!= null;
ab.setTitle("Select Pack");
ab.setDisplayHomeAsUpEnabled(true);
marketSpinner = findViewById(R.id.marketSpinner);
progress = findViewById(R.id.progress);
products = findViewById(R.id.products);
totalCost = findViewById(R.id.totalCost);
products.setHasFixedSize(true);
products.setLayoutManager(new LinearLayoutManager(this));
productList = new ArrayList<>();
List<String> categories = new ArrayList<String>();
categories.add("Select market");
categories.add("Crown");
categories.add("Long Book A4");
categories.add("Long Book");
categories.add("Crown Junior");
categories.add("Physics");
categories.add("Chemistry");
categories.add("Biology");
categories.add("Universal");
categories.add("Sketch Book");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, categories);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
marketSpinner.setAdapter(dataAdapter);
marketSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String item = adapterView.getItemAtPosition(i).toString();
if(item.equals("Select market")){
progress.setVisibility(View.INVISIBLE);
}
else{
getData(item);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
LocalBroadcastManager.getInstance(SelectPack.this).registerReceiver(message,new IntentFilter("msg"));
}
private void getData(String item){
progress.setVisibility(View.VISIBLE);
products.setVisibility(View.INVISIBLE);
productList.clear();
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(20, TimeUnit.SECONDS)
.readTimeout(20,TimeUnit.SECONDS)
.writeTimeout(20,TimeUnit.SECONDS)
.build();
RequestBody formBody = new FormBody.Builder()
.add("name",item)
.build();
Request request = new Request.Builder().post(formBody).url(URL).build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onResponse(#NotNull Call call, #NotNull final Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(response.body().string());
if(jsonArray.length() > 0){
products.setVisibility(View.VISIBLE);
progress.setVisibility(View.INVISIBLE);
}
for(int i=0;i<jsonArray.length();i++){
progress.setVisibility(View.INVISIBLE);
JSONObject object = jsonArray.getJSONObject(i);
String str1 = object.getString("market");
String str2 = object.getString("product_no");
String str3 = object.getString("page");
String str4 = object.getString("mrp");
String str5 = object.getString("inner_pack");
String str6 = object.getString("outer_pack");
Log.d("prod",str2);
ProductsModel model = new ProductsModel(str1,str2,str3,str4,str5,str6);
productList.add(model);
}
ProductAdapter adapter = new ProductAdapter(getApplicationContext(),productList);
products.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#Override
public void onFailure(#NotNull Call call, #NotNull final IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
progress.setVisibility(View.INVISIBLE);
products.setVisibility(View.INVISIBLE);
Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
});
}
public BroadcastReceiver message = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String nam = intent.getStringExtra("cost");
if(nam != null){
int val = Integer.parseInt(nam);
totalCost.setText("Total: "+val+".00");
}
}
};
Someone, please let me know what I am doing wrong or how should I implement it correctly. Any help would be appreciated.
THANKS
why you are using local broadcasts to communicate with activity. Instead, use interface to communicate it will be easy to use.
I found the problem when the item is getting selected you are passing the only current value not all the selected value that's why it is showing the latest value instead of all the value.
You should pass all the selected values from the list, let's say If I select one value, keep that in the separate list or you can manage with a flag in the current list object and when user selects any item then loop through that list and add all the price and pass it to activity.
Add one field in ProductsModel called Qty
Here is my updated adapter class I have added a comment as well please try this Hope it helps
public class ProductAdapter extends RecyclerView.Adapter {
private Context context;
private List<ProductsModel> productList;
// add this list
private List<ProductsModel> selectedProductList = new ArrayList();
public ProductAdapter(Context context, List<ProductsModel> productList) {
this.context = context;
this.productList = productList;
}
#NonNull
#Override
public ProductAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.selectpack_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull final ProductAdapter.ViewHolder holder, int position) {
final ProductsModel model = productList.get(position);
holder.marketName.setText(model.getMarketName());
holder.productNo.setText(model.getProductNo());
holder.page.setText(model.getPage());
holder.mrp.setText(model.getMrp());
holder.innerPack.setText(model.getInnerPack());
holder.outerPack.setText(model.getOuterPack());
List<String> qty = new ArrayList<>();
qty.add("Select qty");
qty.add("1");
qty.add("2");
qty.add("3");
qty.add("4");
qty.add("5");
qty.add("6");
qty.add("7");
qty.add("8");
qty.add("9");
qty.add("10");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_item, qty);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
holder.qtySpinner.setAdapter(dataAdapter);
holder.qtySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
int sum = 0;
String item = adapterView.getItemAtPosition(i).toString();
// add this line
adapterView.getItemAtPosition(i);
if (!item.equals("Select qty")) {
// add this line
model.setQty(Integer.parseInt(item));
selectedProductList.add(model);
}
int val = 0;
for(int j = 0; j < selectedProductList.size(); j++){
ProductsModel model = selectedProductList.get(i);
int mrp = model.getMrp();
int qty = model.getQty();
val = val + (mrp * qty);
}
holder.total.setText(String.valueOf(val));
Intent intent = new Intent("msg");
intent.putExtra("cost", String.valueOf(val));
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
#Override
public int getItemCount() {
return productList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView marketName,productNo,page,mrp,innerPack,outerPack,total;
Spinner qtySpinner;
Button order;
public ViewHolder(#NonNull View itemView) {
super(itemView);
order = itemView.findViewById(R.id.order);
qtySpinner = itemView.findViewById(R.id.qtySpinner);
marketName = itemView.findViewById(R.id.marketName);
productNo = itemView.findViewById(R.id.productNo);
page = itemView.findViewById(R.id.page);
mrp = itemView.findViewById(R.id.mrp);
innerPack = itemView.findViewById(R.id.innerPack);
outerPack = itemView.findViewById(R.id.outerPack);
total = itemView.findViewById(R.id.total);
}
}
}
I made an Adapter for my recyclerView. This adapter works when I use on any xxxActivity.java but when I try to use is on a Fragment Its hows error. Doesn't let me Pass the onClickHandler() that I created in Adapter.
I am Setting Adapter Like this -
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, mClickHandler)); //ClickListener doesn't work :'(
Another try was like --
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, getmClickHandler()));
Here, I implemented getClickHandler() in the Fragment--
public FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler getmClickHandler() {
return mClickHandler;
} //Still doesn't work :'(
and the Adapter Part--
Constructor like this-
public FixedPlaceListAdapter(Context mContext, List<PlaceBean>
placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
I tried to do this ... but still doesn't work--
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler.mClickhandler));
here is my full adapter code-
public class FixedPlaceListAdapter extends RecyclerView.Adapter<FixedPlaceListAdapter.FixedPlaceListAdapterViewHolder> {
private final FixedPlaceListAdapterOnclickHandler mClickHandler;
Context mContext;
List<PlaceBean> placeBeanList;
public FixedPlaceListAdapter(Context mContext, List<PlaceBean> placeBeanList, FixedPlaceListAdapterOnclickHandler mClickHandler) {
this.mContext = mContext;
this.placeBeanList = placeBeanList;
this.mClickHandler = mClickHandler;
}
public void setData(List<PlaceBean> placeBeanList) {
this.placeBeanList = placeBeanList;
notifyDataSetChanged();
}
#Override
public FixedPlaceListAdapterViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.top_list_single, parent, false);
return new FixedPlaceListAdapterViewHolder(view);
}
#Override
public void onBindViewHolder(FixedPlaceListAdapterViewHolder holder, int position) {
PlaceBean pb = placeBeanList.get(position);
holder.nameTextView.setText(pb.getName());
holder.addressTextView.setText(pb.getVicinity());
holder.rating.setRating(pb.getRating());
if (pb.getPhotoref() != null) {
String imageUrl = UrlsUtil.getSinglePhotoUrlString(mContext, pb.getPhotoref(), "350", "300");
Picasso.with(mContext)
.load(imageUrl)
.into(holder.thumbnailImage);
}
}
#Override
public int getItemCount() {
return placeBeanList.size();
}
public interface FixedPlaceListAdapterOnclickHandler {
void onClick(String id);
}
public class FixedPlaceListAdapterViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView nameTextView;
TextView addressTextView;
RatingBar rating;
ImageView thumbnailImage;
public FixedPlaceListAdapterViewHolder(View itemView) {
super(itemView);
nameTextView = (TextView) itemView.findViewById(R.id.place_name_now_in_list);
addressTextView = (TextView) itemView.findViewById(R.id.address_in_list);
rating = (RatingBar) itemView.findViewById(R.id.rating_single_place_in_list);
thumbnailImage = (ImageView) itemView.findViewById(R.id.place_image_thumb);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
String placeID = placeBeanList.get(getAdapterPosition()).getPlaceref();
mClickHandler.onClick(placeID);
}
}
}
Need Help!
public class CategoryNewsListAdapter extends RecyclerView.Adapter<CategoryNewsListAdapter.ViewHolder> {
private List<CategoryNews> actors = new ArrayList<>();
private Context mContext;
private Queue<List<CategoryNews>> pendingUpdates =
new ArrayDeque<>();
**public interface NewsItemClickListener {
void onNewsItemClick(int pos, CategoryNews categoryNews, ImageView shareImageView);
}**
**NewsItemClickListener newsItemClickListener;**
public CategoryNewsListAdapter(List<CategoryNews> personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final LayoutInflater inflater = LayoutInflater.from(parent.getContext());
final View view = inflater.inflate(R.layout.particular_cat_news_list_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Log.d("BusinessSubCategoryListAdapter", "Bindviewholder without payload");
final CategoryNews newsCategory = actors.get(position);
holder.news_title.setText(newsCategory.getPostTitle());
holder.news_date.setText(newsCategory.getPostDate());
holder.news_category.setText(newsCategory.getCategoryName());
holder.news_description.setText(newsCategory.getPostContent());
// GlideApp
// .with(mContext).load(newsCategory.getPostImage())
// .placeholder(R.mipmap.ic_launcher) // can also be a drawable
// .error(R.drawable.placeholder_image) // will be displayed if the image cannot be loaded
// .crossFade()
// .into(holder.news_image);
Picasso.with(mContext).load(newsCategory.getPostImage()).placeholder(R.drawable.placeholder_image).error(R.drawable.placeholder_image).into(holder.news_image);
**holder.itemView.setOnClickListener(v -> {
newsItemClickListener.onNewsItemClick(position, newsCategory, holder.news_image);
});**
}
#Override
public void onBindViewHolder(ViewHolder holder, int position, List<Object> payloads) {
if (payloads.isEmpty()) {
// if empty, do full binding;
onBindViewHolder(holder, position);
return;
}
Bundle bundle = (Bundle) payloads.get(0);
String newTitle = bundle.getString("NAME_CHANGE");
if (newTitle != null) {
// add some animation if you want
final CategoryNews actor = actors.get(position);
holder.news_title.setText(actor.getPostTitle());
holder.news_date.setText(actor.getPostDate());
holder.news_category.setText(actor.getCategoryName());
holder.news_description.setText(actor.getPostContent());
}
}
public void addItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(curSize, newItems.size());
}
public void updtateItems(List<CategoryNews> newItems) {
// record this value before making any changes to the existing list
int curSize = getItemCount();
// update the existing list
actors.addAll(newItems);
// curSize should represent the first element that got added
// newItems.size() represents the itemCount
notifyItemRangeInserted(0,newItems.size()- getItemCount()-1);
}
#Override
public int getItemCount() {
return actors.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
private TextView news_title, news_date, news_category, news_description;
private ImageView news_image;
public ViewHolder(View itemView) {
super(itemView);
news_title = (TextView) itemView.findViewById(R.id.news_title);
news_date = (TextView) itemView.findViewById(R.id.news_date);
news_category = (TextView) itemView.findViewById(R.id.news_category);
news_description = (TextView) itemView.findViewById(R.id.news_description);
news_image = (ImageView) itemView.findViewById(R.id.news_image);
}
}
}
And In your activity
implements NewsItemClickListener
create object NewsItemClickListener newsItemClickListner;
inside oncreate newsItemClickListner=this; (you mush have implemented 1)
pass that object to recyclerview.
In adapter it is received by this
public CategoryNewsListAdapter(List personList, Context mContext, NewsItemClickListener newsItemClickListener) {
this.actors.addAll(personList);
this.mContext = mContext;
this.newsItemClickListener = newsItemClickListener;
}
In your activity
CategoryNewsListAdapter categoryNewsListAdapter= new CategoryNewsListAdapter(list,this,newsItemClickListner)
After doing all this your overriden method will be called when you click in item of recycler view where you have set onclick listner
Okay .. The Problem is Fixed now ...
I was passing the wrong value or maybe the method of passing the ClickHandler was wrong.
The Solution of the Problem :
I Created another Class for ClickHandler-
public class PlaceCardClickHandler implements
FixedPlaceListAdapter.FixedPlaceListAdapterOnclickHandler,
PlaceListAdapter.PlaceListAdapterOnclickHandler {
Context mContext;
public PlaceCardClickHandler(Context mContext) {
this.mContext = mContext;
}
#Override
public void onClick(String id) {
Intent intentToStartDetail = new Intent(mContext, PlaceDetailActivity.class);
intentToStartDetail.putExtra("id", id);
mContext.startActivity(intentToStartDetail);
}
}
and the change in the Fragment was like this- (Just passed a object from the ClickHandler class)
events_recyclerview.setAdapter(new FixedPlaceListAdapter(getContext(), placelist, new PlaceCardClickHandler(getContext())));
I'm Trying to use : SimpleSectionedRecyclerViewAdapter , i have arrayList that have 30 elements with strings , i'm going to group every 10 elements with header Title ,
first item should be "Item0" with header name "First 10 elements start"
but when doing that i get :
"First 10 elements start" // header titile
"Item1" <---! note : it should "Item0"
so where is index number 0 gone?
//adapter.addItem3(CategoriesList.get(0));
List<SimpleSectionedRecyclerViewAdapter.Section> sections =
new ArrayList<SimpleSectionedRecyclerViewAdapter.Section>();
sections.add(new SimpleSectionedRecyclerViewAdapter.Section(0, "First 10 elements start"));
//Add your adapter to the sectionAdapter
SimpleSectionedRecyclerViewAdapter.Section[] dummy = new SimpleSectionedRecyclerViewAdapter.Section[sections.size()];
SimpleSectionedRecyclerViewAdapter mSectionedAdapter = new
SimpleSectionedRecyclerViewAdapter(activity, R.layout.drawer_header_book, R.id.headerName, adapter);
mSectionedAdapter.setSections(sections.toArray(dummy));
mDrawerList.setLayoutManager(new LinearLayoutManager(activity));
mDrawerList.setAdapter(mSectionedAdapter);
I'm using exactly as adapter :
https://gist.github.com/gabrielemariotti/4c189fb1124df4556058
public class DrawerItemCustomAdapterForAllBooks extends RecyclerView.Adapter<DrawerItemCustomAdapterForAllBooks.SimpleViewHolder> {
private final Context context;
Typeface custom_font;
ArrayList<Categories> mData;
private static final int TYPE_HEADER = 0;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
int BookID;
public void add(Categories s,int position) {
position = position == -1 ? getItemCount() : position;
mData.add(position,s);
notifyItemInserted(position);
}
public void remove(int position){
if (position < getItemCount() ) {
mData.remove(position);
notifyItemRemoved(position);
}
}
public DrawerItemCustomAdapterForAllBooks(Context context, ArrayList<Categories> Categories2, int BookID) {
this.mData = Categories2;
this.context = context;
this.BookID = BookID;
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/HelveticaNeueLTArabic-Light.ttf");
}
public SimpleViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
final View view = LayoutInflater.from(context).inflate(R.layout.listview_item_row, parent, false);
return new SimpleViewHolder(view);
}
#Override
public void onBindViewHolder(SimpleViewHolder holder, final int position) {
if (holder != null) {
final Categories currentItem = getItem(holder.getAdapterPosition());
SimpleViewHolder genericViewHolder = (SimpleViewHolder) holder;
genericViewHolder.position = holder.getAdapterPosition();
genericViewHolder.CategoryName.setText(currentItem.getName());
genericViewHolder.CategoryName.setTypeface(custom_font);
genericViewHolder.CategoryName.setTag(holder.getAdapterPosition());
genericViewHolder.itemView.setTag(holder.getAdapterPosition());
if (currentItem.getBookID() == 1) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_white));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_e02)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 2) {
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_openrose));
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
} else if (currentItem.getBookID() == 3) {
genericViewHolder.CategoryName.setTextColor(context.getResources().getColor(R.color.nokhba_darkrose));
genericViewHolder.itemView.setBackgroundColor(context.getResources().getColor(R.color.nokhba_white));
Picasso.with(context).load(R.drawable.list_icon_08)
.error(R.drawable.no_internet)
.tag(context)
.placeholder(R.drawable.no_spic)
.into(genericViewHolder.CategoryImage);
}
}
}
#Override
public int getItemCount() {
return mData.size()-2;
}
public Categories getItem(int position) {
return mData.get(position-1);
}
public static class SimpleViewHolder extends RecyclerView.ViewHolder {
protected TextView CategoryName;
protected ImageView CategoryImage;
protected View itemView;
int position = -1;
public SimpleViewHolder(View itemView) {
super(itemView);
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage);
// CategoryName.setTypeface(custom_font);
this.itemView = itemView;
getAdapterPosition();
this.CategoryName = (TextView) itemView.findViewById(R.id.CategoryName);
this.CategoryImage = (ImageView) itemView.findViewById(R.id.CategoryImage); }
}
}
With the library SectionedRecyclerViewAdapter you can group your items in sections and add a header to each section without worrying about the "position" of the headers:
class MySection extends StatelessSection {
String title;
List<Categories> list;
public MySection(String title, List<Categories> list) {
// call constructor with layout resources for this Section header, footer and items
super(R.layout.section_header, R.layout.section_item);
this.title = title;
this.list = list;
}
#Override
public int getContentItemsTotal() {
return list.size(); // number of items of this section
}
#Override
public RecyclerView.ViewHolder getItemViewHolder(View view) {
// return a custom instance of ViewHolder for the items of this section
return new MyItemViewHolder(view);
}
#Override
public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
MyItemViewHolder itemHolder = (MyItemViewHolder) holder;
// bind your view here
itemHolder.tvItem.setText(list.get(position).getName());
}
#Override
public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
return new SimpleHeaderViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;
// bind your header view here
headerHolder.tvItem.setText(title);
}
}
Then you set up the RecyclerView with your Sections:
// Create an instance of SectionedRecyclerViewAdapter
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();
// Create your sections with a sub list of data from mData
MySection data1Section = new MySection("First 10 elements start", categories1List);
MySection data2Section = new MySection("Elements from 10 to 20 start", categories2List);
MySection data3Section = new MySection("Elements from 20 to 30 start", categories3List);
// Add your Sections to the adapter
sectionAdapter.addSection(data1Section);
sectionAdapter.addSection(data2Section);
sectionAdapter.addSection(data3Section);
// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(sectionAdapter);