Wrong Data Received from Firebase - android

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.

Related

How to complete search in firebase i.e inside every nodes and sub-nodes and even sub-sub nodes if available

How to search in nodes and sub sub nodes because there are different users with different various types of ids inside
I have done this:
public int finddupuser(final String name){
final int[] check = {0};
mUserDatabase=FirebaseDatabase.getInstance().getReference().child("Users");
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
alladmin fam_mem=userSnapshot.getValue(alladmin.class);
if(fam_mem.getName().equals(name)) {
check[0] =1;
}
for(DataSnapshot userSnapshot2: userSnapshot.getChildren()){
allfamily fam_mem2=userSnapshot2.getValue(allfamily.class);
if(fam_mem2.getName().equals(name)) {
check[0] =1;
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, "find="+check[0], Toast.LENGTH_SHORT).show();
return check[0];
}
But it is not checking in sub-sub nodes
my json file looks like this
{
"Users" : {
"gptshubham595" : {
"familymember" : {
"11111" : {
"name" : "ABCD"
"22222":{
"name" : "ABCDE"
}
}
},
"TOTAL_FAMILY_MEMBER" : "1",
"name" : "ABC",
}
}
}
It would have better if you have added the POJO classes for alladmin and allfamily.
And the json file you have added seems to be in an incorrect format. At least it is missing few brackets and commas.
Anyways, What you are trying to do is clear. But the method you've used is not necessary and bit of unclear. If you have created the POJO classes correctly, you can do something like below. For ease of mine, i'll add my own definition of POJO classes below. You can get the idea from it and modify it as you want.
AllAdmin.java
public class AllAdmin {
private String name = '';
private List<AllFamily> familyMembers = null;
private String totalFamilyNumber = ''; //Here you may use the preferred data type, i'll use string for ease.
public AllAdmin() {};
public void setName(String name) {this.name = name};
public String getName(){return this.name};
public void setFamilyMembers(List<AllFamily> members) {
if (familyMembers == null) {
familyMembers = new ArrayList<AllFamily>();
}
//This part depends on how you want to add new members.
familyMember.addAll(members);
}
public List<AllFamily> getFamilyMembers() {
if(familyMembers != null){
return this.familyMembers;
} else {
return new ArrayList<AllFamily>();
}
}
public void setTotalFamilyNumber(String number){this.totalFamilyNumber = number};
public String getTotalFamilyNumber(){return this.totalFamilyNumber}
}
AllFamily.Java
public class AllFamily{
private String name = '';
//Is this all(if so use of separate POJO class is unnecessary), this node is not clear in the json you've added.
public AllFamily(){};
public void setName(String name) {this.name = name};
public String getName(){return this.name};
}
Then to the querying part. Additionally i have used boolean for conditional states. Also make a note of simple java naming conventions i've used with camel-case syntax's. Following these conventions is not necessary, but it improves the readability of a code and comes handy in these kind of platforms since it improves the possibility of understanding the code just by reading it.
public boolean findDupUser(final String name){
final boolean[] check = {false};
mUserDatabase = FirebaseDatabase.getInstance().getReference().child("Users");
mUserDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()){
AllAdmin allAdmin = userSnapshot.getValue(AllAdmin.class);
if(allAdmin.getName().equals(name) || allAdmin.getFamilyMembers().contains(name)) {
check[0] = true;
}
}
}
});
Toast.makeText(this, "find="+check[0], Toast.LENGTH_SHORT).show();
return check[0];
}
Note: Above code is for the logic of checking whether an individual already exists in the database as an user himself or as a family member of an existing user.

ViewModel + Livedata + Databinding + Transformations... How to?

I'm trying to transform a response from server to my databinding object... I didn't understand too much how i make that with the Transformations of livedata...
I think i'm i need to change few things, but i didnt find what i need to change...
:(
When i call loadSellers(), it dont enter on switchMap function
Can someone help me?
public class SellersViewModel extends BaseViewModel {
private EzGasRepository repository;
private MutableLiveData<List<Seller>> sellers;
#Inject
public SellersViewModel(EzGasRepository repository) {
this.repository = repository;
}
public LiveData<List<Seller>> fetchAllSellers() {
if (sellers == null) {
sellers = new MutableLiveData<>();
loadSellers();
}
return sellers;
}
private LiveData<List<Seller>> loadSellers() {
return Transformations.switchMap(repository.fetchAllSellers(), input -> {
List<Seller> sellerList = new ArrayList<>();
for (SellerResponse sellerResponse: input) {
Seller seller = new Seller();
seller.setSellerName(sellerResponse.getName());
seller.setRating(sellerResponse.getRating());
seller.setProductValue(sellerResponse.getProduct().getValue());
seller.setSellerAddress(sellerResponse.getAddress().getFormattedAddress());
sellerList.add(seller);
}
return sellers;
});
}
}
This is my repository
public LiveData<List<SellerResponse>> fetchAllSellers() {
MutableLiveData<List<SellerResponse>> data = new MutableLiveData<>();
ezGasApi.fetchAllSellers().enqueue(new Callback<List<SellerResponse>>() {
#Override
public void onResponse(Call<List<SellerResponse>> call, Response<List<SellerResponse>> response) {
if(response.isSuccessful()) {
data.setValue(response.body());
} else {
//data.setValue(response.errorBody());
}
}
#Override
public void onFailure(Call<List<SellerResponse>> call, Throwable t) {
//data.setValue(t.getMessage());
Timber.e(t);
}
});
return data;
}
This is my View
viewModel.fetchAllSellers().observe(this, response -> {
});

How to get array values without null : Retrofit 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

returning 2 json values from firebase but one of them is always null? Why?

I'm not an experienced android app developer this only my first app, with that said here is my problem. I am taking the value of "company_name" from the manager's Json area by calling the dataSnapshot from addListenerForSingleValueEvent and than putting the value into the the recipient's Json area(I'm also storing the manager's id "manager_id" in the recipient's Json area), so far that works OK. The problem now is reading the value "company_name" from the recipient's area to populate it in a list using firebaseUI, for some rason I can't figure out why "manager_id" is returned as as a string but "company_name" is null. Here is the code:
Getting the value for the "company_name":
mManagersCompany.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
companyName = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Storing it in the recipient's area:
Map<String, Object> info = new HashMap<>();
info.put("company_name", companyName);
info.put("manager_id", manager_id);
mListOfManagers.push().updateChildren(info);
object:
public class CompanyItem {
private String company_name;
private String manager_id;
public CompanyItem(){}
public CompanyItem(String company_name, String manager_id){
this.company_name = company_name;
this.manager_id = manager_id;
}
public String getCompanyName() {
return company_name;
}
public void setCompanyName(String companyName) {
this.company_name = companyName;
}
public String getManager_id() {
return manager_id;
}
public void setManager_id(String manager_id_entering) {
this.manager_id = manager_id_entering;
}
}
retrieve "manager_id" and "company_name" with populateViewHolder of firebaseUI:
#Override
protected void populateViewHolder(CompanyViewHolder viewHolder, CompanyItem model, int position) {
viewHolder.hText.setText(model.getCompanyName());
viewHolder.mText.setText(model.getManager_id());
}
Here is part of the recipient's Json in firebase database:
{ "-KYVoYBRD4UEBL6GYKD_" :
{
"company_name" : "Dude Company",
"manager_id" : "a1b2c3d4"
}
}
Why does it return "a1b2c3d4" for the "manager_id" but null for "company_name"? I tried so many different things but I wasn't successful, and I searched through stackoverflow for an answer but couldn't find one that is close to my problem. Can anyone help please?
As per my comment
change your setter/getter for company_name to match the format of manager_id –
for example
getCompanyName() to getCompany_name()

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