[英]Android: get result from callback (networking KOUSH ION)
For my app I need to contact our API from our server which returns some JSON. 对于我的应用程序,我需要从我们的服务器联系我们的API,它返回一些JSON。
While downloading the JSON, it should display a progressbar. 下载JSON时,它应显示进度条。
I figured I should use Android's AsyncTask
to handle the GUI while doing network operations, so I wrote the following within my Activity
: 我想我应该在进行网络操作时使用Android的AsyncTask
来处理GUI,所以我在我的Activity
编写了以下内容:
class DownloadManager extends AsyncTask<String, Void, Boolean> {
@Override
protected void onPreExecute() {
super.onPreExecute();
mLoadingSpinner.setVisibility(View.VISIBLE);
}
@Override
protected Boolean doInBackground(String... params) {
String id = params[0];
downloadUtility.getId(id);
return true;
}
@Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
mLoadingSpinner.setVisibility(View.INVISIBLE);
}
}
Basically, onPreExecute
shows the loading spinner, the doInBackGround
downloads some JSON, and onPostExecute
stops the spinner. 基本上, onPreExecute
显示加载微调器, doInBackGround
下载一些JSON, onPostExecute
停止微调器。
The question is, within the downloadUtility.getId(id)
I need to either: 问题是,在downloadUtility.getId(id)
我需要:
The code for the getId
: getId
的代码:
public Future getId(final String id) {
// set url
String url = IPAddress.PRODUCTION + Variables.get_id+ id;
downloading = Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
//try catch here for null getHeaders
if (response != null) {
if (response.getHeaders().code() == 200) {
//SUCCESS !! Open new intent!
} else {
//FAIL!! Show TOAST!
}
}
}
});
return downloading;
}
As you can see, I'm returning a future object. 如你所见,我正在返回一个未来的对象。 How do I know from the future object if the onCompleted
(void) either gave a success or fail, so I can handle the result (success: open new intent, fail: toast) in the asynctask? 如果onCompleted
(void)成功或失败,我怎么知道未来的对象,所以我可以在asynctask中处理结果(成功:打开新意图,失败:toast)?
Here you are running one asynctask inside another asyctask this is not a proper way you can call your getId method directly in your activity it won't be required another asynctask because the following code it self a asynctask. 在这里你运行一个asynctask在另一个asyctask中这不是一个正确的方法你可以直接在你的活动中调用你的getId方法它将不需要另一个asynctask因为下面的代码它自己asynctask。
downloading = Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
//try catch here for null getHeaders
if (response != null) {
if (response.getHeaders().code() == 200) {
//SUCCESS !! Open new intent!
} else {
//FAIL!! Show TOAST!
}
}
}
});
//Add new Answer //添加新答案
If you want to separate entire download code from your activity then you can create custom callBack in your download Utility class. 如果要从活动中分离整个下载代码,则可以在下载Utility类中创建自定义callBack。 It will acts like a communicator between activity and your Download class. 它将像活动和下载类之间的沟通者。 I just give a way to do this task on bellow. 我只是想在波纹管上完成这项任务。
DownloadUtility class seams look like bellow DownloadUtility类接缝看起来像吼叫
public class DownloadUtility {
//DO Your all other Stuff
/**
* Custom Callback
*/
public interface customCallBack {
void onCompleted(Exception e, Response<JsonObject> response);
}
/**
* Your getID code
*
* @param context
* @param id
* @param mLoadingSpinner
* @param callBack
*/
public static void getId(Activity context,final String id, Spinner mLoadingSpinner, final customCallBack callBack) {
// set url
mLoadingSpinner.setVisibility(View.VISIBLE);
String url = IPAddress.PRODUCTION + Variables.get_id + id;
downloading = Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
mLoadingSpinner.setVisibility(View.GONE);
if(callBack != null)
callBack.onCompleted(e,response);
}
}
});
}
} }
make a call on your Activity 打电话给你的活动
DownloadUtility.getId(this, "ID", spinnerObj, new DownloadUtility.customCallBack() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
if (response != null) {
if (response.getHeaders().code() == 200) {
//SUCCESS !! Open new intent!
} else {
//FAIL!! Show TOAST!
}
}
}); });
I don't think that you need AsyncTask for network operation because your ion library is already using asynctask internally. 我不认为您需要AsyncTask进行网络操作,因为您的离子库已在内部使用asynctask。 you can do like this 你可以这样做
mLoadingSpinner.setVisibility(View.VISIBLE);
downloading = Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
//try catch here for null getHeaders
if (response != null) {
if (response.getHeaders().code() == 200) {
//SUCCESS !! Open new intent!
mLoadingSpinner.setVisibility(View.INVISIBLE);
} else {
mLoadingSpinner.setVisibility(View.INVISIBLE);
}
}
}
});
return downloading;
let me know if some issue. 如果有问题请告诉我。
In my opinion the cleanest solution is to create a service that handles the dirty download logic and returns a future of your custom response class, that contains the success info and the json object. 在我看来,最干净的解决方案是创建一个处理脏下载逻辑的服务,并返回自定义响应类的未来,其中包含成功信息和json对象。
// in e.g JsonResponse.java
public class JsonResponse() {
public boolean ok;
public JsonObject json;
}
// in Service.java
public Future<JsonResponse> getId(final String id) {
final SimpleFuture<JsonResponse> jsonFuture = new SimpleFuture<>();
String url = IPAddress.PRODUCTION + Variables.get_id + id;
Ion.with(context)
.load("GET", url)
.asJsonObject()
.withResponse()
.setCallback(new FutureCallback<Response<JsonObject>>() {
@Override
public void onCompleted(Exception e, Response<JsonObject> response) {
JsonResponse jsonResponse = new JsonResponse();
if (response != null) {
if (response.getHeaders().code() != 200) {
jsonResponse.ok = false;
} else {
jsonResponse.ok = true;
jsonResponse.json = response.getResult();
}
}
jsonFuture.setComplete(jsonResponse);
}
});
return jsonFuture;
}
// in Activity.java
private void loadUser(String userId) {
mLoadingSpinner.setVisibility(View.VISIBLE);
service.getId(userId)
.setCallback(new FutureCallback<JsonResponse>() {
// onCompleted is executed on ui thread
@Override
public void onCompleted(Exception e, JsonResponse jsonResponse) {
mLoadingSpinner.setVisibility(View.GONE);
if (jsonResponse.ok) {
// Show intent using info from jsonResponse.json
} else {
// Show error toast
}
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.