简体   繁体   中英

Android - Can't Fetch Data from Firebase

I am trying to fetch data from firebase but for some reason, it is not fetching the data.

My Database Structure

在此处输入图像描述

I am trying to fetch Products here. But It is not fetching anything. It just shows the null value. in the Logcat it shows no error.

Code for DisplayOrderDetails Activity .

public class DisplayOrderDetails extends AppCompatActivity {

    OrderDetailsAdapter adapter;
    DatabaseReference reference;
    FirebaseUser user;
    String userId, orderID;
    List<ProductInfo> mList;
    RecyclerView recyclerView;
    TextView textView, textView2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_order_details);

        recyclerView = findViewById(R.id.detailRecyclerView);
        textView = findViewById(R.id.displayOrderId);
        textView2 = findViewById(R.id.displayUserId);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mList = new ArrayList<>();

        user = FirebaseAuth.getInstance().getCurrentUser();
        userId = user.getUid();
        textView2.setText("userId:" + userId);

        Intent intent = getIntent();
        orderID = intent.getStringExtra(PreviousOrderAdapter.ORDER_ID);
        textView.setText("OrderId:" + orderID);

        reference = FirebaseDatabase.getInstance().getReference().child("Admin Order").
                child(userId).child(orderID);
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot childSnapshot : dataSnapshot.child("Products").getChildren()) {
                    ProductInfo orderDetails = childSnapshot.getValue(ProductInfo.class);
                    mList.add(orderDetails);
                }
                adapter = new OrderDetailsAdapter(DisplayOrderDetails.this, mList);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
    }
}

Note: The orderID and UserID are not null. I have checked it. Order Details Adapter

public class OrderDetailsAdapter extends RecyclerView.Adapter<OrderDetailsAdapter.ViewHolder> {
    Context mContext;
    List<ProductInfo> mList;

    public OrderDetailsAdapter(Context mContext, List<ProductInfo> mList) {
        this.mContext = mContext;
        this.mList = mList;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.order_details, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        ProductInfo info = mList.get(position);
        holder.productName.setText(info.getProduct_name());
        holder.productPrice.setText("₹." + info.getProduct_price());
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView productName, productPrice;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            productName = itemView.findViewById(R.id.detailsProductName);
            productPrice = itemView.findViewById(R.id.detaiProductPrice);
        }
    }
}

XMl file

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardElevation="10dp"
    android:padding="10dp"
    android:layout_marginBottom="15dp">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dp">

        <TextView
            android:id="@+id/detailsProductName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:fontFamily="@font/aclonica"
            android:text="@string/product_name"
            android:textSize="17sp"
            android:padding="5dp"/>

        <TextView
            android:id="@+id/detaiProductPrice"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_toEndOf="@+id/detailsProductName"
            android:fontFamily="@font/aclonica"
            android:gravity="right"
            android:text="@string/product_price"
            android:textSize="14sp"
            android:padding="5dp"/>
    </RelativeLayout>
</androidx.cardview.widget.CardView>

The Image. 在此处输入图像描述

ProductInfo Model

public class ProductInfo {
private String product_name;
private String product_price;
private String product_description;
private String image_url;
private String productID;


public ProductInfo(String product_name, String product_price, String product_description, String image_url, String productID) {
    if(product_name.trim().equals("")){
        product_name =  "New Product";
    }
    this.product_name = product_name;
    this.product_price = product_price;
    this.product_description = product_description;
    this.image_url = image_url;
    this.productID = productID;
}

public ProductInfo() {}

public String getProduct_name() {

    return product_name;
}
public String getProductID() {
    return productID;
}

public String getProduct_price() {
    return product_price;
}

public String getProduct_description() {
    return product_description;
}

public String getImage_url() {
    return image_url;
}

}

JSON file format

"Admin Order" : {
"ZPMej6hGreT67BpSv7P9lozMo6u1" : {
  "-M9mX557xvdF1G8w0a2d" : {
    "Order Details" : {
      "consumer" : "Harsh Ashra",
      "orderId" : "-M9mX557xvdF1G8w0a2d",
      "total" : 480
    },
    "Products" : {
      "-M9mL4UUDWwlfyDeOE9S( Back Cover )" : {
        "imageURL" : "https://firebasestorage.googleapis.com/v0/b/grocerystore-cfddc.appspot.com/o/Products%2F1592130026849.jpg?alt=media&token=ca7bcf45-6e38-47b9-8812-15f55fa25297",
        "name" : "Back Cover",
        "price" : "120",
        "productId" : "-M9mL4UUDWwlfyDeOE9S",
        "quantity" : 4
      }
    }
  },
  "-M9mdh3AJJnuEZ0COn0o" : {
    "Order Details" : {
      "consumer" : "Harsh Ashra",
      "orderId" : "-M9mdh3AJJnuEZ0COn0o",
      "total" : 12860
    },
    "Products" : {
      "-M9mL4UUDWwlfyDeOE9S( Back Cover )" : {
        "imageURL" : "https://firebasestorage.googleapis.com/v0/b/grocerystore-cfddc.appspot.com/o/Products%2F1592130026849.jpg?alt=media&token=ca7bcf45-6e38-47b9-8812-15f55fa25297",
        "name" : "Back Cover",
        "price" : "120",
        "productId" : "-M9mL4UUDWwlfyDeOE9S",
        "quantity" : 3
      },
      "-M9mTSnIgXHUjXoX7b29( helo )" : {
        "imageURL" : "https://firebasestorage.googleapis.com/v0/b/grocerystore-cfddc.appspot.com/o/Products%2F1592132223609.jpg?alt=media&token=612550d7-c7bc-4867-9157-affe14caf0c7",
        "name" : "helo",
        "price" : "2500",
        "productId" : "-M9mTSnIgXHUjXoX7b29",
        "quantity" : 5
      }
    }
  }
}

},

The problem here is you are accessing Products using dataSnapshot.child("Products").getChildren() whereas adding .child("Products") to your databaseReference should get you the Product for the orderId and userId .

   public class DisplayOrderDetails extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_order_details);

        recyclerView = findViewById(R.id.detailRecyclerView);
        textView = findViewById(R.id.displayOrderId);
        textView2 = findViewById(R.id.displayUserId);

        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        mList = new ArrayList<>();

        user = FirebaseAuth.getInstance().getCurrentUser();
        userId = user.getUid();
        textView2.setText("userId:" + userId);

        Intent intent = getIntent();
        orderID = intent.getStringExtra(PreviousOrderAdapter.ORDER_ID);
        textView.setText("OrderId:" + orderID);

        reference = FirebaseDatabase.getInstance().getReference().child("Admin Order").
                child(userId).child(orderID).child("Products");
        reference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
                    ProductInfo orderDetails = childSnapshot.getValue(ProductInfo.class);
                    mList.add(orderDetails);
                }
                adapter = new OrderDetailsAdapter(DisplayOrderDetails.this, mList);
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }

        });
    }
}

Change the ProductInfo Schema

public class ProductInfo {
    String imageURL;
    String name;
    String price;
    String productId;
    String quantity;

    // add your constructor here with your logic
    public String getImageURL() {
        return imageURL;
    }

    public void setImageURL(String imageURL) {
        this.imageURL = imageURL;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getProductId() {
        return productId;
    }

    public void setProductId(String productId) {
        this.productId = productId;
    }

    public String getQuantity() {
        return quantity;
    }

    public void setQuantity(String quantity) {
        this.quantity = quantity;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM