Android:从回调获取结果(联网KOUSH ION) [英] Android: get result from callback (networking KOUSH ION)

查看:84
本文介绍了Android:从回调获取结果(联网KOUSH ION)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的应用程序,我需要从服务器返回返回JSON的API与我们联系.

For my app I need to contact our API from our server which returns some JSON.

下载JSON时,它应该显示一个进度条.

While downloading the JSON, it should display a progressbar.

我认为在进行网络操作时应该使用Android的AsyncTask处理GUI,因此我在Activity中编写了以下内容:

I figured I should use Android's AsyncTask to handle the GUI while doing network operations, so I wrote the following within my 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);

    }

}

基本上,onPreExecute显示正在加载的微调器,doInBackGround下载一些JSON,而onPostExecute停止微调器.

Basically, onPreExecute shows the loading spinner, the doInBackGround downloads some JSON, and onPostExecute stops the spinner.

问题是,在downloadUtility.getId(id)中,我需要:

The question is, within the downloadUtility.getId(id) I need to either:

  1. 如果下载成功成功,请打开一个新的意图.
  2. 如果下载失败失败,请继续进行相同的活动并显示错误的祝酒词.
  1. Open a new intent if the download succeeded.
  2. Stay on the same activity and display an error toast if the download failed.

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;

}

如您所见,我正在返回将来的对象.我怎么从将来的对象中知道onCompleted(void)是成功还是失败,所以我可以在asynctask中处理结果(成功:打开新的意图,失败:吐司)?

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?

推荐答案

在这里,您正在另一个asyctask中运行一个asynctask,这不是在活动中直接调用getId方法的正确方法,因为不需要另一个asynctask因为下面的代码本身具有asynctask.

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.

 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!
                    }
                }

            }
        });

//添加新答案

如果要将整个下载代码与活动分开,则可以在下载实用工具类中创建自定义的回调.它将像活动和您的Download类之间的沟通者.我只是给出一种在波纹管上完成此任务的方法.

If you want to separate entire download code from your activity then you can create custom callBack in your download Utility class. It will acts like a communicator between activity and your Download class. I just give a way to do this task on bellow.

DownloadUtility 类接缝看起来像波纹管

DownloadUtility class seams look like bellow

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

}

拨打您的活动

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!
        }
}

});

这篇关于Android:从回调获取结果(联网KOUSH ION)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆