okhttp3如何从异步GET调用返回值

时间:2016-12-20 08:12:05

标签: android android-asynctask okhttp3

我正在Android studio中实现Helper类以服务Activity

public void getLastId()
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);

            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

我的活动类中的函数调用

Helper helper = new Helper();
helper.getLastId();
//I want to get method to return lastId and then manipulate with the data

如何创建id的方法返回值?

3 个答案:

答案 0 :(得分:1)

由于这是一个异步过程,您无法从方法本身返回值。但是,您可以使用回调为异步进程完成时提供值。以下是您可能希望如何执行此操作的示例。

public interface GetLastIdCallback {
    void lastId(String id);
}

您可以按如下方式修改getLastId:

public void getLastId(GetLastIdCallback idCallback) {
    ...
    String last_id = String.valueOf(Integer.parseInt(id)+1);
    idCallback.lastId(last_id);
    ...

}

你的Helper类使用现在看起来像这样:

Helper helper = new Helper();
helper.getLastId(new GetLastIdCallback() {
     @Override
     public void lastId(String id) {
         // Do something with your id
     }
});

我建议让你的回调比我上面建议的更通用。它看起来像这样:

public interface GenericCallback<T> {
    void onValue(T value);
}

...

Helper helper = new Helper();
helper.getLastId(new GenericCallback<String>() {
    @Override
    public void onValue(String value) {
        // Do something
    }
});

如果您使用上述界面,则可以使用任何返回类型。

答案 1 :(得分:0)

创建一个界面。

public interface Result{
   void getResult(String id);
}

现在,将interface作为参数传递给方法。

 Helper helper = new Helper();
      helper.getLastId(new Result(){
        @Override
        void getResult(String id){

        }
});

在你的方法中:

public void getLastId(final Result result)
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);
                result.getResult(last_id);

            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

答案 2 :(得分:0)

您必须为其创建interface

public interface getResponse {

     void getJsonResponse(final String id);

}

在您的代码中:

public void getLastId(fianl getResponse response)
{
    //init OkHttpClient
    OkHttpClient client = new OkHttpClient();

    //backend url
    Request request = new Request.Builder()
            .url("http://192.168.1.102:8080/aquabackend/public/customers/lastid")
            .build();


    client.newCall(request).enqueue(new Callback() {
        @Override
        public void onFailure(Call call, IOException e) {

        }

        @Override
        public void onResponse(Call call, Response response) throws IOException {

            String jsonData = response.body().string();

            try {
                JSONObject jobject = new JSONObject(jsonData);
                String id = jobject.getString("id");

                //increment current id +1
                String last_id = String.valueOf(Integer.parseInt(id)+1);
                Log.i("new id", last_id);
if(response!=null){
response.getJsonResponse(last_id)
}
            } catch (Exception e) {
                    e.printStackTrace();
            }
            //Log.i("ok", response.body().string());
        }
    });

活动:

 public class HomeActivity extends AppCompatActivity  {
 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    Helper helper = new Helper();
      helper.getLastId(new getResponse(){
            @Override
            void getJsonResponse(String id){

            }
    });
}}
    }
相关问题