0

so I am busy building an app that has a gallery system that pulls in pictures from Firebase. I have started my array index at 0. Please see comments for further explanation on why this error is happening.

The layout for the firebase database: Province > Event ID > Gallery > Pic Number > Pic URL

The Code for pulling in the data:

private void loadEventGalleryFromDB(final String eventName){
    DatabaseReference userEventsGFound = Constants.eventsRef.child(eventProvSelected);
    userEventsGFound.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    eventIDFound = String.valueOf(snapshot.getKey());
                    if(!eventIDFound.equals("Total Events")){
                        eventNameFound = String.valueOf(snapshot
                                .child("Festival Name")
                                .getValue());
                        if(eventNameFound.equals(eventName)){
                            DatabaseReference userEventGalleryFound = Constants.eventsRef
                                    .child(eventProvSelected)
                                    .child(eventIDFound)
                                    .child("Gallery")
                                    .child("2018");
                            userEventGalleryFound.addListenerForSingleValueEvent(new ValueEventListener() {
                                @Override
                                public void onDataChange(DataSnapshot dataSnapshot) {
                                    if (dataSnapshot.exists()) {
                                        dbSize = (int) dataSnapshot.getChildrenCount();
                                        Toast.makeText(ScreenUserViewEvent.this, "dbSize: " + dbSize, Toast.LENGTH_SHORT).show();
                                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                                            eventGalleryItem = String.valueOf(snapshot.getKey());
                                            eventGalleryItemPic = String.valueOf(snapshot.getValue());
                                            if(galleryCount == 0 && tempSize < dbSize){
                                                arrayListEventGalleryPic1.add(eventGalleryItemPic);
                                                arrayListEventGalleryItem.add(eventGalleryItem);
                                                Toast.makeText(ScreenUserViewEvent.this, "tempSize: " + tempSize, Toast.LENGTH_SHORT).show();
                                                tempSize++;
                                            }else if(galleryCount == 1 && tempSize < dbSize){
                                                arrayListEventGalleryPic2.add(eventGalleryItemPic);
                                                arrayListEventGalleryItem.add(eventGalleryItem);
                                                Toast.makeText(ScreenUserViewEvent.this, "tempSize: " + tempSize, Toast.LENGTH_SHORT).show();
                                                tempSize++;
                                            }else if(galleryCount == 2 && tempSize < dbSize){
                                                arrayListEventGalleryPic3.add(eventGalleryItemPic);
                                                arrayListEventGalleryItem.add(eventGalleryItem);
                                                Toast.makeText(ScreenUserViewEvent.this, "tempSize: " + tempSize, Toast.LENGTH_SHORT).show();
                                                tempSize++;
                                                galleryCount = -1;
                                            }
                                            galleryCount++;
                                        }
                                        recyclerViewEventGallery.setVisibility(View.VISIBLE);
                                        txtNoEventGallery.setVisibility(View.GONE);

                                        initRecyclerEventGallery();
                                    }
                                }
                                @Override
                                public void onCancelled(DatabaseError databaseError) {}
                            });
                        }
                    }
                }
            }else{
                txtNoEventGallery.setVisibility(View.VISIBLE);
                recyclerViewEventGallery.setVisibility(View.GONE);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {}
    });
}

The Code in initRecyclerEventGallery():

private void initRecyclerEventGallery(){
    layoutManagerUserEventGallery = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,false);
    recyclerViewEventGallery.setLayoutManager(layoutManagerUserEventGallery);
    adapterUserEventGallery = new AdapterRecycleUserEventGallery(arrayListEventGalleryItem,
            arrayListEventGalleryPic1,
            arrayListEventGalleryPic2,
            arrayListEventGalleryPic3,
            this);
    recyclerViewEventGallery.setAdapter(adapterUserEventGallery);
}

The code in the AdapterRecycleUserEventGallery:

public class AdapterRecycleUserEventGallery extends RecyclerView.Adapter<AdapterRecycleUserEventGallery.ViewHolder>{
private ArrayList<String> arrayListEventGalleryItemName;
private ArrayList<String> arrayListEventOptionsPic1;
private ArrayList<String> arrayListEventOptionsPic2;
private ArrayList<String> arrayListEventOptionsPic3;

private Context mContext;

String sEventOpt;

public AdapterRecycleUserEventGallery(ArrayList<String> arrayListEventGalleryItemName,
                                      ArrayList<String> arrayListEventOptionsPic1,
                                      ArrayList<String> arrayListEventOptionsPic2,
                                      ArrayList<String> arrayListEventOptionsPic3,
                                      Context mContext) {
    this.arrayListEventGalleryItemName = arrayListEventGalleryItemName;
    this.arrayListEventOptionsPic1 = arrayListEventOptionsPic1;
    this.arrayListEventOptionsPic2 = arrayListEventOptionsPic2;
    this.arrayListEventOptionsPic3 = arrayListEventOptionsPic3;

    this.mContext = mContext;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout_event_gallery, parent, false);
    return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic1.get(position)).into(holder.image1);
    Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic2.get(position)).into(holder.image2);
    Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic3.get(position)).into(holder.image3);
}

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

public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    CircleImageView image1, image2, image3;

    public ViewHolder(View itemView) {
        super(itemView);
        image1 = itemView.findViewById(R.id.imageViewUserEventItem1);
        image2 = itemView.findViewById(R.id.imageViewUserEventItem2);
        image3 = itemView.findViewById(R.id.imageViewUserEventItem3);

        image1.setOnClickListener(this);
        image2.setOnClickListener(this);
        image3.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        /*sEventOpt = arrayListEventOptions.get(getLayoutPosition());

        Intent intent = new Intent("user-event-opt-selected");
        intent.putExtra("userSelectedEventOpt", sEventOpt);

        LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);*/

    }
}

}

The error code I get:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: evolutionaryapps.festivals4u, PID: 10487
java.lang.IndexOutOfBoundsException: Index: 7, Size: 7
    at java.util.ArrayList.get(ArrayList.java:437)
    at evolutionaryapps.festivals4u.Adapters.AdapterUser.AdapterRecycleUserEventGallery.onBindViewHolder(AdapterRecycleUserEventGallery.java:54)
    at evolutionaryapps.festivals4u.Adapters.AdapterUser.AdapterRecycleUserEventGallery.onBindViewHolder(AdapterRecycleUserEventGallery.java:20)
    at android.support.v7.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:6673)
    at android.support.v7.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:6714)
    at android.support.v7.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:5647)
    at android.support.v7.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5913)
    at android.support.v7.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:285)
    at android.support.v7.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:342)
    at android.support.v7.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:358)
    at android.support.v7.widget.GapWorker.prefetch(GapWorker.java:365)
    at android.support.v7.widget.GapWorker.run(GapWorker.java:396)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6938)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)
  • At which exact line of code are you getting this error? – Alex Mamo Nov 08 '18 at 13:56
  • Possible duplicate of [What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?](https://stackoverflow.com/questions/5554734/what-causes-a-java-lang-arrayindexoutofboundsexception-and-how-do-i-prevent-it) – AlexTa Nov 08 '18 at 13:57
  • It seems like one of your `arrayListEventOptionsPic*` variables does not have an element for item 7. It's impossible for us to see why that is based on what you shared, but I'd step through your `onDataChange` in a debugger to see if it's reading all of the items you expect it to read, and putting in the right `arrayListEventOptionsPic*`. – Frank van Puffelen Nov 08 '18 at 14:05
  • Thanks for your responses. First of all I disagree strongly that is a duplicate stated by @AlexTa as I know that my index starts at 0. The issue is that I have 3 arraylists. Each bringing in information from the Firebase database. Through this I have come across that when the database does not fill up the required arraylists, it throws out the exception due to there being a lack of data to fill the whole row of images. SO for instance I have 23 images in my Database, each row has 3 images inside of it. This means that the last row won't have an image on image 3. Which is where my error is. – Shaldon Nienaber Nov 09 '18 at 06:03
  • However I have set a tempSize counter that increases each time the images are added to the arrayList where the images will be sent to the adapter to be called. And then I break out of the statement once the tempSize has reached the size limit set by dbSize = (int) dataSnapshot.getChildrenCount(); Could be possibly not breaking out of the for loop? If so, and it is only breaking out the IF statement, how do you break out the for loop straight from the IF statement? If that isn't the case, then how do I create code that makes the 24th item be Visibility.GONE if there are 23 items in the DB? – Shaldon Nienaber Nov 09 '18 at 06:09

1 Answers1

0

So I figured this out by making the following code changes:

In my Adapter class:

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    if(position > (arrayListEventGalleryItemName.size()/3)){
        holder.image1.setVisibility(View.GONE);
    }else{
        Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic1.get(position)).into(holder.image1);
    }
    if(position > (arrayListEventGalleryItemName.size()/3)){
        holder.image2.setVisibility(View.GONE);
    }else{
        Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic2.get(position)).into(holder.image2);
    }
    if(position > (arrayListEventGalleryItemName.size()/3)){
        holder.image3.setVisibility(View.GONE);
    }else{
        Glide.with(mContext).asBitmap().load(arrayListEventOptionsPic3.get(position)).into(holder.image3);
    }
}