【发布时间】:2020-11-25 08:12:03
【问题描述】:
我对 android studio 和改造库以及它处理数据的方式有疑问。
我想要一个简单的操作流程:
- 从服务器上的数据库请求单个项目(获取请求)
- 等待回调以确认应用已收到它
- 添加另一个请求(循环)
- 发送完所有数据后停止添加请求
我遇到的问题是我的获取结果的 onResponse 回调在我的所有请求都发送之前不会运行。那么所有的响应都是错误的。 (如果我调用单个项目(数据库中的 1 个))回调运行良好。
如何强制它发送一个请求并等到该响应再发送另一个?
循环代码
private void Pull_data_loop(int total_entries){
//int current_data_point = 0;
boolean datum_processing = false;
for (int i = 1; i <= total_entries; i++) {
Add_single_datam(i);//Call until all entries are fetched from the server
}
}
获取代码- 未运行回调需要等待此回调才能发送下一个请求
private void Add_single_datam(int id)
{
HashMap<String, String> map = new HashMap<>();
map.put("Id_request", Integer.toString(id));//The ID value
Call<Fetch_result> call = retrofitInterface.executeGet_data(map);//Run the post
call.enqueue(new Callback<Fetch_result>() {
@Override
public void onResponse(Call<Fetch_result> call, Response<Fetch_result> response) {
if (response.code() == 200)//Successful login
{
D1= response.body().getD1_String();
D2= response.body().getD2_String();
boolean result = BLE_DB.addData_Downloaded(D1, D2);//Add data
if (result == true) {
Log.d(TAG, "data_changes: Added data correctly");
}
if (result == false) {
Log.d(TAG, "data_changes: did not add data correctly");
}//false
} else if (response.code() == 404) {
Utils.toast(getApplicationContext(), "Get data fail");//Pass information to the display
}
}
@Override
public void onFailure(Call<Fetch_result> call, Throwable t) {
Utils.toast(getApplicationContext(), "Get data error");
}
});
}
注意:
我正在使用节点 js 服务器来处理我的请求。我发送 Id,它会在数据库中返回该 Id。
【问题讨论】: