Answer the question
In order to leave comments, you need to log in
Passing a callback to a method as a parameter, normal practice or a crutch?
I implemented a class to work with my rest-like api using OkHTTP,
for example, the GetSomething() method
public class GetSomething {
public void get(Callback callback,int limit, int offset) {
OkHttpClient client = new OkHttpClient();
// Готовим запрос, и отправляем как положено, асинхронно..
// Ну а callback пихаем из параметра
Request request = new Request.Builder().url(url).build();
client.newCall(request).enqueue(callback);
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
import ru.domain.user.app.api.getSomething;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSomething something = new getSomething();
Callback callback = new Callback() {
@Override
public void onFailure(Call call, IOException e) { e.printStackTrace(); }
@Override
public void onResponse(Call call, Response response) throws IOException {
try {
String jsonData = response.body().string();
JSONObject Jobject = new JSONObject(jsonData);
Log.d("getSomething Resp", Jobject.toString());
} catch (JSONException e) {}
}
Answer the question
In order to leave comments, you need to log in
There is absolutely nothing wrong with your code. Requests in OkHttp are executed in a background thread (not in the main one, in which all the components of the Android application work, but in the background thread), so you need to somehow pass your reaction to the successful / erroneous execution of the request to OkHttp. Callbacks and b were added to OkHttp as a way to add this kind of response to data received on a background thread.
And what exactly do you want to get or do with callback? Pass a reference to some object and perform some logic, or just return the response based on the passed data?
Or transfer some magical method that the one who received it will use?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question