jisoo0427
jisoo0427

Reputation: 39

How to return the result from get (okhttp3)

I get a result by using okhttp3 get method. And Now, I want to return the result to MainActivity.

I tried using intent, but I'm failed. Also I read this okhttp3 how to return value from async GET call. But I confused about where I have to write that code.

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

my MainActivity:

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

getMaskInfo Activity (I want to return JSONObject or 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){
                    //
                }
            }
        });
    }
}

Upvotes: 0

Views: 1232

Answers (3)

Nataraj KR
Nataraj KR

Reputation: 1102

Instead of returning void from requestGet() method, return a 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;
}

Observe the livedata in mainactivity

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

Otherwise, you can also implement interface on mainactivity and use its instance in getMaskInfo or in requestGet method to send back data.

Upvotes: 1

Haseeb Mirza
Haseeb Mirza

Reputation: 454

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 

    }
}

Upvotes: 0

K-dari
K-dari

Reputation: 216

Create a callback in MainActivity: public void onResult(JSONArray stores) or whatever you want to return from the call. Since you now know that your mContext is actually MainActivity, you can make a cast and call that method ((MainActivity)mContext).onResult(totalStore).

If you need to use getMaskInfo with other activities as well, you can put method onResult into an interface, make MainActivity implement that interface and pass the interface as an argument to getMaskInfo.

Upvotes: 0

Related Questions