Each x seconds, I check for new data from a server in my Android App. If some new data is available, I need to add it to an ArrayList
only if that data is not present already in that ArrayList
.
By reading other questions similar to this, I came to understand that I need to use .contains()
on ArrayList
by overriding the .equals()
and .hashcode()
in the model.
So my model looks like this:
class Order {
String tavolo;
String ora;
@Override
public int hashCode() {
return super.hashCode();
}
@Override
public boolean equals(Object obj) {
return super.equals(obj);
}
Order(String tavolo, String ora){
this.tavolo = tavolo;
this.ora = ora;
}
public String getOra() {
return ora;
}
public String getTavolo() {
return tavolo;
}
public void setOra(String ora) {
this.ora = ora;
}
public void setTavolo(String tavolo) {
this.tavolo = tavolo;
}
}
And the method where I check if the item exists in the ArrayList
already(and if not, add it to the ArrayList
) looks like this:
public ArrayList<Order> ordini;
public void VisualOrder(){
Ion.with(getApplicationContext())
.load("GET", "https://visualorder.it/api/ordine/13/00168780351/")
.asJsonArray()
.setCallback(new FutureCallback<JsonArray>() {
@Override
public void onCompleted(Exception e, JsonArray result) {
if(result != null && result.size() > 0){
badgeOrders.setNumber(result.size());
result.forEach(ordine -> {
Order order = new Order(ordine.getAsJsonObject().get("tavolo").toString(), ordine.getAsJsonObject().get("dataora").toString());
if(!ordini.contains(order)){ // Check if order is yet in ArrayList
ordini.add(order); // if not add to ArrayList
adapterOrdini.notifyDataSetChanged();
}
});
}
}
});
}
But !ordini.contains(order)
returns true
everytime, even if I'm adding an item that already exists in the ArrayList.
So how do I add the item to ArrayList only if the item is not present already in that list?