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();
}
});
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've been building an app which has Log In functionality. I've tested it but every time i tried to Log In, the progress bar disappeared to quickly (like a quarter second or something), and the response i get from the server is like about 2 seconds after the progress bar disappeared. Here are some of my codes.
My LoginTask inner class :
private class LoginTask extends AsyncTask<Account, Void, Account>{
private String getUsername = username.getText().toString();
private String getPassword = password.getText().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
//showDialog();
progressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Account account) {
super.onPostExecute(account);
//dismissDialog();
progressBar.setVisibility(View.GONE);
}
#Override
protected Account doInBackground(Account... accounts) {
getLogin(getUsername, getPassword);
return null;
}
}
Login Retrofit call to server
private void getLogin(String email, String password) {
Call<LoginAuth> call = userService.getLogin(email, password);
call.enqueue(new Callback<LoginAuth>() {
#Override
public void onResponse(Call<LoginAuth> call, Response<LoginAuth> response) {
try {
if (response.body().getToken_type().equals("xxx")) {
Log.i(TAG, "getLogin, Authorized access");
Log.i(TAG, "getLogin, access_token: " + response.body().getAccess_token().toString());
Log.i(TAG, "getLogin, expires_at" + response.body().getExpires_at().toString());
} else {
Log.e(TAG, "getLogin, Unauthorized access" + response.body().getToken_type().toString());
}
} catch (Exception e) {
Log.e(TAG, "getLogin exception " + e.getMessage());
}
}
#Override
public void onFailure(Call<LoginAuth> call, Throwable t) {
Log.e(TAG, "getLogin, onFailure : " + t.getMessage());
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(LoginActivity.this, "Unable to Log In :(", Toast.LENGTH_SHORT).show();
}
});
}
});
}
I want it to work like when the response is fetched, that's the time the progress bar disappeared (not instantly). Did i do something wrong with the code?
As you are using retrofit, there is no necessity to call your api in separate asynctask as retrofit manages it asynchronously. what you should do is show your progressbar before you call api and dismiss it in onResponse and onFailure both. so your code would change to something like below.
private void getLogin(String email, String password) {
progressBar.setVisibility(View.VISIBLE);
Call<LoginAuth> call = userService.getLogin(email, password);
call.enqueue(new Callback<LoginAuth>() {
#Override
public void onResponse(Call<LoginAuth> call, Response<LoginAuth> response) {
progressBar.setVisibility(View.Gone);
//rest of your code
}
#Override
public void onFailure(Call<LoginAuth> call, Throwable t) {
Log.e(TAG, "getLogin, onFailure : " + t.getMessage());
progressBar.setVisibility(View.Gone);
//rest of your code
}
});
}
I am using retrofit to authenticate user but when wrong input is entered, response code is 200 and the next activity starts.
public void serverLogin(){
// Create handle for the RetrofitInstance interface
apiInterface = RetrofitInstance.getRetrofitInstance().create(APIInterface.class);
UserModel userModel = new UserModel();
userModel.setUsername(username);
userModel.setPassword(password);
Call<IDModel> activate = apiInterface.userLogin(userModel);
activate.enqueue(new Callback<IDModel>() {
#Override
public void onResponse(Call<IDModel> call, Response<IDModel> response) {
if (response.isSuccessful()) {
int statusCode = response.code();
response.body();
customerID = response.body().getCustomer_id();
subID = response.body().getSub_id();
idDB.addCustomerID(customerID, subID);
session.setLoggedIn(true);
Intent intent = new Intent(Login.this, Drawer.class);
intent.putExtra("cusID", customerID);
startActivity(intent);
Toast.makeText(Login.this, "SUCCESS", Toast.LENGTH_SHORT).show();
Log.d("onresponse", "" + statusCode);
}
else {
Toast.makeText(Login.this, "Login failed", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<IDModel> call, Throwable t) {
Toast.makeText(Login.this, "" + t.getMessage(), Toast.LENGTH_SHORT).show();
Log.d("onfailure"," " + t . getMessage());
}
});
}
The else part always gets skipped. When it is not successful, I want to notify the user and not start next activity.
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.