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?
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 have this issue with Volley library requests. I make calls to API and since they have to be updated very often I implemented timers. After some time it throws me error:"Throwing OutOfMemoryError “pthread_create (1040KB stack) failed: Try again. I used the method which was suggested in this post: Throwing OutOfMemoryError "pthread_create (1040KB stack) failed: Try again" when doing asynchronous posts using Volley , but for me it did not work, the data coming from API stopped updating. I thought it might be something with timers or it is just something I am doing wrong using Volley.
If you have any idea, feel welcome to share.
My printer class
public void setMenuInformation(String url, Context context, final VolleyCallback callback) {
Log.d("API", "Currently calling URL " + url);
if (eRequestQueue == null) {
eRequestQueue = Volley.newRequestQueue(context);
eRequestQueue.add(new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
String temp = response.substring(2, response.length() - 2);
Log.d("API", "Current menu" + response);
byte msgArray[];
try {
msgArray = temp.getBytes("ISO-8859-1");
currentMenu = msgArray[0];
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
menuInformation = response;
callback.onSuccess(menuInformation);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("API", "Current menu Nope ");
callback.onFailure(error);
}
}));
}
}
Main Activity:
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu",
MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("NSD", "Current menu response succeded and added to array " + nsdServiceInfo);
//services.add(myPrinterDetails);
mAdapter.notifyDataSetChanged();
}
});
Log.d("NSD", "CurrentMenu " + myPrinterDetails.getMenuInformation());
myTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myPrinterDetails.setMenuInformation("http://" + nsdServiceInfo.getHost() + "/GetCurrentMenu", MainActivity.this, new PrinterNew.VolleyCallback() {
#Override
public void onSuccess(String result) {
Log.d("NSD", "Current menu response added to timer " + nsdServiceInfo);
mAdapter.notifyDataSetChanged();
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu timer failed");
}
});
}
});
}
}, 0, 2000);
}
#Override
public void onFailure(Object response) {
Log.d("NSD", "Current menu response failed");
}
});
}
};
}
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 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.
I have this project and wish to get all names from table like "1" is the first name how code this for all names
public void capturarPersonagens(View view) {
//-- Retrofit
callPersonagem = service.getPersonagem("1");
callPersonagem.enqueue(new Callback<Personagem>() {
#Override
public void onResponse(Call<Personagem> call, Response<Personagem> response) {
if (response.isSuccessful()) {
if (!call.isCanceled()) {
Log.i("Personagem",response.body().getName());
}
}
}
}
}
Best Regards
Pedro Duarte
You are missing a new method in your Service interface:
The api endpoint people/?format=json depends on the actual implementation of your webservice.
public interface Service {
#GET("people/{id}/?format=json")
Call<Personagem> getPersonagem(#Path("id") String alacazam);
#GET("people/?format=json")
Call<ArrayList<Personagem>> getPersonagens();
}
Then, you may consume it the same way you did with getPersonagem:
public void capturarPersonagens(View view) {
//-- Retrofit
callPersonagens = service.getPersonagens();
callPersonagens.enqueue(new Callback<ArrayList<Personagem>>() {
#Override
public void onResponse(Call<ArrayList<Personagem>> call, Response<ArrayList<Personagem>> response) {
if (response.isSuccessful()) {
if (!call.isCanceled()) {
for(Personagem p:response.body()){
Log.i("Personagem",p.getName());
}
}
}
}
#Override
public void onFailure(Call<ArrayList<Personagem>> call, Throwable t) {
Log.e("SW", "" + t.getMessage());
}
});
}