I want to separate async http code from the activities as I'm reusing the code. This is what I am doing currently:
I want to get a list of projects form a REST API and store it in an array. (Assume I'm not using local caching as I want to load them every time)
ProjectInterface.java
public interface ProjectInterface {
public void onProjectsLoaded(ArrayList<Project> projectArrayList);
}
HttpProjectList.java
//async class will get the results from the server and send to the activity
public class HttpProjectList {
protected ProjectInterface interface;
protected Context c;
public HttpProjectList(ProjectInterface interface, Context c){
this.interface = interface;
this.c = c;
}
//Run Async task Volley here
public void projectListRequest() {
RequestQueue requestQueue = Volley.newRequestQueue(this.c);
JsonArrayRequest req = new JsonArrayRequest(Path.WORK_ORDERS, success, error);
requestQueue.add(req);
}
//on success set the data
private Response.Listener<JSONArray> success = new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
//do dome parsing here and populate the array
interface.onProjectsLoaded(projectArrayList);
}
}
//error function here, i'm not typing
}
MyActivity.java
//I'm calling all in this activity
public class BaseActivity extends Activity implements ProjectInterface {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(setView());
HttpProjectList httpList = new HttpProjectList(this, getBaseContext());
httpList.projectListRequest(); //fire http call
}
//run after projects loaded
@Override
public void onProjectsLoaded(ArrayList<Project> projectArrayList) {
//Do something with the server data
}
}
In this case I have one API that populate the array. What if I have multiple api calls? Like
- User list
- Contractor list
- Task list
- POST a new task to the server etc
How can I organise code according to OOP and SOLID principles? These are the techniques I have In my mind, but I don't know which one is the best.
Create separate classes for all the Async functions. According to the above example I have 1 interface and 1 http service handler class. In the same way, I will create 2 sets of classes for every api call
Create one interface call HttpInterface and put all the call back functions in it, and create another HttpHandler class and put all the http methods of all the API calls
Which one is better? Or is there any other way? Can you give some advice on this? Thanks a lot!