0

I'm very new at programming for Android - please bear with me.

I'm building an app that requires network access, using OKHttp. Since I will be making many similarly structured requests from my server, I created a class that handles all network-related tasks, as I like to keep things compartmentalized.

One method I'm working on is createNetworkThread from within my NetworkManager class. This particular method takes three arguments:

Context context, final String requestURI, final RequestBody formParameters

What I need assistance with is how to return the data received from this method so I can use and manipulate it in the calling Activity.

Here is the method in question:

public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters) {
    if (!this.isConnected(context)) return;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(requestURI).post(formParameters).build();

            Response response = null;

            // Send login request, get response //

            try {
                response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);

                Log.d("Net", "Request send and received!");

            } catch (IOException e) {
                Log.d("Net", "Failed");
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

Here is the call from the Activity:

final NetworkManager Net = new NetworkManager(this);

...

final String requestURI = "http://192.168.1.111/videonow.club/apprequest/signup/thread.php";
final RequestBody formVars = new FormBody.Builder().add("email", strEmail).add("password", strPass1).add("first_name", strNameFirst).add("last_name", strNameLast).build();

Net.createNetworkThread(SignupActivity.this, requestURI, formVars);

What I need to know is how to get the JSON data from jsonResponse returned from the method (I know void doesn't allow this) so I can use the data.

Would it be better to have the jsonObject returned so I can use something like this:

SomeType response = Net.createNetworkThread(...);

Or, to have a class variable within NetworkManager that would be set by the method so it would be called to and referenced like this:

Net.createNetworkThread(...);
SomeType response = Net.someVariable;

Or is there some much more reasonable way to receive this data?

I'm also calling new OkHttpClient() twice - once in the activity, so I can build the requestBody post variables, as well as in the NetworkManager class itself. My instincts tell me this is redundant... if so, is there a way to make this more efficient?

Thanks in advance!

mwieczorek
  • 2,107
  • 6
  • 31
  • 37
  • @TimCastelijns OkHttp is an Http client. Like HttpUrlConnection – Blackbelt May 10 '16 at 09:29
  • @TimCastelijns I was told my a friend to be sure to always keep network requests in a separate thread. If it's already done then, I would just imagine removing the Runnable object from around the code, but my original question about how to cast the method stands. – mwieczorek May 10 '16 at 09:30
  • you could use a delegate object to get the results back. An example [here](http://stackoverflow.com/questions/16752073/how-do-i-return-a-boolean-from-asynctask) – Blackbelt May 10 '16 at 09:32
  • Aha I'm reading the wrong docs – Tim May 10 '16 at 09:33

3 Answers3

0

You can use OkHttp with AysncTask like this:

public class Webservice extends AsyncTask<String, String, UserResponse> {

private String TAG = Webservice.class.getSimpleName();
private static final String ENDPOINT = "YOUR_URL";
private static final Moshi MOSHI = new Moshi.Builder().build();
private static final JsonAdapter<UserResponse> CONTRIBUTORS_JSON_ADAPTER_RESPONSE = MOSHI.adapter(Types.newParameterizedType(UserResponse.class, UserResponse.class));

UserResponse webResponse;
public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
String postBody = "postBody\n";

@Override
protected UserResponse doInBackground(String... parmas) {
    OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
    Call call = okHttpClient.build().newCall(new Request.Builder()
            .url(ENDPOINT)
            .post(RequestBody.create(JSON, postBody))
            .addHeader("Content-Type", "application/json")
            .build());

    try {
        Response response = call.execute();
        adModelResponse = CONTRIBUTORS_JSON_ADAPTER_RESPONSE.fromJson(response.body().source());

    } catch (IOException e) {
        e.printStackTrace();
    }
    return webResponse;
}

@Override
protected void onPostExecute(UserResponse adModelResponse) {


}
}

And then in Activity call like this:

Webservice webservice = new Webservice();
webservice.execute("YOUR_PARAMETER");

Libraries Used:

okhttp-3.2.0, moshi-1.1.0, okio-1.8.0

Umair Adil
  • 968
  • 1
  • 10
  • 24
0

You can use callback interface to get your data back to your activity. Consider the example below:

public interface JsonResponse {
   onResponseReceived(JSONObject response);
}

Then your createNetworkThread will looks like this:

public void createNetworkThread(Context context, final String requestURI, final RequestBody formParameters, JsonResponse responseCallback) {
    if (!this.isConnected(context)) return;

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder().url(requestURI).post(formParameters).build();

            Response response = null;

            // Send login request, get response //

            try {
                response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);
                responseCallback.onResponseReceived(jsonResponse); // This line will return to your caller

                Log.d("Net", "Request send and received!");

            } catch (IOException e) {
                Log.d("Net", "Failed");
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(runnable);
    thread.start();
}

And finally the caller:

Net.createNetworkThread(SignupActivity.this, requestURI, formVars, new JsonResponse() {
            @Override
            public void onResponseReceived(JSONObject response) {
                // Do stuff in your activity
                // eventually use runOnUiThread for your UI operations 
            }
        });
E-Kami
  • 2,529
  • 5
  • 30
  • 50
0

Make NetworkManager Abstract and add one abstract method say public abstract void onResult(JSONObject response); and override this method like

final NetworkManager Net = new NetworkManager(this){
@Override
public void onResult(JSONObject response){
//do whatever you want here
}
};

And from the createNetworkThread when finished call this method as

.....
response = client.newCall(request).execute();
                String stringResponse = response.body().string();
                JSONObject jsonResponse = new JSONObject(stringResponse);
onResult(jsonResponse);
......
Waqar Khan
  • 468
  • 4
  • 18