android - 将 Volley 调用更改为 AsyncTask
问题描述
我想更改此功能以便能够等到完成,因为当我使用它通过 API 登录时,需要一些时间才能获得答案,我的应用程序现在说登录失败,因为它不等待答案。
我知道我需要将我的类更改为 extends AsyncTask
,但我不知道如何将此函数更改为doInBackground()
,因为在每个教程中它们doInBackground
仅发送到 URL 并返回字符串,但我还需要发送到函数请求类型、正文和callbackID
。
private void createCall(int type, String url, JSONObject data, final int callback) {
JsonObjectRequest jsonRequest = new JsonObjectRequest(type, url,data,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d("Response", response.toString());
try {
callback(response, callback);
} catch (Exception e){
Log.d("API callback error", e.getMessage());
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.d("Error response", error.toString());
}
}
);
queue.add(jsonRequest);
}
我希望能够等到我从 api 调用中得到任何结果。
解决方案
如果您想冻结 UI 线程直到响应返回,那么您可以使用进度对话框而不需要使用 asynctask 。在队列中添加请求对象后,启动进度对话框。
//add the request to the queue
queue.add(jsonRequest);
//initialize the progress dialog and show it
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Fetching The File....");
progressDialog.show();
然后在收到服务器的响应后关闭对话框。
@Override
public void onResponse(String response) {
//after finishing all work
progressDialog.dismiss();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(“Volly Error”,”Error: ”+error.getLocalizedMessage());
progressDialog.dismiss();
}
});
推荐阅读
- python - psspy.report_output 未生成 txt 文件
- python - 在 Heteroskedastic gpflow 示例(多潜在 GP)中使用 VGP 而不是 SVGP 时出错
- mocha.js - 无效的柴属性 jsonschema
- material-ui - Material UI 禁用默认的 jss 类
- reactjs - 使用“npm start”运行 React 项目时出错
- sdk - 如何格式化 Visual Studio 扩展的选项(Visual Studio2019)
- javascript - 尝试导入错误:“GridActionsCellItem”未从“@mui/x-data-grid”导出
- python - 如何在 keras 功能 api 上指定 GRU 模型的输入形状?
- android - android studio上的颤振设置
- r - 为什么 ifelse 返回 NA 为假?