I created a layout in my app where I have multiple checkboxes and once the user checked some and clicks ok, I search it via a jsonHttpResponse (each iteration is an item that was checked):
for (int i = 0; i < items.size(); i++) {
String itemID = items.get( i ).getitemID();
MyitemClient client = new MyitemClient();
client.getitems( itemID, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
if (response != null) {
final Myitem items = Myitem.fromJson( response );
itemNames = itemNames + items.getTitle() + "\n";
}
}
@Override
public void onFinish() {
String TimeFormat = "dd.MM.yyyy";
SimpleDateFormat df2 = new SimpleDateFormat( TimeFormat );
String dateText = df2.format( dateInMillis );
db = FirebaseFirestore.getInstance();
CollectionReference usernamedb = db.collection( "Users" ).document( auth.getUid() ).collection( "UserData" );
usernamedb.get().addOnCompleteListener( task -> {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String NewMessage = document.getString( "username" ) + " wants these items: \n\n" + itemNames + "\nUntil " + dateText + "\n\nDo you confirm?";
chatOrganizer.addMessageToChat( chatID, auth.getUid(), receiverID, NewMessage, true );
}
}
} );
}
} );
}
and the client is:
public class MyitemClient {
private static final String API_BASE_URL = "https://www.somesiteinhere..../";
private AsyncHttpClient client;
public MyitemClient() {
this.client = new AsyncHttpClient();
}
public void getitems(final String query, JsonHttpResponseHandler handler) {
try {
client.get(API_BASE_URL + URLEncoder.encode(query, "utf-8"), handler);
} catch (UnsupportedEncodingException ignored) {
}
}
}
My goal is to get from that client the itemTitle and once all of the titles were obtained, to launch a message as shown in chatOrganizer.
My problem is that in this implementation it enters to onFinish as many times as the iteration and therefore it prints this message for every item.
How can I make sure that it will enter onFinish only once all of the iterations are finished?
Thank you
I think one solution can be that:
i hope that this idea is helpful =)