I am using retrofit for parsing JSON from Api. When i am using mobile network (Not WIFI) then continuously making query to retrieve response from api sometimes getting time out error.
Code :
userLogin("Username").
enqueue(new RetrofitCallback<PatientModel>() {
#Override
public void onSuccess(PatientModel result) {
if (null != result) {
loginResponse(result);
}
}
#Override
public void onFailure(int code, String msg) {
}
#Override
public void onThrowable(Throwable t) {
}
#Override
public void onFinish() {
hideProgress();
}
});
Maybe you must increase time out. Could you try this :
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss")
.create();
okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(120, TimeUnit.SECONDS)
.readTimeout(120, TimeUnit.SECONDS)
.writeTimeout(120, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(Constants.BASE_URL).client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
apiService = retrofit.create(IService.class);
Related
Hello Guys I am trying to realtime get data when change data in API automatic referesh my layout and updated data show it. How can i do that?
Here is my Code :-
I use this Dependencies :-
// retrofit, gson
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:retrofit:2.6.1'
implementation 'com.squareup.retrofit2:converter-gson:2.6.1'
Here is my API interface method :-
#GET("get_doctor_expense_categories.php")
Call<GetExpenseCategoriesListResponse> get_doctor_expense_categories(#Query("doctor_id") String doctor_id);
And this my ApiClient :-
public class ApiClient {
private static final String ROOT_URL = "YOUR URL";
public static ApiInterface getApiService() {
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder().addInterceptor(interceptor).build();
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(15, TimeUnit.SECONDS)
.build();
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(ApiInterface.class);
}
}
And This is my API call Method Where i get Data into List :-
private void getCategories(String doctor_id) {
progressDialog = CustomProgressBar.createProgressDialog(ViewCategoriesActivity.this);
final ApiInterface api = ApiClient.getApiService();
Call<GetExpenseCategoriesListResponse> call = api.get_doctor_expense_categories(doctor_id);
call.enqueue(new Callback<GetExpenseCategoriesListResponse>() {
#SuppressLint("SetTextI18n")
#Override
public void onResponse(#NonNull Call<GetExpenseCategoriesListResponse> call, #NonNull Response<GetExpenseCategoriesListResponse> response) {
if (response.code() == 200) {
progressDialog.dismiss();
if (response.body() != null) {
if (response.body().getStatus().equalsIgnoreCase("success")) {
expanseCatList = response.body().getData();
if (expanseCatList.isEmpty()) {
txt_no_data_found.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
txt_no_data_found.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
expanseCatListAdapter = new CategoriesListAdapter(expanseCatList, ViewCategoriesActivity.this, ViewCategoriesActivity.this::catClick);
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(ViewCategoriesActivity.this, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(mLayoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(expanseCatListAdapter);
}
} else {
Toast.makeText(ViewCategoriesActivity.this, "" + response.body().getMessage(), Toast.LENGTH_SHORT).show();
}
}
} else if (response.code() == 400) {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "Bad Request", Toast.LENGTH_SHORT).show();
} else if (response.code() == 401) {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "Unauthorized User", Toast.LENGTH_SHORT).show();
} else if (response.code() == 404) {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "Not Found", Toast.LENGTH_SHORT).show();
} else if (response.code() == 500) {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "Internal Server Error", Toast.LENGTH_SHORT).show();
} else {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "Unknown Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<GetExpenseCategoriesListResponse> call, Throwable t) {
progressDialog.dismiss();
Toast.makeText(ViewCategoriesActivity.this, "onFailer: " + t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
This is not possible using retrofit if you want real time data you can use soup/socket
This is my retrofit setup.
public interface ApiInterface {
#GET("place/autocomplete/json?")
Call<ResponseBody> doPlaces(#QueryMap Map<String, String> options);}
public class RetrofitClient {
public static final String BASE_URL = Environment.getBaseUrl();
public static ApiInterface service (Context context) {
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okHttpClient = new OkHttpClient().newBuilder()
.connectTimeout(3, TimeUnit.MINUTES)
.readTimeout(3, TimeUnit.MINUTES)
.writeTimeout(3, TimeUnit.MINUTES)
.addInterceptor(logging)
.addInterceptor(new NetworkConnection(context))
.addInterceptor(new ResponseStatus(context))
.build();
ApiInterface service = new Retrofit.Builder()
.baseUrl(BASE_URL).client(okHttpClient)
.build().create(UrlServices.class);
return service;
}
public static void getContentData(final Dialog dialog, final Call<ResponseBody> method, final WebResponse webResponse) {
if (dialog != null)
AppProgressDialog.show(dialog);
method.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (dialog != null)
AppProgressDialog.hide(dialog);
JsonUtil.handleResponse(response, webResponse);
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable throwable) {
if (dialog != null)
AppProgressDialog.hide(dialog);
webResponse.onResponseFailed(throwable.getMessage());
}
});
}
}
public interface WebResponse {
void onResponseSuccess(Response<ResponseBody> result);
void onResponseFailed(String error);
}
Use in Activity/Fragment
RetrofitClient.getContentData(new Dialog(context), RetrofitClient.service(context).doPlaces(hashMap), new WebResponse() {
#Override
public void onResponseSuccess(Response<ResponseBody> result) {
}
#Override
public void onResponseFailed(String error) {
}
});
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'
Probably a novice question but I'm wondering where I actually catch the logs in log cat. Is there a particular place I put a log, a special regex to use etc. This is what my interceptor looks like:
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient okClient = new OkHttpClient.Builder().addInterceptor(interceptor).build();
// Retrofit setup
Retrofit client = new retrofit2.Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okClient)
.build();
And here is an api call where the body is null
retrofit2.Call<GeneralTokenResponse> generalTokenResponseCall = ApiInterface.getGeneralAccessToken(ApiGeneral.API_VERSION);
generalTokenResponseCall.enqueue(new retrofit2.Callback<GeneralTokenResponse>() {
#Override
public void onResponse(retrofit2.Call<GeneralTokenResponse> call, retrofit2.Response<GeneralTokenResponse> response) {
Log.d("DEBUG", "body: "+response.body());
}
#Override
public void onFailure(retrofit2.Call<GeneralTokenResponse> call, Throwable t) {
}
});
I use so:
// init okhttp 3 logger
HttpLoggingInterceptor logging = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
#Override public void log(String message) {
Log.d("MyTAG", "OkHttp: " + message);
}
});
logging.setLevel(HttpLoggingInterceptor.Level.BODY);
I am using retrofit 2.0 for network request in my project. Before making any request i am checking if user is connected with network then only proceed the request.
if(Connected()){
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://example.com/cgi-bin/")
.addConverterFactory(GsonConverterFactory.create())
.build();
APIService service = retrofit.create(APIService.class);
Call<ArrayList<Brand>> call = service.loadBrand();
call.enqueue(new Callback<ArrayList<Brand>>() {
#Override
public void onResponse(Response<ArrayList<Brand>> response , Retrofit retrofit)
{
brands = response.body();
//brands.size();
//JSONArray jsonArray_GR = response.body();
//arrayCallback.onResponse(jsonArray_GR);
}
#Override
public void onFailure(Throwable t) {
}
});
}
The problem is how to handle the case if network connection lost in between while request still not completed.
What should i check and where?
Any help will be appreciated.
#Override
public void failure(RetrofitError arg0) {
if (arg0.getCause() instanceof UnknownHostException) {
//network loss in retrofit 2.0 in android
}
}
I have this Interface:
public interface InterfazAguaHttp {
#FormUrlEncoded
#POST("/")
Call<String> saveContador(#Field("contador") Long contador, Callback<String> callBack);
}
The rest of the code is this:
Retrofit builder = new Retrofit.Builder()
.baseUrl(ValoresGlobales.urlServlet)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfazAguaHttp interfaz = builder.create(InterfazAguaHttp.class);
Call<String> respuesta = interfaz.saveContador(93847597L, new Callback<String>() {
#Override
public void onResponse(Response<String> response, Retrofit retrofit) {
//Some logging
}
#Override
public void onFailure(Throwable t) {
//Some logging
}
});
This is all inside a try-catch block. In the catch, I am receiving this error:
Error: No Retrofit annotation found. (parameter #2) for method InterfazAguaHttp.saveContador
How could I get rid of this error, and still have my callback?
Thank you.
change your interface method to this
public interface InterfazAguaHttp {
#FormUrlEncoded
#POST("/")
Call<String> saveContador(#Field("contador") Long contador);
}
and the rest of the code like this
Retrofit builder = new Retrofit.Builder()
.baseUrl(ValoresGlobales.urlServlet)
.addConverterFactory(GsonConverterFactory.create())
.build();
InterfazAguaHttp interfaz = builder.create(InterfazAguaHttp.class);
Call<String> respuesta = interfaz.saveContador(93847597L);
respuesta.enqueue(new Callback<String>() {
#Override
public void onResponse(Response<String> response, Retrofit retrofit) {
//Some logging
}
#Override
public void onFailure(Throwable t) {
//Some logging
}
});
Link for reference