Retrofit is not making api call - android

I'm using retrofit 2 to make api call to my server but it get stucked when trying to make api call. This is my code
public interface GOTApi {
#GET("characters.json")
Call<GOTCharacterResponse> getCharacters();
}
Intermediate class to get the data
public class GOTCharacterResponse {
List<GOTCharacter> characters;
}
My class to make api call
public class GOTService {
public static final String BASE_URL = "https://project-8424324399725905479.firebaseio.com/";
public static GOTApi getGOTApi(){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
return retrofit.create(GOTApi.class);
}
public static void getCharacters(){
getGOTApi().getCharacters().enqueue(new Callback<GOTCharacterResponse>() {
#Override
public void onResponse(Call<GOTCharacterResponse> call, Response<GOTCharacterResponse> response) {
if(response.isSuccessful()){
}
}
#Override
public void onFailure(Call<GOTCharacterResponse> call, Throwable t) {
int a = 0;
}
});
}
}
These are the libraries I'm using
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit:converter-gson:2.0.0-beta2'
compile 'com.squareup.okhttp3:okhttp:3.3.1'
It always get stucked in the getCharacters() method. Of course I have internet permission set in Mainfest.

You may try using Retrofit2 with RxJava, it is more convenient.
public Retrofit providedRetrofit(OkHttpClient okHttpClient){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BuildConfig.BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
return retrofit;
}
Your API interface will look like
public interface Api {
#GET("api/service/schedule/{filial}")
Observable<Response<GOTCharacter>> getSchedule(#Path("some_param") String param);
}
You also need to parse response from JSON. You didn't provided
GOTCharacter class, but you can create code from json response by using
http://www.jsonschema2pojo.org/ service

I think you are implementing wrong onResponse() OR Callback(), because I am using Retrofit 2 too, in which onResponse() looks like this:
#Override
public void onResponse(Response<ListJsonResponseRestaurant> response, Retrofit retrofit) {
...
...
}

Related

How to get the request URL for a Retrofit object?

I need to log the request URL that Retrofit creates. I don't find any getter methods on Retrofit object or web interface that is generated via Retrofit. The following is my code, where I want to log the address of every request:
public void onRequestFoods() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(Const.BASE_LOCAL)
.addConverterFactory(GsonConverterFactory.create())
.build();
FoodOrderInterface foodInterface = retrofit.create(FoodOrderInterface.class);
Log.d(TAG, "onRequestFoods: request url: ");
foodInterface.listFoods().enqueue(new Callback<FoodResponse>() {
#Override
public void onResponse(Call<FoodResponse> call, Response<FoodResponse> response) {
List<Food> foods = response.body().getBody().getFoods();
mPresenter.onResponse((ArrayList<Food>) foods);
}
#Override
public void onFailure(Call<FoodResponse> call, Throwable t) {
mPresenter.onRequestFailed(t.getMessage());
}
});
}
I think what you need is http logging interceptor the github repo has a straightforward example of how to get it up and running

Using Single and Rxjava does not execute the retrofit request?

Hi i am using retrofit and rxjava to make a simple request and get the response back but it doesnt seem to be making the request itself or getting the response back?
This is my retrofit code:
public class Controller
public Single<List<ListItems>> getItems() {
return apiCall().getItems();
}
private ServiceCallsApiCall() {
OkHttpClient okHttpClient = new OkHttpClient().newBuilder().addInterceptor(interceptor).build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()).build();
ServiceCallsApiCall serviceCalls= retrofit.create(ServiceCallsApiCall.class);
return foodHygieneServiceCalls;
}
my ServiceCallsApiCall class
#GET("Authorities/basic")
Single<List<ListItems>> getItems();
Here is my Rxjava part of my code that subscribes and observes this
public void getItems() {
new Controller().getItems()
.observeOn(AndroidSchedulers.mainThread())
.subscribeOn(Schedulers.io())
.subscribe(new SingleObserver<List<ListItems>>() {
#Override
public void onSubscribe(Disposable d) {
Log.d("","onSubscribe");
}
#Override
public void onSuccess(List<ListItems> items) {
viewPresenterCallBacks.updateView(items);
}
#Override
public void onError(Throwable e) {
Log.d("","onError" + e.getMessage());
}
});
}
None of the onSuccess or onError gets called
I had a similar problem recently. The problem is not from retrofit or rxJava, its from the deserialization of the JSON to your ListItem POJO. I believe the crux of the issue is that your JSON deserialization library is unable to translate the Json to POJO.
If you are using Jackson you can just add the #JsonIgnoreProperties(ignoreUnknown = true) to your ListItem class.
In my case I was using GSON and since i wasn't interested in all the JSON properties I just changed my initial retrofit method signature from Single<Movies> getRecentMovies(); to Single<ResponseBody> getRecentMovies(); and extracted the desired fields in my response.

How to handle No Network connection using Retrofit 2.0 in Android?

I am using Retrofit 2.0 library in my android application by adding it into build.gradle file
// retrofit, gson
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
related code is given below
ApiInterface.java
public interface ApiInterface {
#GET("contacts/")
Call<ContactsModel> getContactsList();
}
ApiClient.java
public class ApiClient {
public static final String BASE_URL = "http://myexamplebaseurl/";
private static Retrofit retrofit = null;
public static Retrofit getClient() {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
MainActivity.java
ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class);
Call<ContactsModel> call = apiService.getContactsList();
call.enqueue(new Callback<ContactsModel>() {
#Override
public void onResponse(Call<ContactsModel> call, Response<ContactsModel> response) {
if(response.isSuccessful()){
/*here is my data handling*/
}
}
#Override
public void onFailure(Call<ContactsModel> call, Throwable t) {
/*It is the request failure case,
I want to differentiate Request timeout, no internet connection and any other reason behind the request failure
*/
}
});
if we get status code as 4xx or 5xx even though onResponse() will called, so there we need handle that condition also.
Here my question is, How to differentiate reason for request failure i.e onFailure() by using Retrofit 2.0 in Android?
Here my question is, How to differentiate reason for request failure
by using Retrofit 2.0 in Android?
if you have a 4xx or 5xx error, onResponse is still called. There you have to check the response code of the code to check if everything was fine. E.g
if (response.code() < 400) {
in case of No Network connection, onFailure is called. There you could check the instance of the throwable. Typically an IOException

Json Object Request using Retrofit2

I am new in retrofit. I completed all setup.
I add this gradle in build.gradle file
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
My Interface is like this:
public interface ILoginInterface {
String BASE_URL= "MY_BASE_URL/";
#POST("MY/API")
Call<LoginResponseEntity> startLogin(#Body JSONObject jsonObject);
class Factory{
private static ILoginInterface instance;
public static ILoginInterface getInstance(){
if(instance==null){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
instance = retrofit.create(ILoginInterface.class);
}
return instance;
}
}
}
My Calling procedure is like this:
ILoginInterface.Factory.getInstance().startLogin(jsonObject).enqueue(new Callback<LoginResponseEntity>() {
#Override
public void onResponse(Call<LoginResponseEntity> call, retrofit2.Response<LoginResponseEntity> response) {
Log.d("MS",response.body().fullName);
}
#Override
public void onFailure(Call<LoginResponseEntity> call, Throwable t) {
Log.d("MS",t.getMessage());
}
});
Here jsonObject is like this:
{"user_name":"sajedul Karim", "password":"123456"}
Here it seems everything is ok but i didn't getting proper response.
I found a solution. it is here . Does anybody have proper solution like Volley JsonObjectRequest
May be you are importing
import org.json.JSONObject;
you should use
import com.google.gson.JsonObject;
Then you will get it's value.

apply url to retrofit

I'm writting a retrofit demo.
I have to use "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code" to get code.
when writing rest, I do it like this:
public interface WXService {
#GET("/access_token?grant_type=authorization_code")
Observable<AccessTokenModel> getAccessToken(#Query("appid") String appId,
#Query("secret") String secretId,
#Query("code") String code);
}
public class WXRest {
private static final String WXBaseUrl = "https://api.weixin.qq.com/sns/oauth2/";
private WXService mWXService;
public WXRest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WXBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.build();
mWXService = retrofit.create(WXService.class);
}
public void getAccessToken(String code) {
mWXService.getAccessToken(Constants.APP_ID, Constants.SECRET_ID, code)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<AccessTokenModel>() {
#Override
public void call(AccessTokenModel accessTokenModel) {
Log.e("WX", "accessToken:" + accessTokenModel.accessToken);
}
});
}
}
but I got an error:
java.lang.IllegalArgumentException: Unable to create call adapter for
rx.Observable
I think it's the way i transform the url wrong.But I don't know how to fix it.
i think you should include adapter-rxjava lib to your gradle dependencies.
compile 'com.squareup.retrofit:adapter-rxjava:2.0.0-beta1'
and then add call adapter factory to your retrofit builder
public WXRest() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WXBaseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build();
mWXService = retrofit.create(WXService.class);
}

Categories

Resources