How to get array values without null : Retrofit Android - android

i'm using retrofit for service calls.it's return 5 data sets.each data set contain 6 values.each data set contain one actual values and others are null.how can get actual values without null values?
POST man response is like bellow
{
"status": true,
"message": "successfully count new orders",
"data": [
{
"order_count": "3"
},
{
"pending_order": "0"
},
{
"schedule": "2017-11-18 12:00",
"id_order": "272",
"reference": "KB-838704"
},
{
"deli_orders": "0"
},
{
"store_count": "0"
}
]
}
Webservice call
WebserviceAPI apiService =retrofit.create(WebserviceAPI.class);
Call<OrderResponse> call = apiService.getSummery("countnew",token_acces);
call.enqueue(new Callback<OrderResponse>() {
#Override
public void onResponse(Call<OrderResponse> call, Response<OrderResponse> response) {
OrderResponse result = response.body();
List<Order> data=result.getData();
status=result.isStatus();
msg= result.getMessage();
for (Order a:data)
{
try {
Log.d("ress",""+a.getOrder_count()+" : "+a.getPending_order()+" : "+a.getReference()
+" : "+a.getSchedule()+" : "+a.getDeli_orders()+" : "+a.getStore_count());
//update
if( !(a.getOrder_count().contentEquals("null"))){
Log.d("ress","new order "+a.getOrder_count());
//txtNewOrder.setText(a.getOrder_count());
}
if( !(a.getPending_order().contentEquals("null"))){
Log.d("ress","pending "+a.getPending_order());
// txtPendingOrder.setText(a.getPending_order());
}
if( !(a.getReference().contentEquals("null"))){
Log.d("ress","reference "+a.getReference());
//txtRecentOrder.setText(a.getReference());
}
if( !(a.getSchedule().contentEquals("null"))){
Log.d("ress","time "+a.getSchedule());
//txtRemainingTime.setText(a.getSchedule());
}
if( !(a.getDeli_orders().contentEquals("null"))){
Log.d("ress"," delivered "+a.getDeli_orders());
//txtDeliveredOrder.setText(a.getDeli_orders());
}
if( !(a.getStore_count().contentEquals("null"))){
Log.d("ress","store "+a.getStore_count());
//txtStoreOrder.setText(a.getStore_count());
}
}catch (NullPointerException e){
}
}
}
#Override
public void onFailure(Call<OrderResponse> call, Throwable t) {
Log.d("fragres",""+t.getMessage());
}
});
Update : Order.java
public class Order {
String order_count;
String pending_order;
String schedule;
String id_order;
String reference;
String deli_orders;
String store_count;
public String getOrder_count() {
return order_count;
}
public void setOrder_count(String order_count) {
this.order_count = order_count;
}
public String getPending_order() {
return pending_order;
}
public void setPending_order(String pending_order) {
this.pending_order = pending_order;
}
public String getSchedule() {
return schedule;
}
public void setSchedule(String schedule) {
this.schedule = schedule;
}
public String getId_order() {
return id_order;
}
public void setId_order(String id_order) {
this.id_order = id_order;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDeli_orders() {
return deli_orders;
}
public void setDeli_orders(String deli_orders) {
this.deli_orders = deli_orders;
}
public String getStore_count() {
return store_count;
}
public void setStore_count(String store_count) {
this.store_count = store_count;
}
}
Logcat
when i check null inside for loop,it's display only first value (num 3)
i want to get :
1st value from 1 data set,2 nd value from 2nd data set,3rd and 4th value from 3 data set,5th value from 4th data set,6th value from 5th data set

Related

How to wait for the retrofit call response

I have my own rest api for application so when I create post request to api I want to wait for the response and then do something. how I can wait for the call response.
insert TicketList
public long insertApi(TicketListTable ticketListTable) throws IOException {
Call<TicketListTable> ticketListTableCall = dataService.createTicketList(ticketListTable);
ticketListTableCall.enqueue(new Callback<TicketListTable>() {
#Override
public void onResponse(Call<TicketListTable> call, Response<TicketListTable> response) {
}
#Override
public void onFailure(Call<TicketListTable> call, Throwable t) {
}
});
// want to wait for the call to complete then return the value
//ticketListTableCall.execute();
Log.d("CODE", "insertApi: "+ ticketListTableCall.isExecuted());
return repo.insert(ticketListTable);
}
this method is called when button is clicked
public void saveListToDb(String[] split, String regexData){
String newListName = listName.getText().toString();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
TicketListTable newTicketListTable = new TicketListTable();
newTicketListTable.setTicketListName(newListName);
newTicketListTable.setTicketListCreated(sd.format(Calendar.getInstance().getTime()));
newTicketListTable.setTicketListUpdated(sd.format(Calendar.getInstance().getTime()));
long ticketTableListId = 0;
try {
ticketTableListId = ticketTableVm.insert(newTicketListTable);
} catch (IOException e) {
e.printStackTrace();
}
if(ticketTableListId<=0){
throw new ArithmeticException();
}
for (String s : split) {
String[] values = s.split(regexData);
String number = values[0].replace("\n", "").replace("\r", "");
String info = values[1];
String warningNote = values[2];
String warning = values[3];
String customer = values[4];
int useable = Integer.parseInt(values[5].replaceAll("\\s+", "").replace("\n", "").replace("\r", ""));
TicketTable ticketTable = new TicketTable(number, customer, info, warningNote, useable, ticketTableListId,warning);
ticketTableVm.insert(ticketTable);
}
}
insert Ticket api call, before calling this I want to verify that the previous call has been successfully executed
public void insert(TicketTable ticketTable) throws IOException {
Call<TicketTable> ticketCall = dataService.createTicket(ticketTable);
//Response resp = ticketCall.execute();
ticketCall.enqueue(new Callback<TicketTable>() {
#Override
public void onResponse(Call<TicketTable> call, Response<TicketTable> response) {
repo.insert(ticketTable);
}
#Override
public void onFailure(Call<TicketTable> call, Throwable t) {
}
});

Display and hide progress bar using MVVM pattern

I am working with MVVM pattern. I have just started it and i have done it successfully.
But I don't understand how to add progress bar for showing and hide as we normally do for API calls.
I am not using data binding. So how can i use progress bar for showing and hide it.
For Login
public class LoginRepository {
private DATAModel dataModel = new DATAModel();
private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
private Application application;
public LoginRepository(Application application) {
this.application = application;
}
public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {
APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);
JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);
Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
call.enqueue(new Callback<APIResponseLogin>() {
#Override
public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
APIResponseLogin apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatuscode() == 0) {
if (apiResponse.getDataModel() != null) {
dataModel = apiResponse.getDataModel();
mutableLiveData.setValue(dataModel);
}
} else if (apiResponse != null && apiResponse.getStatuscode() == 1) {
Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
}
}
#Override
public void onFailure(Call<APIResponseLogin> call, Throwable t) {
Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
}
});
return mutableLiveData;
}
Activity Code
void loginCall() {
loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
#Override
public void onChanged(#Nullable DATAModel dataModel) {
if (dataModel != null) {
Userdetails userdetails = dataModel.getUserdetails();
List<ContactTypes> contactTypes = dataModel.getContactTypes();
if (userdetails != null) {
MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
}
if (contactTypes != null) {
MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
}
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
}
Advanced help would be appreciated!
When you call api that time you have to take one live variable which shows your api is in loading mode or not and after success or failure you have to update that variable.
After observe that variable in your activity or fragment class and show or hide your progress.
public class LoginRepository {
private DATAModel dataModel = new DATAModel();
private MutableLiveData<DATAModel> mutableLiveData = new MutableLiveData<>();
private Application application;
private MutableLiveData<Boolean> progressbarObservable;
public LoginRepository(Application application) {
this.application = application;
}
public MutableLiveData<DATAModel> getMutableLiveData(String username, String password) {
// add below line
progressbarObservable.value = true
APIRequest apiRequest = RetrofitRequest.getRetrofit().create(APIRequest.class);
JsonLogin jsonLogin = new JsonLogin(Constants.DEVICE_TYPE, Functions.getDeviceId(application.getApplicationContext()), Constants.APP_VERSION, Constants.API_VERSION, Functions.getTimeStamp(), Functions.getDeviceModel(), Build.VERSION.RELEASE, username, password);
Call<APIResponseLogin> call = apiRequest.getUsersDetails(jsonLogin);
call.enqueue(new Callback<APIResponseLogin>() {
#Override
public void onResponse(Call<APIResponseLogin> call, Response<APIResponseLogin> response) {
// add below line
progressbarObservable.value = false
APIResponseLogin apiResponse = response.body();
if (apiResponse != null && apiResponse.getStatuscode() == 0) {
if (apiResponse.getDataModel() != null) {
dataModel = apiResponse.getDataModel();
mutableLiveData.setValue(dataModel);
}
} else if (apiResponse != null && apiResponse.getStatuscode() == 1) {
Log.v("AAAAAAAAA", apiResponse.getStatusmessage());
}
}
#Override
public void onFailure(Call<APIResponseLogin> call, Throwable t) {
// add below line
progressbarObservable.value = false
Log.v("ErrorResponse", t.getMessage() + " : " + call.request().toString());
}
});
return mutableLiveData;
}
}
Now, observe above variable in activity or fragment and based on that value hide or show your progress bar
public class LoginActivity extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
...
observeLogin();
}
#Override
public void onClick(View view)
{
switch (view.getId()) {
case R.id.button_login:
// Do something
loginCall();
}
}
private void observeLogin() {
loginViewModel.progressbarObservable().observe(this, new Observer<Boolean>() {
#Override
public void onChanged(final Boolean progressObserve) {
if(progressObserve){
show your progress
}
else {
hide your progress
}
}
});
}
void loginCall() {
loginViewModel.getUserDetails(editTextUsername.getText().toString().trim(), editTextPassword.getText().toString().trim()).observe(this, new Observer<DATAModel>() {
#Override
public void onChanged(#Nullable DATAModel dataModel) {
if (dataModel != null) {
Userdetails userdetails = dataModel.getUserdetails();
List<ContactTypes> contactTypes = dataModel.getContactTypes();
if (userdetails != null) {
MySharedPreferences.setCustomPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USERDETAILS, userdetails);
MySharedPreferences.setStringPreference(LoginActivity.this, Constants.SHAREDPREFERENCE_USER_ID, userdetails.getUserId());
}
if (contactTypes != null) {
MySharedPreferences.setCustomArrayList(LoginActivity.this, Constants.SHAREDPREFERENCE_CONTACTTYPES, contactTypes);
}
Intent i = new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}
});
}
}
I find it easier to write my own callback interface in this situation. Just not that this will be done synchronously so all will wait until your api call responds. But in such a case, a progress dialog would be havin the similar effect.
1.Create inteface:
public interface ProgressCallback{
void onDone(String message);
void onFail(String message);
}
Now in your method where you call the API
loginUser(String name, String password, ProgressCallback
progressCallback){
call.enqueue(new Callback<LoginData>() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onResponse(Call<LoginData> call, Response<LoginData> response) {
progressCallBack.onSuccess(response.message());
}
#Override
public void onFailure(Call<LoginData> call, Throwable t) {
progressCallBack.onFail(t.getMessage());
}
});
Now when you call the method
loginUser("John#doe.com", "applesgravity", new ProgressCallBack() {
#Override
public void onSuccess(String message) {
progressBar.setVisibility(View.INVISIBLE);
}
#Override
public void onFail(String message) {
progressBar.setVisibility(View.INVISIBLE);
}
});

UI didn't updated using Rxjava with CompositeSubscription

I have used rxjava and retrofit to load data from backend and update the UI.
But there is no data displayed on section view. I have tested it, and the backend data load successful and the UI can be updated using fake data.
Are there something wrong when I use Rxjava?
private void retrieveCardInfo(String stripeId, String userToken) {
subscriptions.add(NetworkUtil.getRetrofit(userToken).getCustomerInfo(new GetCustomer(stripeId))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleCustomerResponse, this::handleError));
}
private void handleCustomerResponse(CreateStripeCustomerResponse response) {
if (response.getSuccess()) {
updateCardList(response);
bankSection.setState(Section.State.EMPTY);
} else {
Utils.toast(this,"Get credit card failed");
}
}
private void updateCardList(CreateStripeCustomerResponse response) {
List<CardInfo> cardList = response.getCustomer().getSources().getData();
if (cardList == null || cardList.size() == 0) {
cardSection.setState(Section.State.EMPTY);
} else {
list = new ArrayList<>();
for (int i = 0; i < cardList.size(); i++) {
CardInfo cardInfo = cardList.get(i);
String brand = cardInfo.getBrand();
String subTitle = cardInfo.getFunding() + "****" + cardInfo.getLast4();
list.add(new PaymentAccountItem(brand, subTitle, cardDrawable.get(brand)));
}
list.add(new PaymentAccountItem("title", "subtitle", R.drawable.ic__credit_amex_svg));
cardSection.swipeData(list);
}
}
private void handleError(Throwable throwable) {
}
// works fine without sectionedAdapter.notifyDataSetChanged(); when using fake data,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
ButterKnife.bind(this);
subscriptions = new CompositeSubscription();
initialToolbar();
initialRecyclerView();
initialPaymentData();
}
private void initialPaymentData() {
stripeIdAndToken = Utils.getStripeIdAndToken(this);
if (TextUtils.isEmpty(stripeIdAndToken.first)) {
cardSection.setState(Section.State.EMPTY);
bankSection.setState(Section.State.EMPTY);
} else {
initialCardDrawableResource();
retrieveCardInfo(stripeIdAndToken.first, stripeIdAndToken.second);
}
// fake data here
// initialCardDrawableResource();
// list = new ArrayList<>();
// list.add(new PaymentCreditCardItem("Visa", "123456", 10, 2018, cardDrawable.get("Visa")));
// cardSection.swipeData(list);
}
private void initialCardDrawableResource() {
cardDrawable = new HashMap<>();
cardDrawable.put("Visa", R.drawable.ic_visa_svg);
cardDrawable.put("Discover", R.drawable.ic_discover_svg);
cardDrawable.put("American Express", R.drawable.ic__credit_amex_svg);
cardDrawable.put("Mastercard", R.drawable.cio_ic_mastercard);
}
private void retrieveCardInfo(String stripeId, String token) {
subscriptions.add(NetworkUtil.getRetrofit(token).getCustomerInfo(new GetCustomer(stripeId))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::handleCustomerResponse, this::handleError));
}
private void handleCustomerResponse(CreateStripeCustomerResponse response) {
if (response.getSuccess()) {
updateCardList(response);
} else {
Utils.toast(this, "Get credit card failed");
}
}
private void updateCardList(CreateStripeCustomerResponse response) {
List<CardInfo> cardList = response.getCustomer().getSources().getData();
if (cardList == null || cardList.size() == 0) {
cardSection.setState(Section.State.EMPTY);
} else {
list = new ArrayList<>();
for (int i = 0; i < cardList.size(); i++) {
CardInfo cardInfo = cardList.get(i);
String brand = cardInfo.getBrand();
String cardNum = cardInfo.getFunding() + "****" + cardInfo.getLast4();
list.add(new PaymentCreditCardItem(brand, cardNum, cardInfo.getExpMonth(), cardInfo.getExpYear(), cardDrawable.get(brand)));
}
cardSection.swipeData(list);
sectionedAdapter.notifyDataSetChanged();
}
}
private void handleError(Throwable throwable) {
}
private void initialRecyclerView() {
sectionedAdapter = new SectionedRecyclerViewAdapter();
cardSection = new PaymentCardAndAccountSection(this, R.layout.header_card, R.layout.payment_card_empty_view);
bankSection = new PaymentCardAndAccountSection(this, R.layout.header_bank, R.layout.payment_account_empty_view);
sectionedAdapter.addSection(cardSection);
sectionedAdapter.addSection(bankSection);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(sectionedAdapter);
bankSection.setState(Section.State.EMPTY);
}
private void initialToolbar() {
toolbar.setTitle("Payment");
toolbar.setNavigationIcon(R.drawable.ic_back_svg);
setSupportActionBar(toolbar);
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
#OnClick(R.id.fab_add_payment)
void launchAddPaymentDialog() {
AddPaymentDialogFragment addPaymentDialogFragment = AddPaymentDialogFragment.newInstance();
addPaymentDialogFragment.setStyle(DialogFragment.STYLE_NO_FRAME, 0);
addPaymentDialogFragment.show(getSupportFragmentManager(), "dialog");
}
#Override
public void onPause() {
super.onPause();
if (subscriptions != null) {
subscriptions.clear();
}
}
Do you use an adapter? In this case adapter.notifyDataSetChanged();
Also, print yout error: throwable.printStackTrace(); in order to see if something goes wrong.
You need to add .observeOn(AndroidSchedulers.mainThread()) after you write subsribeOn() to tell your observable to perform your onNext callback on UI thread/MainThread.

Wrong Data Received from Firebase

I'm trying to get the data from Firebase, but when I debug my app I can see that the app has found the key I put, but I received no data on the value:
DatabaseReference taxiref = childRef.child(chapa);
taxiref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Sesion.taxis.add(dataSnapshot.getValue(Taxi.class));
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
As you can see in the following code, that my structure from Firebase:
"taxis" : {
"bbb222" : {
"año" : 1998,
"modelo" : "Gol",
"ubicaciones" : {
"u1" : {
"fecha" : "20-12-2016 12:30",
"latitud" : 31231231,
"longitud" : 2131241
},
"u2" : {
"fecha" : "20-12-2016 12:31",
"latitud" : 31231232,
"longitud" : 2131243
}
}
},
And as you can see on the following image when I debugged the code the key I got is correct, but I didn't receive any value, could somebody help me with that?
Here its the taxi.java class:
public class Taxi {
private String año;
private String modelo;
private String chapaTaxi;
private LinkedList<Ubicaciones> ubicaciones;
public void diagramarRecorrido() {
for (Ubicaciones u : getUbicaciones()) {
u.ubicarMapa();
}
}
public String getAño() {
return año;
}
public void setAño(String año) {
this.año = año;
}
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getChapaTaxi() {
return chapaTaxi;
}
public void setChapaTaxi(String chapaTaxi) {
this.chapaTaxi = chapaTaxi;
}
public LinkedList<Ubicaciones> getUbicaciones() {
return ubicaciones;
}
public void setUbicaciones(LinkedList<Ubicaciones> ubicaciones) {
this.ubicaciones = ubicaciones;
}
}
Sorry guys my bad, childRef was a variable:
private static DatabaseReference childRef= ref.child("taxis");
and that was the problem as you can see the child its taxis but I had Taxis thats why I never got any results from the firebase, thanks to all for all your help.

Display the ArrayList values into TextVitew

Am working on one android project. i stored the getting response in the ArrayList while parsing from the JsonArray. now i want just display the values to required text views.
Here am doing.
public void updateRedemptionRequestDetails(){
//Dismiss dialog
dlgProgress.dismiss();
// Get the status
String status=redemptionRequestDetailsResponse.getStatus();
if(status.equals("success")){
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = redemptionRequestDetailsResponse.getData();
if(!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0 ){
redemptionRequestDetailsResources.addAll(redemptionRequestDetailsResource);
populateRedemptionDetails(redemptionRequestDetailsResources);
}
}else if ( status.equals("failed")) {
//Show toast based on error code
generalMethods.showToastMessage(context,redemptionRequestDetailsResponse.getErrorcode());
}
}
Can anyone please shed some lights on this.how can i get the values in specified string and display them.
Here my model class
public class RedemptionRequestDetailsResource {
private String rdmId;
private String rdmUniqueBatchTrackingId;
private String rdmLoyaltyId;
private String rdmStatus;
private String rdmCashPaymentStatus;
private String rdmProductCode;
public String getRdmId() {
return rdmId;
}
public void setRdmId(String rdmId) {
this.rdmId = rdmId;
}
public String getRdmUniqueBatchTrackingId() {
return rdmUniqueBatchTrackingId;
}
public void setRdmUniqueBatchTrackingId(String rdmUniqueBatchTrackingId) {
this.rdmUniqueBatchTrackingId = rdmUniqueBatchTrackingId;
}
public String getRdmLoyaltyId() {
return rdmLoyaltyId;
}
public void setRdmLoyaltyId(String rdmLoyaltyId) {
this.rdmLoyaltyId = rdmLoyaltyId;
}
public String getRdmStatus() {
return rdmStatus;
}
public void setRdmStatus(String rdmStatus) {
this.rdmStatus = rdmStatus;
}
public String getRdmCashPaymentStatus() {
return rdmCashPaymentStatus;
}
public void setRdmCashPaymentStatus(String rdmCashPaymentStatus) {
this.rdmCashPaymentStatus = rdmCashPaymentStatus;
}
public String getRdmProductCode() {
return rdmProductCode;
}
public void setRdmProductCode(String rdmProductCode) {
this.rdmProductCode = rdmProductCode;
}
}
here my populateRedemptionDetails method
public void populateRedemptionDetails(List<RedemptionRequestDetailsResource> requestDetailsResource) {
List<RedemptionRequestDetailsResource> redemptionRequestDetailsResource = requestDetailsResource;
TextView txtLoyaltyId = (TextView)rootView.findViewById(R.id.txtLoyaltyId);
txtLoyaltyId.setText(redemptionRequestDetailsResource.getRdmLoylatyId());
}
i tried like this but it throwing error.
The if condition is wrong, it will never enter:
if (!redemptionRequestDetailsResource.isEmpty() && redemptionRequestDetailsResource.size()==0) {
}
it should be:
if (!redemptionRequestDetailsResource.isEmpty()) {}
also, small tip, when using equals, you should put the constant on the left side of the call, like this:
"success".equals(status)
this is to prevent NullPointerExceptions

Categories

Resources