I am working on a new Android Application and I would like to organise all the components - Network Call class, JSON parsing class etc. properly. I am using Okhttp for network calls; After a lot of research I was able to structure my code like this:
My NetworkUtil Class:
public class NetworkUtil {
public static void getData(String url, final OkHttpListener listener){
OkHttpClient client = new OkHttpClient();
// GET request
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
listener.onFailure(request, e);
}
@Override
public void onResponse(Response response) throws IOException {
listener.onResponse(response);
}
});
}
My network callback interface:
public interface OkHttpListener {
void onFailure(Request request, IOException e);
void onResponse(Response response) throws IOException;
}
And this is my Activity class:
OkHttpListener listener = new OkHttpListener() {
@Override
public void onFailure(Request request, IOException e) {
Log.e(LOG_TAG, e.toString());
}
@Override
public void onResponse(Response response) throws IOException {
String responseBody = response.body().string();
Log.i(LOG_TAG, responseBody);
}
};
String url = "http://myserver/api/getvalues";
OkHttpUtils.getData(url, listener);
String url1 = "http://myserver/api/getvalues/123";
OkHttpUtils.getData(url1, listener);
}
Here are the issues that I am facing:
I want to make multiple network calls from an Activity/Fragment based on different events, how do I design the Activity class in such a way that I am able to make multiple requests. I would also like to keep a separate class (an Application class maybe) for all the common methods that will be used in the Activities. I want to make my architecture cohesive.
I would like parse the JSON response in a separate class and pass the results to my Activity class. How do I parse the JSON response in a separate class and pass the results to my Activity/Fragment class from the onSuccess() method in my NetworkUtil class
I would like to use no libraries or very less libraries (at least for the JSON parsing part) throughout this project, at this moment I will be sticking with only okhttp.
It will be of great help if someone could refer me to a git repository or a sample project to have a look.
Your current code can't be tested and breaks SOLID principles, your activity will soon became too huge to easily maintain. Try to avoid using Utils classes in case like that. Use IoC. So I recommend you to take a look at MVP/MVVM or any other presentation pattern.
Search for some articles about MVP pattern and take a look at this repository. Good luck.