0

Here is the scenario: I have an Activity, named MainActivity, calling a OkHttp wrapper class, named NetworkManager to perform network post in background:

// In MainActivity
NetworkManager manager = new NetworkManager();
try {
    manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
} catch(IOException ioe) {
    Log.e(TAG, ioe.getMessage());
}

Then, in the NetworkManager, I perform the POST action in asynchronous mode:

public class NetworkManager {
    static String TAG = "NetworkManager";
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    OkHttpClient client = new OkHttpClient();

    void post(String url, JSONObject json) throws IOException {
        //RequestBody body = RequestBody.create(JSON, json);
        try {
            JSONArray array = json.getJSONArray("d");
            RequestBody body = new FormEncodingBuilder()
                    .add("m", json.getString("m"))
                    .add("d", array.toString())
                    .build();
            Request request = new Request.Builder()
                    .url(url)
                    .post(body)
                    .build();

            // Asynchronous Mode
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.e(TAG, e.toString());
                    // what should I put here?
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Log.w(TAG, response.body().string());
                    // what should I put here?
                }
            });
        } catch (JSONException jsone) {
            Log.e(TAG, jsone.getMessage());
        }
    }
}

What I'm trying to achieve is to call a function in MainActivity after network POST is successful or failed. How can I achieve this?

Raptor
  • 53,206
  • 45
  • 230
  • 366
  • Although I have not tried your issue with OkHttp, however, IMO, it's the same way with Volley, so please read some following links: http://stackoverflow.com/questions/33535435/how-to-create-a-proper-volley-listener-for-cross-class-volley-method-calling/33535554#33535554 http://stackoverflow.com/questions/31602042/android-java-how-to-delay-return-in-a-method and http://stackoverflow.com/questions/32375295/android-how-to-return-async-jsonobject-from-method-using-volley/32379539#32379539. And I think @John's answer below is working for your issue :) – BNK Dec 10 '15 at 04:41

1 Answers1

2

You can create an interface with onFailure and onResponse then let YourActivity implement it. And, on NetworkManagertry to notify YourActivity using listener.

       // MainActivity implements NetworkListener 
        NetworkManager manager = new NetworkManager();
        manager.setOnNetWorkListener(this);
        try {
            manager.post("http://www.example.com/api/", reqObj); // reqObj is a JSONObject
        } catch(IOException ioe) {
            Log.e(TAG, ioe.getMessage());
        }
        void onFailure(Request request, IOException e) {
             // call your activity methods
        }
        void onResponse(Response response) {
             // call your activity methods  
        }

        // ======NetworkManager class============
        public class NetworkManager {
            static String TAG = "NetworkManager";
            public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
            OkHttpClient client = new OkHttpClient();
            public NetworkListenerv listener;
            public void setOnNetWorkListener(NetworkListener listener) {
                this.listener = listener
            }
            // Asynchronous Mode
            client.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Log.e(TAG, e.toString());
                    // what should I put here?
                    if (listener != null) {
                        listener.onFailure(request, e);
                    }
                }

                @Override
                public void onResponse(Response response) throws IOException {
                    Log.w(TAG, response.body().string());
                    // what should I put here?
                     if (listener != null) {
                        listener.onResponse(response);
                    }
                }
            });

    // Your interface;
     public interface NetworkListener {
        void onFailure(Request request, IOException e);
        void onResponse(Response response);
    }
NamNH
  • 1,752
  • 1
  • 15
  • 37