我使用okhttp3 get方法获得结果。现在,我想将结果返回给MainActivity。
我尝试使用Intent,但失败了。我也读了这个okhttp3 how to return value from async GET call。但是我对于必须在哪里编写该代码感到困惑。
public interface GetLastIdCallback {
void lastId(String id);
}
我的MainActivity:
getMaskInfo info = new getMaskInfo(this);
info.requestGet(latitude, longitude);
getMaskInfo活动(我想返回JSONObject或JSONArray):包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)
或您希望从通话中返回的任何内容。由于您现在知道mContext
实际上是MainActivity
,因此可以进行强制转换并调用该方法((MainActivity)mContext).onResult(totalStore)
。
如果还需要在其他活动中使用getMaskInfo
,则可以将方法onResult
放入接口,使MainActivity
实现该接口,并将该接口作为参数传递给getMaskInfo
。
接口类
public interface GetLastIdCallback {
void lastId(String id);
void getJSONCallback(JSONObject object);
}
更新onResponse函数
@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){
//
}
}
});
呼叫活动必须实现GetLastIdCallback接口
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
}
}
而不是从void
方法返回requestGet()
,而是返回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());
result.postValue(jsonObject);
}catch (JSONException e){
/* catch and do something */
}
}
});
return result;
}
在mainactivity中观察实时数据
info.requestGet(latitude, longitude).observe(getViewLifeCycleOwner, new Observer() {
@Override
public void onCanged(JSONObject result) {
/* code to use result */
}
});
否则,您也可以在mainactivity上实现接口,并在getMaskInfo或requestGet方法中使用其实例来发送回数据。