I am making a chat app, checking if there are any new messages using a REST call. On a one second timer I am checking if the id of the last message in list is the same as the last id of newly downloaded list. If it isn't the same id (there are new messages) then update the recycerview. The problem is that it keeps on updating without any new messages and I am not sure why. Most likely it's a simple problem though i can't seem to find it.
Timer:
Timer t = new Timer();
t.schedule(new TimerTask() {
@Override
public void run() {
readMessages(myId, chatId);
}
}, 0, 1000);
REST call:
private void readMessages(String myId, String chatId) {
apiInterface = ApiClient.getClient().create(userApi.class);
Call<LinkedList<Messages>> call = apiInterface.getMessages(myId, chatId);
call.enqueue(new Callback<LinkedList<Messages>>() {
@Override
public void onResponse(Call<LinkedList<Messages>> call, Response<LinkedList<Messages>> response) {
mList.clear();
mList = response.body();
if (mList2.isEmpty() || mList2.getLast().getId().equals(mList.getLast().getId())) {
messageAdapter = new MessageAdapter(ChatActivity.this, mList, Integer.parseInt(myId));
recyclerView.setAdapter(messageAdapter);
mList2.clear();
mList2 = (LinkedList) mList.clone();
Toast.makeText(ChatActivity.this, mList2.getLast().getId(), Toast.LENGTH_SHORT).show();
}
}
@Override
public void onFailure(Call<LinkedList<Messages>> call, Throwable t) {
}
});
}
The first part of your if
statement is mList2.isEmpty()
(I assume mList
and mList2
are actually the same thing). A wild guess for a reason why each call to onResponse
passes if
the test would be that the list is actually empty. Try step-by-step debug and placing a breakpoint on the if
line to check, and if so, take a look at your REST service in order to understand why it is responding with an empty list.
So in your code what exactly is supposed to happen if the condition is not met?
If see that there is an if
statement. And let us assume we are not going into it because conditions are not met. So where is the else statement? What is the code supposed to do if the conditions don't match? As there is nothing else to be done in function, the control will return back from the function to the timer.
You can probably try putting timer inside the if statement, so it will only run when your conditions are met.
Do you think this was the problem?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.