调用多个 JsonHttpResponseHandler 但只调用一个 onFinish

Call multiple JsonHttpResponseHandler but only one onFinish

我在我的应用程序中创建了一个布局,其中有多个复选框,一旦用户选中了一些并单击确定,我就通过 jsonHttpResponse 搜索它(每次迭代都是一个被选中的项目):

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 );

                    }
                }

            } );
        }
    } );

}

客户是:

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) {

        }
    }

}

我的目标是从该客户端获取 itemTitle 并在获取所有标题后启动一条消息,如 chatOrganizer 所示。

我的问题是,在此实现中,它进入 onFinish 的次数与迭代次数一样多,因此它会为每个项目打印此消息。

如何确保它只在所有迭代完成后才进入 onFinish?

谢谢

我认为一种解决方案是:

  • 您编写了两个处理程序,一个带有虚拟 onFinish(该方法不执行任何操作),另一个带有您当前的 onFinish 实现。
  • 检查i的索引。如果 i 不是最后一项,则将虚拟处理程序作为第二个参数传递给 client.getitems。如果 i 是最后一项,则将另一个传递给 client.getItems(...).

希望这个想法对您有所帮助=)

if (i != items.size() -1) {
  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";
                //TODO save item names
            }
        }
        @Override
        public void onFinish(int statusCode, Header[] headers, JSONObject response) {
            //DO nothing
        }
  })
} else {
  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";
                //TODO save item names
            }
        }
        @Override
        public void onFinish(int statusCode, Header[] headers, JSONObject response) {
            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" );
            ...
        }
  })
}