1

I use a RecyclerView with Posts and when the user clicks an Item, he starts a new PostDetailActivity.

I want to count the number of views for each Post ie when the user starts PostDetailActivity, I increment the views counter of my database.

The problem is : when the user starts PostDetailActivity, the views counter is updated but when he comes back to the main RecyclerView, we have a Fatal Error and the app crashes : Inconsistency detected. Invalid view holder adapter positionViewHolder

I did researches and this error happened when people added new Data, but in my case I don't add new Data, I just update a field from my database

Here's my code for the views counter (in PostDetailActivity) :

viewsCollection.document(current_user).get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
            @Override
            public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                if(task.isSuccessful()) {
                    if (!task.getResult().exists()) {
                        Map<String, Object> viewMap = new HashMap<>();
                        viewMap.put("timestamp", FieldValue.serverTimestamp());

                        viewsCollection.document(current_user).set(viewMap);
                        postDocument.update("views", FieldValue.increment(1));
                    }
                }
            }
        })

Here's my SnapShot Listener to update UI (in PostDetailActivity) :

 postDocument.addSnapshotListener(new EventListener<DocumentSnapshot>() {
            @Override
            public void onEvent(@androidx.annotation.Nullable DocumentSnapshot documentSnapshot, @androidx.annotation.Nullable FirebaseFirestoreException e) {
                if (documentSnapshot != null) {
                    if (documentSnapshot.getLong("views") != null) {
                        txtPostViews.setText((documentSnapshot.getLong("views").toString()));
                    }
                }
            }
        });

Here's my code to populate RecyclerView (in MainActivity) :

firstQuery.addSnapshotListener(new EventListener<QuerySnapshot>() {
                        @Override
                        public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                            if (e != null) {
                                Log.w("Error", "Listen failed.", e);
                                return;
                            }
                            if (queryDocumentSnapshots != null && !queryDocumentSnapshots.isEmpty()) {
                                lastVisible = queryDocumentSnapshots.getDocuments().get(queryDocumentSnapshots.size() - 1);
                                postList.clear();
                                for (DocumentChange doc : queryDocumentSnapshots.getDocumentChanges()) {
                                    if (doc.getType() == DocumentChange.Type.ADDED) {
                                        String postId = doc.getDocument().getId();
                                        Post post = doc.getDocument().toObject(Post.class).withId(postId);
                                        postList.add(post);
                                        mMainList.getRecycledViewPool().clear();
                                        forumRecyclerAdapter.notifyDataSetChanged();
                                    }
                                }
                            }
                        }
                    });

Here's the code for comeback button (in PostDetailActivity) :

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return true;
    }

Here's the LogCat :

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.XXX.XXX, PID: 19661
    java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{1409fd7 position=10 id=-1, oldPos=-1, pLpos:-1 no parent} androidx.recyclerview.widget.RecyclerView{2f14a37 VFED..... ........ 0,0-1080,1669 #7f0a00ad app:id/main_list}, adapter:com.XXX.XXX.Adapters.ForumRecyclerAdapter@2e38ba4, layout:androidx.recyclerview.widget.LinearLayoutManager@4469d0d, context:com.XXX.XXX.Activities.MainActivity@e21878f
        at androidx.recyclerview.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:5715)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:5898)
        at androidx.recyclerview.widget.GapWorker.prefetchPositionWithDeadline(GapWorker.java:286)
        at androidx.recyclerview.widget.GapWorker.flushTaskWithDeadline(GapWorker.java:343)
        at androidx.recyclerview.widget.GapWorker.flushTasksWithDeadline(GapWorker.java:359)
        at androidx.recyclerview.widget.GapWorker.prefetch(GapWorker.java:366)
        at androidx.recyclerview.widget.GapWorker.run(GapWorker.java:397)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7058)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

I would be very grateful for your help because I did a lot of researches, and i really don't understand why my app crashes...

Kolya
  • 99
  • 2
  • 10

0 Answers0