In my Main Activity i execute SincronizacionDb to compare the data between SQLite and the MYSQL Server, however the json_array retrieved works fine, it's show true or false if the data it's different from the server, but in the APP, this value seems to be always false.
SincronizacionDb
private void sincronizacionDB() {
if (dbCheck(MainActivity.this, "beneficiosColaborador.db")) {
int size = sqLiteHandler.getLastIdBeneficio();
Call<VersionDb> versionDb = restManager.getApiService().checkServerDatabaseVersion(size);
versionDb.enqueue(new Callback<VersionDb>() {
#Override
public void onResponse(Call<VersionDb> call, Response<VersionDb> response) {
Log.e("RESPONSE", "CALLING ON RESPONSE");
VersionDb version = response.body();
isOutdate = version.getEstado();
Log.i("VERSION", "RESPUESTA" + version.getEstado()); // Get the value from GSon(TRUE, FALSE) WORKS PERFECT
}
#Override
public void onFailure(Call<VersionDb> call, Throwable t) {
Log.e("error", t.getMessage());
}
});
Log.e("outdate","" + isOutdate); // ALWAYS FALSE
if (isOutdate) {
sqLiteHandler.deleteBeneficio();
Log.e("Beneficios", "Se han eliminado los beneficios viejos");
Call<List<Beneficios>> callBeneficios = restManager.getApiService().getListadoBeneficios();
callBeneficios.enqueue(new Callback<List<Beneficios>>() {
#Override
public void onResponse(Call<List<Beneficios>> call, Response<List<Beneficios>> response) {
List<Beneficios> beneficioData = response.body();
sqLiteHandler.addListBeneficios(beneficioData);
}
#Override
public void onFailure(Call<List<Beneficios>> call, Throwable t) {
Log.e("error", t.getMessage());
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}else{
Call<List<Beneficios>> callBeneficios = restManager.getApiService().getListadoBeneficios();
callBeneficios.enqueue(new Callback<List<Beneficios>>() {
#Override
public void onResponse(Call<List<Beneficios>> call, Response<List<Beneficios>> response) {
List<Beneficios> beneficioData = response.body();
sqLiteHandler.addListBeneficios(beneficioData);
}
#Override
public void onFailure(Call<List<Beneficios>> call, Throwable t) {
Log.e("error", t.getMessage());
//Toast.makeText(MainActivity.this, t.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
and the Results i got in the ANDROID MONITOR
08-11 08:39:31.417 13618-13618/com.freelance.crdzbird_dev.clarobadge D/SQLiteHandler: Fetching LAST ROW from Sqlite: 213
08-11 08:39:31.617 13618-13618/com.freelance.crdzbird_dev.clarobadge E/outdate: false
08-11 08:39:31.867 13618-13618/com.freelance.crdzbird_dev.clarobadge E/RESPONSE: CALLING ON RESPONSE
08-11 08:39:31.867 13618-13618/com.freelance.crdzbird_dev.clarobadge I/VERSION: RESPUESTA true
Please someone explain me how to avoid this error :(
It seems that you are doing an asynchrounous call in here :
versionDb.enqueue(new Callback<VersionDb>() {
#Override
public void onResponse(Call<VersionDb> call, Response<VersionDb> response) {
Log.e("RESPONSE", "CALLING ON RESPONSE");
VersionDb version = response.body();
isOutdate = version.getEstado();
Log.i("VERSION", "RESPUESTA" + version.getEstado()); // Get the value from GSon(TRUE, FALSE) WORKS PERFECT
}
#Override
public void onFailure(Call<VersionDb> call, Throwable t) {
Log.e("error", t.getMessage());
}
});
And your value of isOutdate is initialized at false, so it will be always false since it executes the check before returning from the service.
So either wait for your callback or use the synchronized method execute in retrofit.
Related
Activity
#Override
protected void onResume() {
super.onResume();
getCartList();
}
private void getCartList() {
showProgressDialog();
Call<List<CartList>> call = api.getCartList(1);
call.enqueue(new Callback<List<CartList>>() {
#Override
public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
cartLists = response.body();
if (cartLists.size() == 0) {
tvCartEmpty.setVisibility(View.VISIBLE);
progressDialog.cancel();
} else {
addToCartAdapter.setData(cartLists);
productList.setAdapter(addToCartAdapter);
progressDialog.cancel();
}
}
#Override
public void onFailure(Call<List<CartList>> call, Throwable t) {
Toast.makeText(AddToCartActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void deleteItemID(int id) {
Call<CartList> deleteCall = api.deleteCartItem(id);
deleteCall.enqueue(new Callback<CartList>() {
#Override
public void onResponse(Call<CartList> call, Response<CartList> response) {
Log.d(TAG, "deleteItem by id" + response.code());
onResume();
}
#Override
public void onFailure(Call<CartList> call, Throwable t) {
Log.d(TAG, t.getMessage());
}
});
}
i mean last is deleting but not updating on the spot even though i called onresume in delete item method.
i have to open that activity again to see updted result
i hope i will get my query solved soon!
thanks
if you want i will upload inteface and adapter code. which i do not think necessary here.
Solution
just had to add this in response class
public void onResponse(Call<List<CartList>> call, Response<List<CartList>> response) {
cartLists = response.body();
if (cartLists.size() == 0) {
tvCartEmpty.setVisibility(View.VISIBLE);
tvCartItems.setText("0 items");
addToCartAdapter.setData(cartLists);
progressDialog.cancel();
} else {
addToCartAdapter.setData(cartLists);
productList.setAdapter(addToCartAdapter);
tvCartItems.setText(cartLists.size() + " Items");
progressDialog.cancel();
}
}
you don't need to call onResume() again.
instead of that you should use the following snippet:
cartLists.removeAt(id);
addToCartAdapter.notifyDataSetChanged();
your deleteItem function would look like below code:
#Override
public void deleteItemID(int id) {
Call<CartList> deleteCall = api.deleteCartItem(id);
deleteCall.enqueue(new Callback<CartList>() {
#Override
public void onResponse(Call<CartList> call, Response<CartList> response) {
Log.d(TAG, "deleteItem by id" + response.code());
cartLists.removeAt(id);
addToCartAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Call<CartList> call, Throwable t) {
Log.d(TAG, t.getMessage());
}
});
I got an error of Expected Begin_ARRAY. but was BEGIN_OBJECTS at line 1 column
I am trying to get data from URL into recyclerview
api = RetrofitClient.getApiClient().create(Api.class);
Call<List<Courses>> call = api.getallcourse();
call.enqueue(new Callback<List<Courses>>()
{
#Override
public void onResponse(Call<List<Courses>> call, Response<List<Courses>> response) {
Toast.makeText(Dashboard.this, ""+response.toString(), Toast.LENGTH_SHORT).show();
courses = response.body();
recyclerAdapter = new RecyclerAdapter(courses);
recyclerView.setAdapter(recyclerAdapter);
}
#Override
public void onFailure(Call<List<Courses>> call, Throwable t) {
Toast.makeText(Dashboard.this, ""+t.toString(), Toast.LENGTH_SHORT).show();
}
});
i have two methods in my api which i have to call independently because each of them return a different object and actually when i tested it worked perfectly but the problem is when i have to test it a second time it bugs . and I want to make sure my code is correct or not .
IFiche IFiche = APIClient.getClient().create(IFiche.class);
String ItemsSP = GetItemSelectedSP();
String ItemsAntc = GetItemSelectedAntc();
IFiche.add(Double.parseDouble(age.getText().toString()), Double.parseDouble(EVA.getText().toString())
, ItemsSP, ItemsAntc, motif.getText().toString(), total_score,Integer.parseInt(ID))
.enqueue(new Callback<FichePatient>() {
#Override
public void onResponse(Call<FichePatient> call, Response<FichePatient> response) {
Toast.makeText(getApplicationContext(), "Succees", Toast.LENGTH_LONG).show();
IUser IUser = APIClient.getClient().create(IUser.class);
IUser.affecterliste_fiche(Integer.parseInt(ID), Integer.parseInt(response.body().getId()),
total_score).enqueue(new Callback<Users>() {
#Override
public void onResponse(Call<Users> call, Response<Users> response) {
Toast.makeText(getApplicationContext(), "HIIIIII", Toast.LENGTH_LONG).show();
response.body().setLastScore(total_score);
Intent intent= new Intent(getApplicationContext(),NavigationActivity.class);
startActivity(intent);
}
#Override
public void onFailure(Call<Users> call, Throwable t)
{
Toast.makeText(getApplicationContext(), "NOOO", Toast.LENGTH_LONG).show();
Log.v("TAG!!!!!!!!!!", "error " + t.getMessage());
}
});
}
#Override
public void onFailure(Call<FichePatient> call, Throwable t) {
Log.v("TAG!!!!!!!!!!!", "error " + t.getMessage());
Toast.makeText(getApplicationContext(), "erreur", Toast.LENGTH_LONG).show();
}
});
hi i am using retrofit my callback is as follow
#Override
public void onResponse(final Call<T> call, Response<T> response) {
if (response.isSuccessful()) {
passing this to my view
} else {
// as this failed other then 200 retroCallback.onFailure(call, new Throwable(""));
}
}
#Override
public void onFailure(Call<T> call, Throwable t) {
retroCallback.onFailure(call, t);
}
so in this how i can pass my ErrorBean instead of Throwable anyway we can pass custom model in onFailure ? as my server giving me response in some formate i want to pass that format .. i am using retrofit 2.1.0
You can subclass Throwable and pass additional object using composition.
public class ErrorBean extends Throwable {
public ErrorPayload payload = null;
public ErrorBean(ErrorPayload payload) {
this.payload = payload;
}
}
Then, in onError:
#Override
public void onFailure(Call<T> call, Throwable t) {
retroCallback.onFailure(call, t);
if (t instanceof ErrorBean) {
// do your stuff here
((ErrorBean)t).payload.text;
}
}
AFAIK,, Retrofit's onFailure is used for handling errors like no internet connection.
To handle the error response from your Server, Error response, I mean response from Server with 4xx status code but with some JSON response for client to handle it.
Say, you are getting this error structure from Server:
{
statusCode: 409,
message: "Email address already registered"
}
This error will be captured in onResponse(...). To handle this, create your
public class ErrorBean {
private int statusCode;
private String message;
public ErrorBean() {
}
public int status() {
return statusCode;
}
public String message() {
return message;
}
}
Create a simple ErrorHandler util:
public class ErrorUtils {
public static ErrorBean parseError(Response<?> response) {
Converter<ResponseBody, ErrorBean> converter =
ServiceGenerator.retrofit()
.responseBodyConverter(ErrorBean.class, new Annotation[0]);
ErrorBean error;
try {
error = converter.convert(response.errorBody());
} catch (IOException e) {
return new ErrorBean();
}
return error;
}
}
And finally,
...
call.enqueue(new Callback<SuccessResponse>() {
#Override
public void onResponse(Call<SuccessResponse> call, Response<SuccessResponse> response) {
if (response.isSuccessful()) {
// use response data and do some fancy stuff :)
} else {
// parse the response body …
ErrorBean error = ErrorUtils.parseError(response);
// … and use it to show error information
// … or just log the issue like we’re doing :)
Log.d("error message", error.message());
}
}
#Override
public void onFailure(Call<User> call, Throwable t) {
// there is more than just a failing request (like: no internet connection)
}
});
Hope you got the point..!!!
I am using Retrofit 2.0 to make api calls with nesting multiple requests. All api's works fine individually.
But when i nested all retrofit, First request execute perfectly but after that when i register second request it's not callback in enqueue method (i.e. it's directly returning null without inserting enqueue's inner methods like onResponse, onFailure)
My Code :-
public class Main2Activity extends AppCompatActivity {
Gson gson;
JSONObject jsonResult=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
gson=new GsonBuilder().create();
firstRequest(); //-- First retrofit request
}
private void firstRequest() {
Retrofit retrofit=new Retrofit.Builder().baseUrl(getResources().getString(R.string.Api_Url)).addConverterFactory(GsonConverterFactory.create(gson)).build();
CityRetailsApi service = retrofit.create(CityRetailsApi.class);
Call call_first= service.getMainCatFlag();
call_first.enqueue(new Callback() {
#Override
public void onResponse(Call call, Response response) {
Log.d("MainActivity", "Status Code = " + response.code());
if (response.isSuccessful()){
MainCatFlag result = (MainCatFlag) response.body(); //-- Get First request response
JSONObject json2nd = secondRequest(); //-- Second request
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}
private JSONObject secondRequest() {
try {
Retrofit retrofit=new Retrofit.Builder().baseUrl(getResources().getString(R.string.Api_Url)).addConverterFactory(GsonConverterFactory.create(gson)).build();
CityRetailsApi service = retrofit.create(CityRetailsApi.class);
Call call_second= service.getMainCat();
call_second.enqueue(new Callback() {
#Override
public void onResponse(Call call2, Response response1) {
Log.d("MainActivity", "Status Code = " + response1.code());
if (response1.isSuccessful()) {
MainCat result = (MainCat) response1.body();
if (result.getSuccess()==1)
{
try {
jsonResult= new JSONObject(new Gson().toJson(result));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}catch (Exception e){
Log.d("MainActivity", "Error= " + e);
}
return jsonResult;
}
}
In above code firstRequest() executed correctly and proving response but the secondRequest (inside firstRequest() enqueue method) not working fine. Not showing any error, success message in console. Can any one please help me to override this problem.
If any problem in my code, please let me know.
Thank you in advance.
You made a mistake that when you using retrofit enquene,it's called asynchronously, so you can't get the result outside of the callback method!
So, you should process your result inside the onResponse method like this:
private void secondRequest() {
try {
call_second.enqueue(new Callback() {
#Override
public void onResponse(Call call2, Response response1) {
Log.d("MainActivity", "Status Code = " + response1.code());
if (response1.isSuccessful()) {
MainCat result = (MainCat) response1.body();
if (result.getSuccess()==1)
{
try {
jsonResult= new JSONObject(new Gson().toJson(result));
// process your jsonResult here
...
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
#Override
public void onFailure(Call call, Throwable t) {
Log.d("MainActivity", "Error");
}
});
}catch (Exception e){
Log.d("MainActivity", "Error= " + e);
}
}