Reputation: 41
I've seen a few similar questions but they don't seem to answer my problem exactly. I've got a method that is supposed to return a string. I am using retrofit, but in onresponse, I can't return a string? Below is the code.
public String getInformation(String information, String username) {
String result;
Call<DefaultResponse> call = RetrofitClient.getInstance().getApi().getInformation(information,username);
call.enqueue(new Callback<DefaultResponse>() {
@Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
result = response.body().getMsg();
}
@Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
}
});
return result;
}
Upvotes: 0
Views: 981
Reputation: 1
You can use Result as output String wherever you want, as I used it in my adapter class in onBindViewHolder method, simply making object of the class from which string was sent and then calling the method (in which Interface was kept as parameter) & override success and failure method in adapter class and do whatever u want to do with this string......... Thanks a lot @y.allam & @Anonymous Cardinal :):)
Upvotes: 0
Reputation: 1516
The .enqueue
method will take time to get the response, so your method will return before onResponse
callback gets called.
Try using a callback approach for getInformation
method and make it void
:
public void getInformation(String information, String username, MyCallback callback) {
Call<DefaultResponse> call = RetrofitClient.getInstance().getApi().getInformation(information,username);
call.enqueue(new Callback<DefaultResponse>() {
@Override
public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) {
result = response.body().getMsg();
callback.success(result);
}
@Override
public void onFailure(Call<DefaultResponse> call, Throwable t) {
callback.failure(t)
}
});
}
With the MyCallback
interface:
interface MyCallback {
void success(String result);
void failure(Throwable t);
}
Then you can call the method like this:
getInformation("Information", "Username", new MyCallback() {
@Override
public void success(String result) {
// Use result
}
@Override
public void failure(Throwable t) {
// Display error
}
});
Upvotes: 2