如何 return get (okhttp3) 的结果

How to return the result from get (okhttp3)

我使用 okhttp3 get 方法得到了结果。 现在,我想 return 结果到 MainActivity.

我尝试使用 intent,但失败了。 我也读了这个 。但是我对必须在哪里编写该代码感到困惑。

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

我的主要Activity:

getMaskInfo info = new getMaskInfo(this);
info.requestGet(latitude, longitude);

getMaskInfo Activity(我要return JSONObject 或 JSONArray):

package com.example.buymaskapp;

public class getMaskInfo {
    OkHttpClient client = new OkHttpClient();
    public static Context mContext;

    public getMaskInfo(Context context){
        mContext = context;
    }

    public void requestGet(double lat, double lng){
        String url = "https://8oi9s0nnth.apigw.ntruss.com/corona19-masks/v1/storesByGeo/json";

        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        urlBuilder.addEncodedQueryParameter("lat", Double.toString(lat));
        urlBuilder.addEncodedQueryParameter("lng", Double.toString(lng));
        urlBuilder.addEncodedQueryParameter("m", "1000");

        String requestUrl = urlBuilder.build().toString();

        Request request = new Request.Builder().url(requestUrl).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("error", "Connect Server Error is " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try{
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONArray totalStore = jsonObject.getJSONArray("stores");
                    System.out.println(jsonObject);                          
                }catch (JSONException e){
                    //
                }
            }
        });
    }
}

在 MainActivity 中创建回调: public void onResult(JSONArray stores) 或任何您想从通话中 return 的内容。由于您现在知道您的 mContext 实际上是 MainActivity,您可以进行转换并调用该方法 ((MainActivity)mContext).onResult(totalStore).

如果您还需要将 getMaskInfo 与其他活动一起使用,您可以将方法 onResult 放入接口中,让 MainActivity 实现该接口并将该接口作为参数传递至 getMaskInfo.

Interface class

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

Update the onResponse function

 @Override
            public void onResponse(Call call, Response response) throws IOException {
                try{
                    JSONObject jsonObject = new JSONObject(response.body().string());
                    JSONArray totalStore = jsonObject.getJSONArray("stores");
                    System.out.println(jsonObject); 
                    ((GetLastIdCallback )(mContext)).getJSONCallback(jsonObject);   //Return here                     
                }catch (JSONException e){
                    //
                }
            }
        });

Calling activity must implement GetLastIdCallback interface

public class Main2Activity extends AppCompatActivity  implements GetLastIdCallback{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
    }

    @Override
    public void lastId(String id) {

    }

    @Override
    public void getJSONCallback(JSONObject object) {
        //Here you can use response according to your requirements 

    }
}

不是从 requestGet() 方法 returning void,而是 return LiveData

public LiveData<JSONObject> requestGet(double lat, double lng) {
   LiveData<JSONObject> result = MutableLiveData<JSONObject>();

   /* reqeust builder & url builder code here */

   client.newCall(request).enqueue(new Callback() {
   /* override other methods here */

   public void onResponse(Call call, Response response) throws IOException {
            try{
                JSONObject jsonObject = new JSONObject(response.body().string());
                ((MutableLiveData) result).postValue(jsonObject);                        
            }catch (JSONException e){
                /* catch and do something */
            }
        }
   });

   return result;
}

观察mainactivity中的livedata

info.requestGet(latitude, longitude).observe(getViewLifeCycleOwner, new Observer() {
   @Override
   public void onCanged(JSONObject result) {
       /* code to use result */   
   }
});

否则,你也可以在mainactivity上实现接口,在getMaskInfo或requestGet方法中使用其实例回传数据。