只调用多个 JsonHttpResponseHandler,但只有一个 onFinish。

huangapple go评论73阅读模式
英文:

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 item = MyItem.fromJson(response);
                itemNames = itemNames + item.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

英文:

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 &lt; 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() + &quot;\n&quot;;
}
}
@Override
public void onFinish() {
String TimeFormat = &quot;dd.MM.yyyy&quot;;
SimpleDateFormat df2 = new SimpleDateFormat( TimeFormat );
String dateText = df2.format( dateInMillis );
db = FirebaseFirestore.getInstance();
CollectionReference usernamedb = db.collection( &quot;Users&quot; ).document( auth.getUid() ).collection( &quot;UserData&quot; );
usernamedb.get().addOnCompleteListener( task -&gt; {
if (task.isSuccessful()) {
for (QueryDocumentSnapshot document : task.getResult()) {
String NewMessage = document.getString( &quot;username&quot; ) + &quot; wants these items: \n\n&quot; + itemNames + &quot;\nUntil &quot; + dateText + &quot;\n\nDo you confirm?&quot;;
chatOrganizer.addMessageToChat( chatID, auth.getUid(), receiverID, NewMessage, true );
}
}
} );
}
} );
}

and the client is:

public class MyitemClient {
private static final String API_BASE_URL = &quot;https://www.somesiteinhere..../&quot;;
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, &quot;utf-8&quot;), 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

答案1

得分: 0

我认为一个解决方案可以是:

  • 您编写两个处理程序,一个具有虚拟的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 保存项目名称
            }
        }

        @Override
        public void onFinish(int statusCode, Header[] headers, JSONObject response) {
            //什么都不做
        }
    });
} 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 保存项目名称
            }
        }

        @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");
            ...
        }
    });
}
英文:

I think one solution can be that:

  • You write two handlers, one with dummy onFinish (the method does nothing) and one with your current implementation onFinish.
  • Check the index of i. If i is not the last item, pass the dummy handler to client.getitems as the second parameter. If i is the last item, pass the other to client.getItems(...).

i hope that this idea is helpful =)

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() + &quot;\n&quot;;
//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() + &quot;\n&quot;;
//TODO save item names
}
}
@Override
public void onFinish(int statusCode, Header[] headers, JSONObject response) {
String TimeFormat = &quot;dd.MM.yyyy&quot;;
SimpleDateFormat df2 = new SimpleDateFormat( TimeFormat );
String dateText = df2.format( dateInMillis );
db = FirebaseFirestore.getInstance();
CollectionReference usernamedb = db.collection( &quot;Users&quot; ).document( auth.getUid() ).collection( &quot;UserData&quot; );
...
}
})
}

huangapple
  • 本文由 发表于 2020年7月31日 16:17:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/63188206.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定