How to get Header from RxAndroid Response.? - android

This is the function which i used for the network calls.
private void generateNewCard()
{
showProgressDialog();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetworkCalls.BASE_URL)
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
NetworkCalls.CustomerApi customerApi = retrofit.create(NetworkCalls.CustomerApi.class);
customerApi.addExistingCard(prefs.getString(Constants.AUTH_TOKEN, ""), "", CREATE_NEW_CARD)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Observer<DataGeneral>() {
#Override
public void onCompleted() {
stopProgressDialog();
Log.d(TAG, "onCompleted DataGeneral" + DataGeneral.class);
}
#Override
public void onError(Throwable e) {
Log.d(TAG, "onError" + e.getMessage());
stopProgressDialog();
}
#Override
public void onNext(DataGeneral data) {
stopProgressDialog();
if (data.getStatus() == 1) {
}
}
});
}
and the interface class is here,
#FormUrlEncoded
#POST("add-loyalty-card")
Observable<DataGeneral> addExistingCard(#Field("Token") String token, #Field("cardHas") String cardHas, #Field("ltyCardId") String ltyCardId);
This works fine for me. I am getting desired result. I wish to know how can i get the Header from the response and is there a way to simplify the above code?
Any help would be really appreciated.

Related

Android - Retrofit does not display data

I'm trying to learn Retrofit making simple weather app and I have some problem. I made two methods to display data in Activity and method does not work outside onCreate, but second one in works. In Android Profiler I can see JSON logs, but still I don't see anything in Activity. What's the problem?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(WeatherAPI_Interface.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();
WeatherAPI_Interface weatherAPIInterface = retrofit.create(WeatherAPI_Interface.class);
latitude = 37.8267;
longitude = -122.4233;
Call<Currently> call = weatherAPIInterface.getWeather(latitude, longitude);
call.enqueue(new Callback<Currently>() {
#Override
public void onResponse(#NonNull Call<Currently> call, #NonNull Response<Currently> response) {
temp_textview.setText(String.valueOf(response.body().getCurrently().getTemperature()));
city_textview.setText(response.body().getTimezone());
image_View.setImageResource(Integer.parseInt(response.body().getCurrently().getIcon()));
}
#Override
public void onFailure(#NonNull Call<Currently> call, #NonNull Throwable t) {
}
});
}
#Override
public void getCurrentWeather(final Currently currently) {
latitude = 37.8267;
longitude = -122.4233;
NetworkClient.getInstance().getWeather(latitude, longitude).enqueue(new Callback<Currently>() {
#Override
public void onResponse(#NonNull Call<Currently> call, #NonNull Response<Currently> response) {
weather_textview.setText((CharSequence) response.body().getCurrently().getSummary());
pressure_textview.setText((CharSequence) response.body().getDaily().getData());
temp_textview.setText(String.valueOf(currently.getCurrently().getTemperature()));
Log.d(TAG, "City" + currently.getLatitude());
}
#Override
public void onFailure(Call<Currently> call, Throwable t) {
Log.d(TAG, "Failed" + t.getMessage());
}
});
}
public class NetworkClient {
private static WeatherAPI_Interface service;
public static WeatherAPI_Interface getInstance() {
if (service == null) {
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(WeatherAPI_Interface.API_URL)
.build();
service = retrofit.create(WeatherAPI_Interface.class);
return service;
}
else {
return service;
}
}
}
You didn't call the function how can it work?
when the activity starts it'll run the code in OnCreate ( and any call in it) only, so to run any function outside it you need to call it.

onComplete is not getting called when returning response as Flowable

I am trying to make webservie call using retrofit and rxjava 2. i was exploring two different approach to use RxJava2. problem is i am getting response whene i use Observable but it is not working with Flowable. Logs are not getting printed when using Flowable i tried to debug it but its not going inside onNext or onComplete or onError. only onSubscribe gets executed.
1) using observable as return type
new WebRequestManager().getContactObservable(userRequest)
.subscribe(new Observer<ResponseData>() {
#Override
public void onSubscribe(Disposable d) {
}
#Override
public void onNext(ResponseData responseData) {
Log.e(TAG , "data "+responseData.getStatus());
}
#Override
public void onError(Throwable e) {
}
#Override
public void onComplete() {
Log.e(TAG , "data complete");
}
}
);
2) Using flowable as return type
new WebRequestManager().getContactFlowable(userRequest)
.subscribe(new Subscriber<ResponseData>() {
#Override
public void onSubscribe(Subscription s) {
Log.e(TAG , "contact subscription ");
}
#Override
public void onNext(ResponseData responses) {
Log.e(TAG , "contact onNext ");
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
Log.e(TAG , "contact onComplete ");
}
});
Rest contact retrofit api
public interface ContactApi {
#POST(WebRequest.GET_CONTACTS)
Flowable<ResponseData> getContactFlowable(#Body UserRequest userRequest);
#POST(WebRequest.GET_CONTACTS)
Observable<ResponseData> getContactObservable(#Body UserRequest userRequest);
}
call to webservice
public Flowable<ResponseData> getContactsData(UserRequest userRequest){
return webRequest.getWebClient().create(ContactApi.class).getContacts(userRequest);
}
public Observable<ResponseData> getContact(UserRequest userRequest){
return webRequest.getWebClient().create(ContactApi.class).getContact(userRequest);
}
getting retrofit instance
public static Retrofit getWebClient(){
//if(okHttpClient == null)
okHttpClient = new OkHttpClient.Builder()
.connectTimeout(120,TimeUnit.SECONDS)
.readTimeout(120,TimeUnit.SECONDS)
.writeTimeout(120,TimeUnit.SECONDS)
.addInterceptor(new WebRequestInterceptor("\"application/json\""))
.build();
// if(client == null)
client = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(LoganSquareConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
return client;
}
With Subscribers, you have to call request to get items:
new WebRequestManager().getContactFlowable(userRequest)
.subscribe(new Subscriber<ResponseData>() {
#Override
public void onSubscribe(Subscription s) {
Log.e(TAG , "contact subscription ");
s.request(Long.MAX_VALUE); // <---------------------------------
}
#Override
public void onNext(ResponseData responses) {
Log.e(TAG , "contact onNext ");
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
Log.e(TAG , "contact onComplete ");
}
});
See also DisposableSubscriber with its example.

How to POST with RxJava 2 + Retrofit 2?

This question may sound like a no-brainer but I'm having a hardtime.
I can do the post with retrofit 2 this way:
class RetrofitClient {
private static Retrofit retrofit = null;
static Retrofit getClient(String baseUrl) {
if (retrofit == null) {
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
Api service interface:
#POST("postsInit")
#FormUrlEncoded
Call<InitPost> postInit(
#Field("appVersion") String versionName,
#Field("appId") String applicationId,
);
And finally:
apiService.postInit(versionName, applicationId).enqueue(new Callback<InitPost>() {
#Override
public void onResponse(#NonNull Call<InitPost> call, #NonNull Response<InitPost> response) {
if (response.isSuccessful()) {
Timber.d("post submitted to API");
getInitResponse();
}
}
#Override
public void onFailure(#NonNull Call<InitPost> call, #NonNull Throwable t) {
if (call.isCanceled()) {
Timber.e("Request was aborted");
} else {
Timber.e("Unable to submit post to API.");
}
}
});
How can I convert this to RxJava 2 ? I've already implemented the converter factory but there is no info on the internet for using rxJava 2 and retrofit 2 together.
Converting your call in RxJava code:-
apiService.postInit(versionName, applicationId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.unsubscribeOn(Schedulers.io())
.subscribe(new Subscriber<InitPost>() {
#Override
public void onSubscribe(Subscription s) {
}
#Override
public void onNext(InitPost initPost) {
}
#Override
public void onError(Throwable t) {
}
#Override
public void onComplete() {
}
});
}
Post service interface:
#POST("postsInit")
#FormUrlEncoded
Observable<InitPost> postInit(
#Field("appVersion") String versionName,
#Field("appId") String applicationId,
);

It's possible to download only one Json with retrofit2 for time?

I'm using this code to download a list of airports:
final Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.baseUrl(AirportService.SERVICE_ENDPOINT).build();
AirportService service = retrofit.create(AirportService.class);
service.getAirport()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<Airport>>()
{
#Override
public void onCompleted()
{
}
#Override
public void onError(Throwable e)
{
e.printStackTrace();
}
#Override
public void onNext(List<Airport> airports)
{
airps = airports;
}
});
with this interface:
#GET("airports.json")
Observable<List<Airport>> getAirport();
i want to know if it's possible to have in onNext() method Airport and not List . I'll try it but I've got error (because airports are about 40k) and if it's possible to add a progress bar to show the download.
Thank you for answers.

POST with Retrofit

I am creating a simple log-in/register app, consuming predefined JSON-structured data. So far I have created the GET endpoint (using retrofit)
public interface RetrofitGet {
#GET("----")
Call<User> getUserDetails();
}
EDIT: the POST endPoint:
#POST("----")
Call<User> postUserDetails();
Then I have a method, taking the entered JSON-like data and set the data as text of 2 of the fields:
private void getUser() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitGet service = retrofit.create(RetrofitGet.class);
Call<User> call = service.getUserDetails();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
try {
input_email.setText(response.body().getEmail());
input_pass.setText(response.body().getPassword());
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Throwable t) {
Log.d("onFailure", t.toString());
}
});
What I am trying to do now is to define the POST endpoint, in order to be able the data to be generated from the app (to be taken from the register form), posted on the server, and then handled in the login.
EDIT:
The method, consuming the POST endpoint so far:
private void postUser() {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.build();
RetrofitPost service = retrofit.create(RetrofitPost.class);
Call<User> call = service.postUserDetails();
call.enqueue(new Callback<User>() {
#Override
public void onResponse(Response<User> response, Retrofit retrofit) {
try {
emailRegister.getText().toString();
passRegister.getText().toString();
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
So, I have the data, entered by the user on Register, but I don't see it stored in the server and cannot handle it in the Login part.
Any help would be appreciated,
Thanks!
#POST("----")
Call<CommonBean> comment(#Body PostComment comment);
and the PostComment:
public class PostComment {
private int pcOrdersId;
private int pcStar;
private String pcComment;
public PostComment(int pcOrdersId, int pcStar, String pcComment) {
this.pcOrdersId = pcOrdersId;
this.pcStar = pcStar;
this.pcComment = pcComment;
}
}
others on different with 'GET'

Categories

Resources