Why does my progress bar not working properly? - android

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
}
});
}

Related

recycelrview adapter last item is not updating after deleting using retrofit , i am using interface because have to pass product id

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());
}
});

How to get https status code in Retrofit RxJava Android?

Before I always used retrofit to load data. It's very easy to handle or get status code of the response.
But now I want to use Retrofit with RxJava but I don't know how to handle or get the https status code of the response in onNext method.
progressDialog.show();
Observable<ResponseData> observable = apiService.getData();
compositeDisposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<ResponseData>() {
#Override
public void onNext(ResponseData responseData) {
Log.e("pppp", "onNext: " + responseData.toString());
}
#Override
public void onError(Throwable e) {
progressDialog.dismiss();
Log.e("pppp", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
progressDialog.dismiss();
Log.e("pppp", "onComplete");
}
})
);
Everyone, please help me to solve this problem.
Thanks!
You should wrap your ResponseData inside Response as
Observable<Response<ResponseData>> observable = apiService.getData();
Then inside onNext
#Override
public void onNext(Resposne<ResponseData> response) {
int statusCode = response.code();
}
and for error
#Override
public void onError(Throwable e) {
((HttpException) e).code();
}
responseData.code gives you the status code
int statusCode = responseData.code();
for getting status
Observable<ResponseData> observable = apiService.getData();
compositeDisposable.add(observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(new DisposableObserver<ResponseData>() {
#Override
public void onNext(ResponseData responseData) {
int statusCode = responseData.code();
// here you get your status code
Log.e("statusCode ", "onNext: " + statusCode );
}
#Override
public void onError(Throwable e) {
progressDialog.dismiss();
Log.e("pppp", "onError: " + e.getMessage());
}
#Override
public void onComplete() {
progressDialog.dismiss();
Log.e("pppp", "onComplete");
}
})
);

Error when calling RokoAccount.logout()?

I am integrating ROKO Mobi into my Android app.
I am trying to call RokoAccount.logout() after I call RokoAccount.setUser() but I see the following error message in my client-side console log when I try to do this.
E/btLogout: failure string: {"apiStatusCode":"AccessDenied","apiStatusMessage":"User not authorized for this action."}
Why am I receiving this?
It's possible you're seeing this error because RokoAccount.setUser() executes asynchronously.
The code snippet below calls RokoAccount.logout() in an asynchronous fashion, give it a shot!
RokoAccount.setUser(this, "UserA#referrals.com", null, null, new ResponseCallback() {
#Override
public void success(Response response) {
User userA = RokoAccount.getLoginUser(InfoActivity.this);
final String userAreferralCode = userA.referralCode;
Log.i("userA.referralCode", "refCode = " + userAreferralCode);
// call logout() in the asynchronous success callback of setUser()
RokoAccount.logout(InfoActivity.this, new ResponseCallback() {
#Override
public void success(Response response) {
Log.i("btLogout", "success response: " + response.body);
}
#Override
public void failure(Response response) {
Log.e("btLogout", "failure string: " + response.body);
}
});
}
#Override
public void failure(Response response) {
}
});

enqueue multiple GET request when using nested retrofit 2.0

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);
}
}

Android Retrofit start another request from success method

I'm using retrofit to add a task.
private void addTask(Map<String, String> map) {
ApiClient.getPptApiClient().addTask(map, new Callback<String>() {
#Override
public void success(String s, Response response) {
Log.d("TAG", "add task success");
downloadTasks(id)
}
#Override
public void failure(RetrofitError retrofitError) {
Log.d("TAG", "add task failed");
}
});
}
after add task succes i want to refresh my list, and for that i have method below:
private void downloadTasks(int id) {
ApiClient.getPptApiClient().getTasks(id, new Callback<ArrayList<TaskModel>>() {
#Override
public void success(ArrayList<TaskModel> taskModels, Response response) {
Log.d("TAG", "download task success");
taskAdapter.clear();
taskAdapter.addAll(taskModels);
lvTasks.setAdapter(taskAdapter);
}
#Override
public void failure(RetrofitError retrofitError) {
Log.e("TAG", "download task failed");
}
});
}
My problem is : downloadTask is never called.
Can you explain why?

Categories

Resources