GridView with infinite scroll optimization












8














I've created a simple app that fetches images from Pixabay and then displays them in a GridView with infinite scroll.



My OnScrollListener:



public class BasicOnScrollListener implements AbsListView.OnScrollListener {

private IOnScroll onScroll;

public BasicOnScrollListener(IOnScroll action) {
this.onScroll = action;
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount - visibleItemCount)
onScroll.onReachedEnd();
}
}


Code resposible for data handling:



private List<Image> images = new ArrayList<>();

....

private void init() {
this.imageAdapter = new ImageAdapter(this, images);
this.gridView.setAdapter(imageAdapter);

populateGridView();
this.gridView.setOnScrollListener(new BasicOnScrollListener(() -> {
populateGridView();
}));
}

private void populateGridView() {
if (!isLoading) {
isLoading = true;
this.progressBar.setVisibility(View.VISIBLE);
imagesRepository.getImages(currentPage, PAGE_SIZE, new IOnRepositoryDataReturn<ImagesList>() {
@Override
public void onData(ImagesList data) {
clearIfNeeded();
images.addAll(data.images);
imageAdapter.notifyDataSetChanged();
onFinish();
}

@Override
public void onError(String error) {
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}

private void clearIfNeeded() {
if (images.size() > 1000) {
images.subList(0, 300).clear();
}
}

private void onFinish() {
progressBar.setVisibility(View.INVISIBLE);
isLoading = false;
currentPage = currentPage + 1;
}
});
}
}


Everything works fine but I'd like to optimize that. When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.



The problem is, when I simply remove the first 300 items from list (as shown in clearIfNeeded() method in IOnRepositoryDataReturn implementation), the screen shifts. I no longer see items that I've seen before removal.



Example image. Situation if first row (items 1-2) from images list is removed.




  • left image - grid before removing

  • center - grid after removing (as it is for now, removing items on top shifts all items up)

  • right - how i'd like it to behave (removing items somewhere up doesnt affect what is seen)


The black square is representing the GridView.



enter image description here



I'd like to somehow adjust the viewing position in GridView, so I'd still see the same images as before removal.



Layout xml:



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/ProgressSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="@+id/GridView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/GridView" />

<GridView
android:id="@+id/GridView"
android:layout_width="match_parent"
android:layout_height="406dp"
android:layout_marginBottom="8dp"
android:numColumns="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

</GridView>




Is it even possible with Grid View or should i look for some other possibility?










share|improve this question
























  • Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
    – Cheticamp
    Nov 16 '18 at 22:05


















8














I've created a simple app that fetches images from Pixabay and then displays them in a GridView with infinite scroll.



My OnScrollListener:



public class BasicOnScrollListener implements AbsListView.OnScrollListener {

private IOnScroll onScroll;

public BasicOnScrollListener(IOnScroll action) {
this.onScroll = action;
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount - visibleItemCount)
onScroll.onReachedEnd();
}
}


Code resposible for data handling:



private List<Image> images = new ArrayList<>();

....

private void init() {
this.imageAdapter = new ImageAdapter(this, images);
this.gridView.setAdapter(imageAdapter);

populateGridView();
this.gridView.setOnScrollListener(new BasicOnScrollListener(() -> {
populateGridView();
}));
}

private void populateGridView() {
if (!isLoading) {
isLoading = true;
this.progressBar.setVisibility(View.VISIBLE);
imagesRepository.getImages(currentPage, PAGE_SIZE, new IOnRepositoryDataReturn<ImagesList>() {
@Override
public void onData(ImagesList data) {
clearIfNeeded();
images.addAll(data.images);
imageAdapter.notifyDataSetChanged();
onFinish();
}

@Override
public void onError(String error) {
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}

private void clearIfNeeded() {
if (images.size() > 1000) {
images.subList(0, 300).clear();
}
}

private void onFinish() {
progressBar.setVisibility(View.INVISIBLE);
isLoading = false;
currentPage = currentPage + 1;
}
});
}
}


Everything works fine but I'd like to optimize that. When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.



The problem is, when I simply remove the first 300 items from list (as shown in clearIfNeeded() method in IOnRepositoryDataReturn implementation), the screen shifts. I no longer see items that I've seen before removal.



Example image. Situation if first row (items 1-2) from images list is removed.




  • left image - grid before removing

  • center - grid after removing (as it is for now, removing items on top shifts all items up)

  • right - how i'd like it to behave (removing items somewhere up doesnt affect what is seen)


The black square is representing the GridView.



enter image description here



I'd like to somehow adjust the viewing position in GridView, so I'd still see the same images as before removal.



Layout xml:



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/ProgressSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="@+id/GridView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/GridView" />

<GridView
android:id="@+id/GridView"
android:layout_width="match_parent"
android:layout_height="406dp"
android:layout_marginBottom="8dp"
android:numColumns="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

</GridView>




Is it even possible with Grid View or should i look for some other possibility?










share|improve this question
























  • Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
    – Cheticamp
    Nov 16 '18 at 22:05
















8












8








8


0





I've created a simple app that fetches images from Pixabay and then displays them in a GridView with infinite scroll.



My OnScrollListener:



public class BasicOnScrollListener implements AbsListView.OnScrollListener {

private IOnScroll onScroll;

public BasicOnScrollListener(IOnScroll action) {
this.onScroll = action;
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount - visibleItemCount)
onScroll.onReachedEnd();
}
}


Code resposible for data handling:



private List<Image> images = new ArrayList<>();

....

private void init() {
this.imageAdapter = new ImageAdapter(this, images);
this.gridView.setAdapter(imageAdapter);

populateGridView();
this.gridView.setOnScrollListener(new BasicOnScrollListener(() -> {
populateGridView();
}));
}

private void populateGridView() {
if (!isLoading) {
isLoading = true;
this.progressBar.setVisibility(View.VISIBLE);
imagesRepository.getImages(currentPage, PAGE_SIZE, new IOnRepositoryDataReturn<ImagesList>() {
@Override
public void onData(ImagesList data) {
clearIfNeeded();
images.addAll(data.images);
imageAdapter.notifyDataSetChanged();
onFinish();
}

@Override
public void onError(String error) {
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}

private void clearIfNeeded() {
if (images.size() > 1000) {
images.subList(0, 300).clear();
}
}

private void onFinish() {
progressBar.setVisibility(View.INVISIBLE);
isLoading = false;
currentPage = currentPage + 1;
}
});
}
}


Everything works fine but I'd like to optimize that. When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.



The problem is, when I simply remove the first 300 items from list (as shown in clearIfNeeded() method in IOnRepositoryDataReturn implementation), the screen shifts. I no longer see items that I've seen before removal.



Example image. Situation if first row (items 1-2) from images list is removed.




  • left image - grid before removing

  • center - grid after removing (as it is for now, removing items on top shifts all items up)

  • right - how i'd like it to behave (removing items somewhere up doesnt affect what is seen)


The black square is representing the GridView.



enter image description here



I'd like to somehow adjust the viewing position in GridView, so I'd still see the same images as before removal.



Layout xml:



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/ProgressSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="@+id/GridView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/GridView" />

<GridView
android:id="@+id/GridView"
android:layout_width="match_parent"
android:layout_height="406dp"
android:layout_marginBottom="8dp"
android:numColumns="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

</GridView>




Is it even possible with Grid View or should i look for some other possibility?










share|improve this question















I've created a simple app that fetches images from Pixabay and then displays them in a GridView with infinite scroll.



My OnScrollListener:



public class BasicOnScrollListener implements AbsListView.OnScrollListener {

private IOnScroll onScroll;

public BasicOnScrollListener(IOnScroll action) {
this.onScroll = action;
}

@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}

@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount - visibleItemCount)
onScroll.onReachedEnd();
}
}


Code resposible for data handling:



private List<Image> images = new ArrayList<>();

....

private void init() {
this.imageAdapter = new ImageAdapter(this, images);
this.gridView.setAdapter(imageAdapter);

populateGridView();
this.gridView.setOnScrollListener(new BasicOnScrollListener(() -> {
populateGridView();
}));
}

private void populateGridView() {
if (!isLoading) {
isLoading = true;
this.progressBar.setVisibility(View.VISIBLE);
imagesRepository.getImages(currentPage, PAGE_SIZE, new IOnRepositoryDataReturn<ImagesList>() {
@Override
public void onData(ImagesList data) {
clearIfNeeded();
images.addAll(data.images);
imageAdapter.notifyDataSetChanged();
onFinish();
}

@Override
public void onError(String error) {
Toast.makeText(getApplicationContext(), error, Toast.LENGTH_LONG).show();
}

private void clearIfNeeded() {
if (images.size() > 1000) {
images.subList(0, 300).clear();
}
}

private void onFinish() {
progressBar.setVisibility(View.INVISIBLE);
isLoading = false;
currentPage = currentPage + 1;
}
});
}
}


Everything works fine but I'd like to optimize that. When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.



The problem is, when I simply remove the first 300 items from list (as shown in clearIfNeeded() method in IOnRepositoryDataReturn implementation), the screen shifts. I no longer see items that I've seen before removal.



Example image. Situation if first row (items 1-2) from images list is removed.




  • left image - grid before removing

  • center - grid after removing (as it is for now, removing items on top shifts all items up)

  • right - how i'd like it to behave (removing items somewhere up doesnt affect what is seen)


The black square is representing the GridView.



enter image description here



I'd like to somehow adjust the viewing position in GridView, so I'd still see the same images as before removal.



Layout xml:



<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<ProgressBar
android:id="@+id/ProgressSpinner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="@+id/GridView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="@+id/GridView" />

<GridView
android:id="@+id/GridView"
android:layout_width="match_parent"
android:layout_height="406dp"
android:layout_marginBottom="8dp"
android:numColumns="3"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">

</GridView>




Is it even possible with Grid View or should i look for some other possibility?







java android optimization gridview infinite-scroll






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 13 '18 at 17:31

























asked Nov 12 '18 at 19:05









Pan Wolodyjowsky

9011




9011












  • Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
    – Cheticamp
    Nov 16 '18 at 22:05




















  • Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
    – Cheticamp
    Nov 16 '18 at 22:05


















Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
– Cheticamp
Nov 16 '18 at 22:05






Seems a little complicated. Have you considered using weak or soft references? You could maintain your backing array of data and let the garbage collector worry about reclaiming space. There are many references on the net. Here is one.
– Cheticamp
Nov 16 '18 at 22:05














2 Answers
2






active

oldest

votes


















6





+50










When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.
Is it even possible with Grid View or should I look for some other possibility?




Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:



RecyclerView:




The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.




GridLayoutManager:




GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.




You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView






share|improve this answer































    1














    You can optimize this by:




    1. Using RecycleView + Grid Layout instead of GridView. RecycleView will help your view scroll smoothly.


    2. To reach scroll to bottom, I no longer use ScrollListener for better performance. I will provide you another option:




      • Create callback
        public interface AdapterCallback {
        void onReachLastItem();
        }

      • Call onBindViewHolder:
        @Override
        protected void onBindContentViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
        if (0 != position && position == getItemCount() - 1 && null != mCallback) {
        mCallback.onReachLastItem();
        }
        }


      • Make your fragment or activity implement AdapterCallback to load more data.









    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268545%2fgridview-with-infinite-scroll-optimization%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      6





      +50










      When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.
      Is it even possible with Grid View or should I look for some other possibility?




      Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:



      RecyclerView:




      The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.




      GridLayoutManager:




      GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.




      You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView






      share|improve this answer




























        6





        +50










        When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.
        Is it even possible with Grid View or should I look for some other possibility?




        Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:



        RecyclerView:




        The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.




        GridLayoutManager:




        GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.




        You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView






        share|improve this answer


























          6





          +50







          6





          +50



          6




          +50





          When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.
          Is it even possible with Grid View or should I look for some other possibility?




          Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:



          RecyclerView:




          The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.




          GridLayoutManager:




          GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.




          You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView






          share|improve this answer















          When there are already more than 1000 items in the GridView I'd like to remove the first 300 items, so I won't run into out of memory problems.
          Is it even possible with Grid View or should I look for some other possibility?




          Here is my 2 cents. If I understand correctly, your concern seems to be preventing OutOfMemory exceptions and improving memory usage and performance. If you implement the grid of photos using RecyclerView and GridLayoutManager, it would reduce many of your problems with memory. Your approach of trying to remove 300 items which are off screen, seems pretty cumbersome and error prone. Here is an excerpt from the official doc titled Create a List with RecyclerView:



          RecyclerView:




          The RecyclerView uses a layout manager to position the individual items on the screen and determine when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset. Recycling views in this manner improves performance by avoiding the creation of unnecessary views or performing expensive findViewById() lookups.




          GridLayoutManager:




          GridLayoutManager arranges the items in a two-dimensional grid, like the squares on a checkerboard. Using a RecyclerView with GridLayoutManager provides functionality like the older GridView layout.




          You can find many tutorials for this on quick search eg: Android GridLayoutManager with RecyclerView







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 19 '18 at 19:53

























          answered Nov 14 '18 at 23:02









          Shobhit Puri

          21.5k671102




          21.5k671102

























              1














              You can optimize this by:




              1. Using RecycleView + Grid Layout instead of GridView. RecycleView will help your view scroll smoothly.


              2. To reach scroll to bottom, I no longer use ScrollListener for better performance. I will provide you another option:




                • Create callback
                  public interface AdapterCallback {
                  void onReachLastItem();
                  }

                • Call onBindViewHolder:
                  @Override
                  protected void onBindContentViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
                  if (0 != position && position == getItemCount() - 1 && null != mCallback) {
                  mCallback.onReachLastItem();
                  }
                  }


                • Make your fragment or activity implement AdapterCallback to load more data.









              share|improve this answer


























                1














                You can optimize this by:




                1. Using RecycleView + Grid Layout instead of GridView. RecycleView will help your view scroll smoothly.


                2. To reach scroll to bottom, I no longer use ScrollListener for better performance. I will provide you another option:




                  • Create callback
                    public interface AdapterCallback {
                    void onReachLastItem();
                    }

                  • Call onBindViewHolder:
                    @Override
                    protected void onBindContentViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
                    if (0 != position && position == getItemCount() - 1 && null != mCallback) {
                    mCallback.onReachLastItem();
                    }
                    }


                  • Make your fragment or activity implement AdapterCallback to load more data.









                share|improve this answer
























                  1












                  1








                  1






                  You can optimize this by:




                  1. Using RecycleView + Grid Layout instead of GridView. RecycleView will help your view scroll smoothly.


                  2. To reach scroll to bottom, I no longer use ScrollListener for better performance. I will provide you another option:




                    • Create callback
                      public interface AdapterCallback {
                      void onReachLastItem();
                      }

                    • Call onBindViewHolder:
                      @Override
                      protected void onBindContentViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
                      if (0 != position && position == getItemCount() - 1 && null != mCallback) {
                      mCallback.onReachLastItem();
                      }
                      }


                    • Make your fragment or activity implement AdapterCallback to load more data.









                  share|improve this answer












                  You can optimize this by:




                  1. Using RecycleView + Grid Layout instead of GridView. RecycleView will help your view scroll smoothly.


                  2. To reach scroll to bottom, I no longer use ScrollListener for better performance. I will provide you another option:




                    • Create callback
                      public interface AdapterCallback {
                      void onReachLastItem();
                      }

                    • Call onBindViewHolder:
                      @Override
                      protected void onBindContentViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
                      if (0 != position && position == getItemCount() - 1 && null != mCallback) {
                      mCallback.onReachLastItem();
                      }
                      }


                    • Make your fragment or activity implement AdapterCallback to load more data.










                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 15 '18 at 4:09









                  Louis Solo

                  1162




                  1162






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53268545%2fgridview-with-infinite-scroll-optimization%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      這個網誌中的熱門文章

                      Xamarin.form Move up view when keyboard appear

                      Post-Redirect-Get with Spring WebFlux and Thymeleaf

                      Anylogic : not able to use stopDelay()