RecyclerView inside RecyclerView made wrong getItemCount()

240 views Asked by At

So its to looks like this: SCREENSHOT

But when I click add or less button its returning the size of the whole list. In this case its returns 2(because the otitles.size() returns 2) Like under the item that I clicked appears another item from the list.

PARENT RecyclerView Adapter:

public class recyclercart extends RecyclerView.Adapter<recyclercart.myViewHolder> {
Context context;
ArrayList<String> list;
public static View.OnClickListener onclickup;
public static View.OnClickListener onclickdown;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oid = new ArrayList<>();
Cursor gettitle, getimage, getingridients, getdependencies,getquantities, getprices, getstartprice, getbrand, getid;
ArrayList<Integer> postoremove= new ArrayList<>();
ProgressBar progressBar;
SQLiteDatabase database;
public recyclercart(Context c, ProgressBar progressBar){
    context=c;
    this.progressBar=progressBar;
    SQLHelper helper = new SQLHelper(context);
    database = helper.getWritableDatabase();
    Cursor cursor = database.rawQuery("SELECT * FROM "+SQLHelper.DATABASE_TABLE, null);
    list =new ArrayList<>();
    cursor.moveToFirst();
    do {
        String lol = cursor.getString(cursor.getColumnIndex(SQLHelper.BRAND_NAME));
        list.add(lol.substring(0,lol.length()-5));
    }while (cursor.moveToNext());
    if(cursor.moveToLast()) {
        postoremove.clear();
        Log.d("glavniy", "LIST: " + list.toString());
        list = new ArrayList<>(removeDuplicates(list));
    }
}
@NonNull
@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.templatecart, parent, false );
    return new myViewHolder(view);
}
@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull myViewHolder holder, int position) {
    otitles.clear();
    oimages.clear();
    oingridients.clear();
    odependencies.clear();
    oprices.clear();
    oquantities.clear();
    ostartprices.clear();
    obrand.clear();
    oid.clear();
    Cursor cur = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "+SQLHelper.BRAND_NAME+" LIKE '%"+
    list.get(position)+"%'", null);
    SQLHelper helper = new SQLHelper(context);
    SQLiteDatabase database = helper.getWritableDatabase();
    gettitle = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getimage = database.rawQuery("SELECT "+SQLHelper.IMAGESRC_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getingridients = database.rawQuery("SELECT "+SQLHelper.INGRIDIENTS_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getdependencies = database.rawQuery("SELECT "+SQLHelper.DEPENDENCIES_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getprices = database.rawQuery("SELECT "+SQLHelper.PRICE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getquantities = database.rawQuery("SELECT "+SQLHelper.QUANTITY_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getstartprice = database.rawQuery("SELECT "+SQLHelper.START_PRICE+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getbrand = database.rawQuery("SELECT "+SQLHelper.BRAND_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
    getid = database.rawQuery("SELECT "+SQLHelper.KEY_ID+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
            +SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);

    if (gettitle.moveToFirst() && getimage.moveToNext() && getingridients.moveToFirst() && getdependencies.moveToFirst()
            && getprices.moveToFirst() && getquantities.moveToFirst() && getstartprice.moveToFirst() && getbrand.moveToFirst() && getid.moveToFirst()) {
        do {
            otitles.add(gettitle.getString(gettitle.getColumnIndex(SQLHelper.TITLE_NAME)));
            oimages.add(getimage.getString(getimage.getColumnIndex(SQLHelper.IMAGESRC_NAME)));
            oingridients.add(getingridients.getString(getingridients.getColumnIndex(SQLHelper.INGRIDIENTS_NAME)));
            odependencies.add(getdependencies.getString(getdependencies.getColumnIndex(SQLHelper.DEPENDENCIES_NAME)));
            oprices.add(getprices.getString(getprices.getColumnIndex(SQLHelper.PRICE_NAME)));
            oquantities.add(getquantities.getString(getquantities.getColumnIndex(SQLHelper.QUANTITY_NAME)));
            ostartprices.add(getstartprice.getString(getstartprice.getColumnIndex(SQLHelper.START_PRICE)));
            obrand.add(getbrand.getString(getbrand.getColumnIndex(SQLHelper.BRAND_NAME)));
            oid.add(getid.getString(getid.getColumnIndex(SQLHelper.KEY_ID)));
            Log.d("glavniy", String.valueOf(ostartprices));
        } while (gettitle.moveToNext() && getimage.moveToNext() && getingridients.moveToNext() && getdependencies.moveToNext()
                && getprices.moveToNext() && getquantities.moveToNext() && getstartprice.moveToNext() && getbrand.moveToNext() && getid.moveToNext());
    }
    if(gettitle.moveToLast()) {
        Log.d("glavniy", "MOVETOLAST");
        holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
        holder.recyclerView.setAdapter(new recyclerOrdersAdapter(context, otitles, oimages, oingridients, oquantities, oprices, ostartprices
                , obrand, odependencies, oid));
    }
    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("resources");
    reference.child(list.get(position)).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {
            holder.title.setText(snapshot.child("nameBrand").getValue().toString());
            Glide.with(context).load(snapshot.child("imageBrand").getValue().toString()).into(holder.imageView);
            try {
                if(recyclerSearchRecycler.timeCheck(snapshot.child("times").child("startTime").getValue().toString(),
                snapshot.child("times").child("closeTime").getValue().toString())){
                    holder.open.setText("OPEN");
                }else {holder.open.setText("CLOSED");}
            } catch (ParseException e) {
                e.printStackTrace();
            }
            reference.child(list.get(position)).child("addresses").addListenerForSingleValueEvent(new ValueEventListener() {
                @SuppressLint("SetTextI18n")
                @Override
                public void onDataChange(@NonNull DataSnapshot snapshot) {
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()){
                        ArrayList<String> addresses = new ArrayList<>();
                        addresses.add(dataSnapshot.getValue().toString());
                        Log.d("glavniy", dataSnapshot.getValue().toString());
                        if(addresses.size()==snapshot.getChildrenCount()) {
                            try {
                                float distance = activityBrandPage.getNearestRest(addresses, context);
                                Log.d("glavniy", "DIST: " + distance);
                                if (distance <= 1000) {
                                    progressBar.setVisibility(View.INVISIBLE);
                                    holder.delivery.setText("Delivery: 400 AMD");
                                } else if (distance > 1000 && distance <= 2000) {
                                    holder.delivery.setText("Delivery: 500 AMD");
                                    progressBar.setVisibility(View.INVISIBLE);
                                } else if (distance > 2000 && distance <= 3000) {
                                    holder.delivery.setText("Delivery: 600 AMD");
                                } else if (distance > 3000 && distance <= 4000) {
                                    holder.delivery.setText("Delivery: 700 AMD");
                                    progressBar.setVisibility(View.INVISIBLE);
                                }
                                if (search.prog != null) {
                                    search.prog.setVisibility(View.INVISIBLE);
                                }
                            } catch (IOException e) {
                                e.printStackTrace();
                                progressBar.setVisibility(View.VISIBLE);
                                Toast.makeText(context, "Failed, please restart", Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {

                }
            });
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });
}

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

public static class myViewHolder extends RecyclerView.ViewHolder {
    TextView title, delivery, open;
    ImageView imageView;
    public static RecyclerView recyclerView;
    public myViewHolder(@NonNull View itemView) {
        super(itemView);
        imageView=itemView.findViewById(R.id.ivBrandCart);
        recyclerView=itemView.findViewById(R.id.recyclerMainCart);
        title=itemView.findViewById(R.id.tvBrandCart);
        delivery=itemView.findViewById(R.id.tvdelivery);
        open=itemView.findViewById(R.id.opentv);
    }
}

CHILD RecyclerView Adapter:

public class recyclerOrdersAdapter extends RecyclerView.Adapter<recyclerOrdersAdapter.myViewHolder> {
public static Context context;
SQLiteDatabase database;
public static int pos;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oids = new ArrayList<>();

@SuppressLint("Recycle")
public recyclerOrdersAdapter(Context c, ArrayList<String> titles, ArrayList<String> images, ArrayList<String> ingridients,
                              ArrayList<String> quantities, ArrayList<String> prices, ArrayList<String> startprices, ArrayList<String> brands,
                             @Nullable ArrayList<String> dependencies, ArrayList<String> ids){
    System.out.println("hi");
    otitles=new ArrayList<>(titles);
    oimages= new ArrayList<>(images);
    oingridients=new ArrayList<>(ingridients);
    oquantities=new ArrayList<>(quantities);
    oprices=new ArrayList<>(prices);
    ostartprices=new ArrayList<>(startprices);
    obrand=new ArrayList<>(brands);
    oids=new ArrayList<>(ids);
    assert dependencies != null;
    odependencies=new ArrayList<>(dependencies);
    context = c;
}
@NonNull
@Override
public myViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    LayoutInflater inflater = LayoutInflater.from(context);
    View view = inflater.inflate(R.layout.templateorders, parent, false );
    return new myViewHolder(view);
}

@SuppressLint("SetTextI18n")
@Override
public void onBindViewHolder(@NonNull myViewHolder holder, int position) {
    System.out.println("hello n");
    if(obrand.size()!=0) {
        String title = otitles.get(position);
        String image = oimages.get(position);
        String ingridient = oingridients.get(position);
        String dependencie = odependencies.get(position);
        String priceik = oprices.get(position);
        String quanik = oquantities.get(position);
        ingridient = ingridient.replaceAll("[^a-zA-Z0-9, ]", "");
        if (ingridient.contains("null, ")) {
            ingridient = ingridient.replaceAll("null, ", "");
        } else if (ingridient.contains("null,")) {
            ingridient = ingridient.replaceAll("null,", "");
        } else {
            ingridient = ingridient.replaceAll("null", "");
        }
        dependencie = dependencie.replaceAll("[^a-zA-Z0-9, ]", "");

        System.out.println("ingridients " + ingridient);
        holder.title.setText(title);
        Glide.with(context).load(image).placeholder(R.drawable.elipsis).into(holder.imageView);
        holder.ingridients.setText(ingridient);
        if(odependencies.get(position)!=null) {
            holder.dependencies.setText(dependencie);
        }
        if(!priceik.contains("$")) {
            holder.price.setText(priceik + "$");
        }else {
            holder.price.setText(priceik);
        }
        holder.quantity.setText(quanik);
        holder.startprice.setText(ostartprices.get(position));
        holder.id.setText(oids.get(position));
        SQLHelper helper = new SQLHelper(context);
        database = helper.getWritableDatabase();
        holder.delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
                Log.d("glavniy", "position is" + String.valueOf(position));
                SQLHelper helper = new SQLHelper(context);
                SQLiteDatabase database = helper.getWritableDatabase();
                database.execSQL("DELETE FROM " + SQLHelper.DATABASE_TABLE + " WHERE (" + SQLHelper.KEY_ID +
                        "='" + holder.id.getText().toString() + "')");
                notifyItemRemoved(position);
                Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
            }
        });
        holder.up.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
                int o = Integer.parseInt(holder.quantity.getText().toString())+1;
                holder.quantity.setText(String.valueOf(o));
                int o1 = Integer.parseInt(holder.startprice.getText().toString()) * Integer.parseInt(holder.quantity.getText().toString());
                holder.price.setText(o1 + "$");
                Log.d("glavniy", "UPDATED");
                database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
                        + SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
                database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
                        + SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
                Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
            }
        });
        holder.down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Integer.parseInt(holder.quantity.getText().toString()) != 1) {
                    holder.quantity.setText(String.valueOf(Integer.parseInt(holder.quantity.getText().toString())-1));
                    int o1 = Integer.parseInt(holder.price.getText().toString().replace("$","")) - Integer.parseInt(holder.startprice.getText().toString());
                    holder.price.setText(o1 + "$");
                    database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
                            + SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
                    database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
                            + SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
                    Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
                }
            }
        });
    }
}

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

@SuppressLint("StaticFieldLeak")
public class myViewHolder extends RecyclerView.ViewHolder {
    public TextView title, price, ingridients, dependencies, up,down, quantity, startprice, id;
    public ImageView imageView;
    public ImageView delete;
    public myViewHolder(@NonNull View itemView) {
        super(itemView);
        
        id=itemView.findViewById(R.id.textView7);
        startprice=itemView.findViewById(R.id.textView6);
        quantity = itemView.findViewById(R.id.ordersQuanity);
        up=itemView.findViewById(R.id.upBtn);
        down=itemView.findViewById(R.id.downBtn);
        delete=itemView.findViewById(R.id.removeButton);
        title = itemView.findViewById(R.id.titleOfOrder);
        price = itemView.findViewById(R.id.priceOfOrder);
        imageView=itemView.findViewById(R.id.imageOfOrde);
        ingridients = itemView.findViewById(R.id.ingridientsOfOrder);
        dependencies = itemView.findViewById(R.id.dependenciesOfOrder);
    }
}

}

How can I make to return exactly size of list that PARENT RecyclerView sends (of that position)?

2

There are 2 answers

0
Merujan On BEST ANSWER

Ok finally I found solution. Thats pretty funny but problem was that ArrayLists were static. So I just removed static field and everything works fine now.

1
GeekAbout On

Oh... This is really hard to read. I will try to give you some tips for better architecture. I hope you are fine with it.

  1. Why are you using so many lists? Why you don't make one list of custom madr classes with all the data like title, image, ingredient itp.
  2. Why you name the type of class recyclercart instead of RecyclerCard. In Kotlin and in Java programmers have not written rule that classes should be named from big letter and in camelCase stale.
  3. The other thing is that you melted together using database and uploadung data into the view processes. It is not good. It would be better to have other class like DatabaseManager or something like this, which will make the job of taking data from the database etc. If you will do that your RecyclerViewAdapter will get list of ready items in the constructor and the only responsibility of this class will be to show the data in the views. The code will be simplified and maybe the mistake will be more visible. If you want to upload children data dynamically (during scrolling) you cab, but the code for it should be places in the DatabaseManager or Helper, too. If number of data is not big- it could be better to upload it before adapter is created even and just put Map<Item,List instead.
  4. I would also check the way of using SQLiteHelper. I am not sure, but something tells me that you are creating few databases in one program. It can be damgerous. Please, just check it. Remember to create database once and just connect to it few times. About this one I am not sure. I have to less time to investigate yourt code.

About my tips: checkout SOLID; you will have a lot more clear architecture.