Search code examples
androidandroid-recyclerviewinsert-update

notifyItemInserted() not working when inserting first item at zero index


I am trying to insert an item in recycler view at first position i.e, 0 index as below

 try {
       commentList.add(new Comment(
          Preferences.getProfileImageUrl(),
             "",                                       
               Preferences.getUserName(DONApplication.getInstance()),
               String.valueOf(Preferences.getUserId(DONApplication.getInstance())),
               response.getString("comment_id"),
               commentText
       ));
       commentAdapter.notifyItemInserted(commentList.size() - 1);                                      
     } catch (Exception e) {
         e.printStackTrace();                    
       }

but its not showing at all but when I close the window and open it again it gets visible. I don't know why it is happening. Can someone help me?


Solution

  • After waisting hours - this is what I found. Item 0 was added to the list and the screen was already showing items that were previously 0-9 now displayed the items 1-10.

    you need to scroll programmatically to position 0 in order to see the newly added item.

    I used

    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        this.recyclerView = recyclerView;
        super.onAttachedToRecyclerView(recyclerView);
    } 
    

    to get a reference to the recyclerView that is attached to the adapter(In my case I know that there is only one possible recyclerView, the javadoc states that there could be multiple ones)

    after adding item at position 0, I checked if the first visible item was 0 (I don't want to scroll if the user already scrolled down)

    private void restoreScrollPositionAfterAdAdded() {
        LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
        if (layoutManager != null) {
            int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
    
            if (firstVisibleItemPosition == 0){
                layoutManager.scrollToPosition(0);
            }
        }
    }