I don't think I'm implementing ListenerRegistration properly











up vote
-2
down vote

favorite












I have a chat activity that loads the 5 most recent messages of a chat room in descending order from the bottom to the top of a reversed RecyclerView using a Firebase query. Messages sent to the Firebase collection after those messages are loaded are displayed at the bottom of the screen by changing the position new list items are inserted into the list after the onEvent is called. Here is my code:



private void initRecyclerView() {

//initializes and sets adapter/resets variables


mAdapter = new ChatRecyclerViewAdapter(mMessages);
mRecyclerView.setAdapter(mAdapter);
firstEventListenerCalled = false;


final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
mRecyclerView.setLayoutManager(linearLayoutManager);


Query query = mCollection.orderBy("timestamp", Query.Direction.DESCENDING).limit(5;

firstRegistration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
Log.d("First SnapshotListener", "Called");

for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:

//Creates listener for queried messages that puts messages retrieved during initial query at end of message list,
// then another one after one runs its course that puts new ones at the beginning of the list
if (!firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);

mMessages.add(message);

mAdapter.notifyDataSetChanged();

} else if (firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);
mMessages.add(0, message);
mAdapter.notifyDataSetChanged();
Log.d(TAG, "newMessageAdded " + message.getMessage());
}


}
}

firstEventListenerCalled = true;

}
});


I am attempting to remove the ListenerRegistration in the activity's onStop() method, clear the contents of the RecyclerView in the onRestart() method, and then re-call the method above in onStart(), so that no messages come in when the activity is stopped and that any messages sent during that time appear among the 5 queried by the initRecyclerView() method when the activity is restarted:



@Override
protected void onRestart() {
super.onRestart();
mMessages.clear();
mAdapter.notifyItemRangeRemoved(0, mMessages.size());
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart Called");
initRecyclerView();

}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop Called");
firstRegistration.remove();

if (refreshRegistraton != null) {
refreshRegistraton.remove();
}
}

@Override
public void onBackPressed() {
finish();

}


However, the following happens when the activity is restarted using this strategy:




  1. The 5 queried messages appear in the proper order


  2. Any messages sent while the activity was stopped appear in addition to those 5 messages and in reverse order:




    • Old message 1


    • Old message 2


    • Old message 3


    • Old message 4


    • Old message 5


    • Message sent while stopped 2


    • Message sent while stopped 1





The new messages appear to be getting loaded in the order described for when firstEventListenerCalled == true, but it is made false at the beginning of the initRecyclerView() method every time it is called. They should not be getting loaded separately at all since I removed the listeners and totally recreated the RecyclerView. What am I missing?










share|improve this question




















  • 3




    Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
    – TheWanderer
    Nov 12 at 20:52










  • Noted for next time.
    – aedgar777
    Nov 12 at 20:53















up vote
-2
down vote

favorite












I have a chat activity that loads the 5 most recent messages of a chat room in descending order from the bottom to the top of a reversed RecyclerView using a Firebase query. Messages sent to the Firebase collection after those messages are loaded are displayed at the bottom of the screen by changing the position new list items are inserted into the list after the onEvent is called. Here is my code:



private void initRecyclerView() {

//initializes and sets adapter/resets variables


mAdapter = new ChatRecyclerViewAdapter(mMessages);
mRecyclerView.setAdapter(mAdapter);
firstEventListenerCalled = false;


final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
mRecyclerView.setLayoutManager(linearLayoutManager);


Query query = mCollection.orderBy("timestamp", Query.Direction.DESCENDING).limit(5;

firstRegistration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
Log.d("First SnapshotListener", "Called");

for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:

//Creates listener for queried messages that puts messages retrieved during initial query at end of message list,
// then another one after one runs its course that puts new ones at the beginning of the list
if (!firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);

mMessages.add(message);

mAdapter.notifyDataSetChanged();

} else if (firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);
mMessages.add(0, message);
mAdapter.notifyDataSetChanged();
Log.d(TAG, "newMessageAdded " + message.getMessage());
}


}
}

firstEventListenerCalled = true;

}
});


I am attempting to remove the ListenerRegistration in the activity's onStop() method, clear the contents of the RecyclerView in the onRestart() method, and then re-call the method above in onStart(), so that no messages come in when the activity is stopped and that any messages sent during that time appear among the 5 queried by the initRecyclerView() method when the activity is restarted:



@Override
protected void onRestart() {
super.onRestart();
mMessages.clear();
mAdapter.notifyItemRangeRemoved(0, mMessages.size());
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart Called");
initRecyclerView();

}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop Called");
firstRegistration.remove();

if (refreshRegistraton != null) {
refreshRegistraton.remove();
}
}

@Override
public void onBackPressed() {
finish();

}


However, the following happens when the activity is restarted using this strategy:




  1. The 5 queried messages appear in the proper order


  2. Any messages sent while the activity was stopped appear in addition to those 5 messages and in reverse order:




    • Old message 1


    • Old message 2


    • Old message 3


    • Old message 4


    • Old message 5


    • Message sent while stopped 2


    • Message sent while stopped 1





The new messages appear to be getting loaded in the order described for when firstEventListenerCalled == true, but it is made false at the beginning of the initRecyclerView() method every time it is called. They should not be getting loaded separately at all since I removed the listeners and totally recreated the RecyclerView. What am I missing?










share|improve this question




















  • 3




    Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
    – TheWanderer
    Nov 12 at 20:52










  • Noted for next time.
    – aedgar777
    Nov 12 at 20:53













up vote
-2
down vote

favorite









up vote
-2
down vote

favorite











I have a chat activity that loads the 5 most recent messages of a chat room in descending order from the bottom to the top of a reversed RecyclerView using a Firebase query. Messages sent to the Firebase collection after those messages are loaded are displayed at the bottom of the screen by changing the position new list items are inserted into the list after the onEvent is called. Here is my code:



private void initRecyclerView() {

//initializes and sets adapter/resets variables


mAdapter = new ChatRecyclerViewAdapter(mMessages);
mRecyclerView.setAdapter(mAdapter);
firstEventListenerCalled = false;


final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
mRecyclerView.setLayoutManager(linearLayoutManager);


Query query = mCollection.orderBy("timestamp", Query.Direction.DESCENDING).limit(5;

firstRegistration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
Log.d("First SnapshotListener", "Called");

for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:

//Creates listener for queried messages that puts messages retrieved during initial query at end of message list,
// then another one after one runs its course that puts new ones at the beginning of the list
if (!firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);

mMessages.add(message);

mAdapter.notifyDataSetChanged();

} else if (firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);
mMessages.add(0, message);
mAdapter.notifyDataSetChanged();
Log.d(TAG, "newMessageAdded " + message.getMessage());
}


}
}

firstEventListenerCalled = true;

}
});


I am attempting to remove the ListenerRegistration in the activity's onStop() method, clear the contents of the RecyclerView in the onRestart() method, and then re-call the method above in onStart(), so that no messages come in when the activity is stopped and that any messages sent during that time appear among the 5 queried by the initRecyclerView() method when the activity is restarted:



@Override
protected void onRestart() {
super.onRestart();
mMessages.clear();
mAdapter.notifyItemRangeRemoved(0, mMessages.size());
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart Called");
initRecyclerView();

}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop Called");
firstRegistration.remove();

if (refreshRegistraton != null) {
refreshRegistraton.remove();
}
}

@Override
public void onBackPressed() {
finish();

}


However, the following happens when the activity is restarted using this strategy:




  1. The 5 queried messages appear in the proper order


  2. Any messages sent while the activity was stopped appear in addition to those 5 messages and in reverse order:




    • Old message 1


    • Old message 2


    • Old message 3


    • Old message 4


    • Old message 5


    • Message sent while stopped 2


    • Message sent while stopped 1





The new messages appear to be getting loaded in the order described for when firstEventListenerCalled == true, but it is made false at the beginning of the initRecyclerView() method every time it is called. They should not be getting loaded separately at all since I removed the listeners and totally recreated the RecyclerView. What am I missing?










share|improve this question















I have a chat activity that loads the 5 most recent messages of a chat room in descending order from the bottom to the top of a reversed RecyclerView using a Firebase query. Messages sent to the Firebase collection after those messages are loaded are displayed at the bottom of the screen by changing the position new list items are inserted into the list after the onEvent is called. Here is my code:



private void initRecyclerView() {

//initializes and sets adapter/resets variables


mAdapter = new ChatRecyclerViewAdapter(mMessages);
mRecyclerView.setAdapter(mAdapter);
firstEventListenerCalled = false;


final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
mRecyclerView.setLayoutManager(linearLayoutManager);


Query query = mCollection.orderBy("timestamp", Query.Direction.DESCENDING).limit(5;

firstRegistration = query.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
Log.d("First SnapshotListener", "Called");

for (DocumentChange documentChange : queryDocumentSnapshots.getDocumentChanges()) {
switch (documentChange.getType()) {
case ADDED:

//Creates listener for queried messages that puts messages retrieved during initial query at end of message list,
// then another one after one runs its course that puts new ones at the beginning of the list
if (!firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);

mMessages.add(message);

mAdapter.notifyDataSetChanged();

} else if (firstEventListenerCalled) {

Message message = documentChange.getDocument().toObject(Message.class);
mMessages.add(0, message);
mAdapter.notifyDataSetChanged();
Log.d(TAG, "newMessageAdded " + message.getMessage());
}


}
}

firstEventListenerCalled = true;

}
});


I am attempting to remove the ListenerRegistration in the activity's onStop() method, clear the contents of the RecyclerView in the onRestart() method, and then re-call the method above in onStart(), so that no messages come in when the activity is stopped and that any messages sent during that time appear among the 5 queried by the initRecyclerView() method when the activity is restarted:



@Override
protected void onRestart() {
super.onRestart();
mMessages.clear();
mAdapter.notifyItemRangeRemoved(0, mMessages.size());
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart Called");
initRecyclerView();

}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop Called");
firstRegistration.remove();

if (refreshRegistraton != null) {
refreshRegistraton.remove();
}
}

@Override
public void onBackPressed() {
finish();

}


However, the following happens when the activity is restarted using this strategy:




  1. The 5 queried messages appear in the proper order


  2. Any messages sent while the activity was stopped appear in addition to those 5 messages and in reverse order:




    • Old message 1


    • Old message 2


    • Old message 3


    • Old message 4


    • Old message 5


    • Message sent while stopped 2


    • Message sent while stopped 1





The new messages appear to be getting loaded in the order described for when firstEventListenerCalled == true, but it is made false at the beginning of the initRecyclerView() method every time it is called. They should not be getting loaded separately at all since I removed the listeners and totally recreated the RecyclerView. What am I missing?







android firebase google-cloud-firestore






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 23:31

























asked Nov 12 at 20:51









aedgar777

5412




5412








  • 3




    Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
    – TheWanderer
    Nov 12 at 20:52










  • Noted for next time.
    – aedgar777
    Nov 12 at 20:53














  • 3




    Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
    – TheWanderer
    Nov 12 at 20:52










  • Noted for next time.
    – aedgar777
    Nov 12 at 20:53








3




3




Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
– TheWanderer
Nov 12 at 20:52




Don't re-ask the question. Edit the old one to explain why it's not a duplicate and it will be reopened if at least 5 people agree.
– TheWanderer
Nov 12 at 20:52












Noted for next time.
– aedgar777
Nov 12 at 20:53




Noted for next time.
– aedgar777
Nov 12 at 20:53












1 Answer
1






active

oldest

votes

















up vote
0
down vote













It appears that the disk persistance that is enabled by default for Android was responsible for this behavior. Turning it off got me the result I wanted.






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%2f53269912%2fi-dont-think-im-implementing-listenerregistration-properly%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    It appears that the disk persistance that is enabled by default for Android was responsible for this behavior. Turning it off got me the result I wanted.






    share|improve this answer

























      up vote
      0
      down vote













      It appears that the disk persistance that is enabled by default for Android was responsible for this behavior. Turning it off got me the result I wanted.






      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        It appears that the disk persistance that is enabled by default for Android was responsible for this behavior. Turning it off got me the result I wanted.






        share|improve this answer












        It appears that the disk persistance that is enabled by default for Android was responsible for this behavior. Turning it off got me the result I wanted.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 19 at 20:48









        aedgar777

        5412




        5412






























            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%2f53269912%2fi-dont-think-im-implementing-listenerregistration-properly%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







            Popular posts from this blog

            If I really need a card on my start hand, how many mulligans make sense? [duplicate]

            Alcedinidae

            Can an atomic nucleus contain both particles and antiparticles? [duplicate]