Reputation: 2600
I want to move my OkHttp async request to a separate class as I use it multiple times in multiple activities in my application. Is this possible? I've read a lot about it but can't find a solution for me.
MainActivity.java
public void mainActivityMethod(String JSONData) {
// Handle JSONData string
}
MyClass.java
public void doRequest() {
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = okHttpClient.newCall(request);
call.enqueue(new Callback() {
@Override
public void onFailure(Request request, IOException e) {
e.printStackTrace();
}
@Override
public void onResponse(final Response response) throws IOException {
if (response.isSuccessful()) {
// Fetch request data
String JSONData = response.body().string();
mainActivityMethod(JSONData);
}
}
});
}
Upvotes: 1
Views: 1647
Reputation: 516
I assume you have this solved by now. The easy answer is to create an interface that main activity supports and pass the mainActivity via the interface to MyClass so MyClass makes the call to the interface. I would tell you more but I suspect no one will ever read this.
Upvotes: 0
Reputation: 1112
Rather this one. First create the Interface for it and implement it in needed activities. After that, create an AsyncTask
to do network related stuff. In the AsyncTask
's onPost
method, call the Activity
's implement method to reflect needed changes in the Activity
.
Upvotes: 1
Reputation: 5806
What you are looking for is AsyncTask
http://developer.android.com/reference/android/os/AsyncTask.html
Remember to subclass it. You can do it in your MainActivity if static. Here is a simple example from the documentation
private static class ConnectTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
//executed in background
int result
//call...
//set 0 or 1 depending or the error code
return result;
}
protected void onProgressUpdate(Integer... progress) {
//in case you want to post any progress
// on UI thread
}
protected void onPostExecute(Long result) {
//when the call is finished
// on UI thread
}
}
Upvotes: 0
Reputation: 519
Or you could use OTTO. You can use OTTO to publish an event and then subscribe to that event in the activity. It helps you in loose coupling.
Upvotes: 1
Reputation: 377
when you need to use a function of another class just create an instance of that class and call the function, like :
MyWantedClass myWantedClass= new MyWantedClass;
myWantedClass.functionNeeded();
Upvotes: 0