如何在适配器的RecyclerView中使用两个ArrayList。

huangapple go评论64阅读模式
英文:

How to use two arraylist in adapter recyclerview

问题

I want to use two arraylist in same adapter but I'm getting error. It is not setting the value and I'm getting INDEX OUT BOUND EXCEPTION 

This is my adapter code:

    public class packagingProductAdapter extends RecyclerView.Adapter<packagingProductAdapter.ViewHolder> {

        private List<packingProductPOJO> list_data;
       // private List<packingProductPOJO> testPOJO;

        private List<testPOJO> test_POJO;

      //  private packingProduct context;
        private testClass context;
        String product_id, category_id, quantity = "0", sizeValue = "0";
        private static int _value = 0;
        PrefManager prefManager;
        ProgressLoader progressLoader;
    /*
        public packagingProductAdapter(List<packingProductPOJO> list_data, List<testPOJO> testPOJO, packingProduct context) {
            this.list_data = list_data;
            this.test_POJO = testPOJO;
            this.context = context;
            prefManager = new PrefManager(context);
            progressLoader = new ProgressLoader(context);

        } */

        public packagingProductAdapter(List<packingProductPOJO> list_data, List<testPOJO> test_POJO, testClass context) {
            this.list_data = list_data;
            this.test_POJO = test_POJO;
            this.context = context;
            prefManager = new PrefManager(context);
            progressLoader = new ProgressLoader(context);

        }

        @Override
        public packagingProductAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.packing_product_cart_view_row,parent,false);
            return new packagingProductAdapter.ViewHolder(view);

        }

        @Override
        public void onBindViewHolder(final packagingProductAdapter.ViewHolder holder, final int position){
            final packingProductPOJO listData = list_data.get(position);
            final testPOJO test_POJO1 = test_POJO.get(position);
            holder.setIsRecyclable(false);

                if (test_POJO.equals("null")){

                holder.linearLayout.setVisibility(View.GONE);

            }else
                {

                    holder.linearLayout.setVisibility(View.VISIBLE);
                    holder.heading.setText(test_POJO1.getContact_name());
                 //   holder.linearLayout.setBackgroundResource((R.drawable.rectangleborder));

                }

            holder.produt_quantity.setText("=  " +listData.getQuantity() );

            if (listData.getProductPdf().equals("null")) {

                holder.product_name.setText(listData.getCat_name());

            }else {

                holder.product_name.setText("DOWNLOAD PDF");

            }

            product_id = listData.getProductid();
            category_id = listData.getImage();
            holder.purchaseQty.setText(listData.getUser_quantity());
            holder.pro_price.setText("Rs. " +listData.getPrice());

            final String finalPro_qty = "0";
            final String finalProduct_ID = product_id;

            holder.count_up.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // ...
                }
            });

            holder.count_down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    // ...
                }
            });

            holder.purchaseQty.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // ...
                }
            });
        }

        @Override
        public int getItemCount() {
            return  list_data.size()  + test_POJO.size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder{
            private CardView cardView;
            private TextView purchaseQty, product_name, produt_quantity, heading, pro_price;
            private ImageView     count_up, count_down;
            private LinearLayout  topview, userQuantityLayout;
            private LinearLayout linearLayout;
            public ViewHolder(View itemView) {
                super(itemView);
                heading = itemView.findViewById(R.id.heading);
                purchaseQty= itemView.findViewById(R.id.txtItemQty);
                produt_quantity= itemView.findViewById(R.id.total_qty);
                product_name=itemView.findViewById(R.id.pro_name);
                purchaseQty.setText("0");
                count_up =  itemView.findViewById(R.id.count_up);
                count_down =  itemView.findViewById(R.id.count_down);
                pro_price = itemView.findViewById(R.id.pro_price);
                cardView = itemView.findViewById(R.id.packing_card_view);
                cardView.setVisibility(View.VISIBLE);
                topview = itemView.findViewById(R.id.topview);
                topview.setVisibility(View.GONE);
                linearLayout = itemView.findViewById(R.id.linearheading);
            }
        }
    }


And this is Log error 

    E/AndroidRuntime: FATAL EXCEPTION: main
        Process: com.cls.kraftpaper, PID: 24722
        java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
            at java.util.ArrayList.get(ArrayList.java:437)
            at com.kraftpaper.handler.activity.packaging.adapter.packagingProductAdapter.onBindViewHolder(packagingProductAdapter.java:71)
            at com.kraftpaper.handler.activity.packaging.adapter.packagingProductAdapter.onBindViewHolder(packagingProductAdapter.java:27)
            at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
            at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
            // ... (more lines of the error stack trace)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)

(Note: I've only translated the code and the error message as per your request. If you have any specific questions or need further assistance, feel free to ask.)

英文:

I want to use two arraylist in same adapter but I'm getting error. It is not setting the value and I'm getting INDEX OUT BOUND EXPECTION

This is my adapter code:

public class packagingProductAdapter extends RecyclerView.Adapter&lt;packagingProductAdapter.ViewHolder&gt; {
private List&lt;packingProductPOJO&gt; list_data;
// private List&lt;packingProductPOJO&gt; testPOJO;
private List&lt;testPOJO&gt; test_POJO;
//  private packingProduct context;
private testClass context;
String product_id, category_id, quantity = &quot;0&quot;, sizeValue = &quot;0&quot;;
private static int _value = 0;
PrefManager prefManager;
ProgressLoader progressLoader;
/*
public packagingProductAdapter(List&lt;packingProductPOJO&gt; list_data, List&lt;testPOJO&gt; testPOJO, packingProduct context) {
this.list_data = list_data;
this.test_POJO = testPOJO;
this.context = context;
prefManager = new PrefManager(context);
progressLoader = new ProgressLoader(context);
} */
public packagingProductAdapter(List&lt;packingProductPOJO&gt; list_data, List&lt;testPOJO&gt; test_POJO, testClass context) {
this.list_data = list_data;
this.test_POJO = test_POJO;
this.context = context;
prefManager = new PrefManager(context);
progressLoader = new ProgressLoader(context);
}
@Override
public packagingProductAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.packing_product_cart_view_row,parent,false);
return new packagingProductAdapter.ViewHolder(view);
}
@Override
public void onBindViewHolder(final packagingProductAdapter.ViewHolder holder, final int position){
final packingProductPOJO listData = list_data.get(position);
final testPOJO test_POJO1 = test_POJO.get(position);
holder.setIsRecyclable(false);
if (test_POJO.equals(&quot;null&quot;)){
holder.linearLayout.setVisibility(View.GONE);
}else
{
holder.linearLayout.setVisibility(View.VISIBLE);
holder.heading.setText(test_POJO1.getContact_name());
//   holder.linearLayout.setBackgroundResource((R.drawable.rectangleborder));
}
holder.produt_quantity.setText(&quot;=  &quot; +listData.getQuantity() );
if (listData.getProductPdf().equals(&quot;null&quot;)) {
holder.product_name.setText(listData.getCat_name());
}else {
holder.product_name.setText(&quot;DOWNLOAD PDF&quot;);
}
// holder.heading.setText(listData.getImage());
product_id = listData.getProductid();
category_id = listData.getImage();
holder.purchaseQty.setText(listData.getUser_quantity());
holder.pro_price.setText(&quot;Rs. &quot; +listData.getPrice());
final String finalPro_qty = &quot;0&quot;;
final String finalProduct_ID = product_id;
holder.count_up.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String removeProductId = listData.getId();
String removeQuantity = listData.getUser_quantity();
int quantity = 0;
try{
quantity  = Integer.parseInt(removeQuantity) + 1;
} catch(NumberFormatException ex){ // handle your exception
ex.printStackTrace();
}
if (quantity &gt; Integer.parseInt(listData.getQuantity())){
Toast.makeText(context, &quot;Insufficent Stock &quot;, Toast.LENGTH_LONG).show();
}else {
//     context.add(&quot;pk@gmail.com&quot;, String.valueOf(quantity), finalProduct_ID, &quot;manual&quot;, category_id, holder.purchaseQty, position, &quot;0&quot;);
}
}
});
holder.count_down.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String removeProductId = listData.getId();
String removeQuantity = listData.getUser_quantity();
final int quantity = Integer.valueOf(removeQuantity) - 1;
//   context.add(&quot;pk@gmail.com&quot;, String.valueOf(quantity), finalProduct_ID, &quot;manual&quot;, category_id, holder.purchaseQty, position, &quot;0&quot;);
}
});
holder.purchaseQty.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// get alert_dialog.xml view
LayoutInflater li = LayoutInflater.from(context);
View promptsView = li.inflate(R.layout.alert_dialog, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
// set alert_dialog.xml to alertdialog builder
alertDialogBuilder.setView(promptsView);
final EditText userSize = (EditText) promptsView.findViewById(R.id.etUserInput);
final TextView enterQuantity = promptsView.findViewById(R.id.enterQuantity);
// set dialog message
alertDialogBuilder
.setCancelable(false)
.setPositiveButton(&quot;OK&quot;, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//  Toast.makeText(context, &quot;Entered: &quot;+userInput.getText().toString(), Toast.LENGTH_LONG).show();
final String quantityValue = (userSize.getText().toString());
if (TextUtils.isEmpty(quantityValue)) {
userSize.setError(&quot;Quantity cannot be Empty&quot;);
Toast.makeText(context, &quot;Quantity cannot be Empty&quot;, Toast.LENGTH_LONG).show();
userSize.requestFocus();
return;
}
final int quantity = Integer.valueOf(quantityValue);
if (quantity &gt; Integer.parseInt(listData.getQuantity())){
Toast.makeText(context, &quot;Insufficent Stock &quot;, Toast.LENGTH_LONG).show();
}else {
//    context.add(&quot;pk@gmail.com&quot;, String.valueOf(quantity), finalProduct_ID, &quot;manual&quot;, category_id, holder.purchaseQty, position, sizeValue);
}
}
})
.setNegativeButton(&quot;Cancel&quot;,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
});
}
@Override
public int getItemCount() {
return  list_data.size()  + test_POJO.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private CardView cardView;
private TextView purchaseQty, product_name, produt_quantity, heading, pro_price;
private ImageView     count_up, count_down;
private LinearLayout  topview, userQuantityLayout;
private LinearLayout linearLayout;
public ViewHolder(View itemView) {
super(itemView);
heading = itemView.findViewById(R.id.heading);
purchaseQty= itemView.findViewById(R.id.txtItemQty);
produt_quantity= itemView.findViewById(R.id.total_qty);
product_name=itemView.findViewById(R.id.pro_name);
purchaseQty.setText(&quot;0&quot;);
count_up =  itemView.findViewById(R.id.count_up);
count_down =  itemView.findViewById(R.id.count_down);
pro_price = itemView.findViewById(R.id.pro_price);
cardView = itemView.findViewById(R.id.packing_card_view);
cardView.setVisibility(View.VISIBLE);
//            purchaseQty.setBackground(context.getResources().getDrawable(R.drawable.rectangleborder));
topview = itemView.findViewById(R.id.topview);
topview.setVisibility(View.GONE);
linearLayout = itemView.findViewById(R.id.linearheading);
}
}
}

And this is Log error

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.cls.kraftpaper, PID: 24722
java.lang.IndexOutOfBoundsException: Index: 3, Size: 3
at java.util.ArrayList.get(ArrayList.java:437)
at com.kraftpaper.handler.activity.packaging.adapter.packagingProductAdapter.onBindViewHolder(packagingProductAdapter.java:71)
at com.kraftpaper.handler.activity.packaging.adapter.packagingProductAdapter.onBindViewHolder(packagingProductAdapter.java:27)
at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
at android.view.View.measure(View.java:24845)
at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1472)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:221)
at android.widget.ScrollView.onMeasure(ScrollView.java:498)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:221)
at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:143)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:221)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1552)
at android.widget.LinearLayout.measureVertical(LinearLayout.java:842)
at android.widget.LinearLayout.onMeasure(LinearLayout.java:721)
at android.view.View.measure(View.java:24845)
at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6908)
at com.android.internal.policy.DecorView.measureChildWithMargins(DecorView.java:3029)
at android.widget.FrameLayout.onMeasure(FrameLayout.java:221)
at com.android.internal.policy.DecorView.onMeasure(DecorView.java:863)
at android.view.View.measure(View.java:24845)
at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:3218)
at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:2004)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2296)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1888)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7908)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:1101)
at android.view.Choreographer.doCallbacks(Choreographer.java:917)
at android.view.Choreographer.doFrame(Choreographer.java:847)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:1086)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:230)
at android.app.ActivityThread.main(ActivityThread.java:7778)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:526)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1034)

Here I have added the logcat. I'm getting the result is there.

答案1

得分: 1

因为这段代码而导致这个问题:

@Override
public int getItemCount() {
return  list_data.size()  + test_POJO.size();
}

你在返回两个列表的元素总和:
例如,假设你返回:return 3 + 3 // 总计 = 6

但是你还试图在以下位置访问各个列表:

@Override
public void onBindViewHolder(final packagingProductAdapter.ViewHolder holder, final int position){
final packingProductPOJO listData = list_data.get(position); 
final testPOJO test_POJO1 = test_POJO.get(position); 

随着你滚动列表,位置会增加6次,这是两个列表getItemCount()的总和,这将引发java.lang.IndexOutOfBoundsException: Index: 3, Size: 3错误。

尝试只返回其中一个列表的大小:

@Override
public int getItemCount() {
return  list_data.size();
}
英文:

That is because of this code:

@Override
public int getItemCount() {
return  list_data.size()  + test_POJO.size();
}

You are returning the sum of both lists:
For Eg let say you are returning: return 3 + 3 // total = 6

But also you are trying to access individual list in :

@Override
public void onBindViewHolder(final packagingProductAdapter.ViewHolder holder, final int position){
final packingProductPOJO listData = list_data.get(position); 
final testPOJO test_POJO1 = test_POJO.get(position); 

The position will increment as you scroll at list 6 times which is the total sum of the two lists getItemCount(), which will trow java.lang.IndexOutOfBoundsException: Index: 3, Size: 3

Try to return the size of only one of the lists:

@Override
public int getItemCount() {
return  list_data.size();
}

答案2

得分: 1

你在getItemCount()方法中的代码如下:

@Override
public int getItemCount() {
    return list_data.size() + test_POJO.size();
}

你返回了两个不同数组的大小。onBindViewHolder()方法有一个position变量。这个变量表示项目的位置,其范围是 0 到 getItemCount()

onBindViewHolder()方法中,你有以下代码:

final packingProductPOJO listData = list_data.get(position);
final testPOJO test_POJO1 = test_POJO.get(position);

你的getItemCount()方法返回了两个不同数组的大小,但你尝试访问相同的位置。这是异常的原因。如果数组大小相同,你可以使用以下代码:

@Override
public int getItemCount() {
    return list_data.size();
}

但如果不相同,你可以这样做:

@Override
public int getItemCount() {
    return Math.max(list_data.size(), test_POJO.size());
}

onBindViewHolder()方法中:

if (list_data.size() >= position) {
    list_data.get(0);
} else {
    list_data.get(position);
}

if (test_POJO.size() >= position) {
    list_data.get(0);
} else {
    test_POJO.get(position);
}

但这不是一个好的方式。

英文:

Your code inside the getItemCount() method is

@Override
public int getItemCount() {
return  list_data.size()  + test_POJO.size();
}

You returning 2 different array's size. onBindViewHolder() method has position variable. This variable gives item position and this position's range is 0..getItemCount().

In onBindViewHolder() method you have this code

    final packingProductPOJO listData = list_data.get(position);
final testPOJO test_POJO1 = test_POJO.get(position);

Your getItemCount() method returning two different array's size but you trying access same position. This is Exception's cause. If the arrays size's are the same you can use this

@Override
public int getItemCount() {
return  list_data.size();
}

But if not you can do this:

@Override
public int getItemCount() {
return  Math.max(list_data.size(), test_POJO.size());
}

in onBindViewHolderMethod()

    if (list_data.size() &gt;= position) list_data.get(0);
else list_data.get(position);
if (test_POJO.size() &gt;= position) list_data.get(0);
else test_POJO.get(possition);

But this is not the good way

答案3

得分: 0

尝试这样做。

@Override
public int getItemCount() {
return min(list_data.size(), test_POJO.size());
}

这将解决当前的问题。但你会发现RecyclerView中有一些数据丢失。

英文:

Try this.

@Override
public int getItemCount() {
return  min(list_data.size(), test_POJO.size());
}

It will resolve current issue. But you'll find some data missing from RecyclerView.

答案4

得分: 0

如果这些列表包含相似的元素,您可以将它们合并,然后将它们作为适配器中的一个列表使用,这样做可以避免各种麻烦。

List<PojoClass> combined = new ArrayList<>();
combined.addAll(firstList);
combined.addAll(secondList);
英文:

If the lists, contain similar elements, you could combine them and then use them as one list in the adapter, you will avoid all sorts of hassles if you do that.

List&lt;PojoClass&gt; combined = new ArrayList&lt;&gt;();
combined.addAll(firstList);
combined.addAll(secondList);

huangapple
  • 本文由 发表于 2020年10月7日 12:24:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/64237188.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定