【问题标题】:okhttp3 how to return value from async GET callokhttp3 如何从异步 GET 调用返回值
【发布时间】:2016-12-20 20:59:45
【问题描述】:

我正在 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的值?

【问题讨论】:

    标签: android android-asynctask okhttp3


    【解决方案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
        }
    });
    

    如果您使用上述接口,您将能够使用任何返回类型。

    【讨论】:

      【解决方案2】:

      创建一个界面。

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

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

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

      【讨论】:

        【解决方案3】:

        你必须为它创建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){
        
                    }
            });
        }}
            }
        

        【讨论】:

        • 在哪里创建界面?在我的 Helper 类中?
        • 它是分开的。无需在 Helper 类中创建
        • 它说 Error:(181, 18) error: getJsonResponse(String) in cannot implement getJsonResponse(String) in getResponse试图分配较弱的访问特权;是公开的
        猜你喜欢
        • 2020-06-23
        • 2012-03-13
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        相关资源
        最近更新 更多