0

How can I retrieve data from products in my orders child Firebase Realtime Database:

This is my Orders_class

this class contains only orderId and Order full pay

package com.example.safetysouq.Orders_Classes;

public class Orders_Class {
    String OrderId,FullPay,ProductName;

    public String getProductName() {
        return ProductName;
    }

    public void setProductName(String productName) {
        ProductName = productName;
    }

    public String getFullPay() {
        return FullPay;
    }

    public void setFullPay(String fullPay) {
        FullPay = fullPay;
    }

    public String getOrderId() {
        return OrderId;
    }

    public void setOrderId(String orderId) {
        OrderId = orderId;
    }
}

this is my Orders_adapter

this class contains only orderId and Order full pay

public class Orders_Adapter extends BaseAdapter {
    ArrayList<Order_Item_Class>orderItemClassArrayList;
    Orders_Item_Adapter ordersItemAdapter;
    
    Context context;
    DatabaseReference databaseReference,databaseReference2;
    FirebaseAuth firebaseAuth;
    ArrayList<Orders_Class>ordersClassArrayList;
    ArrayList<SingleCartProductInformationDataClass>singleCartProductInformationDataClassArrayList;
    LayoutInflater layoutInflater;


    public Orders_Adapter(Context context, DatabaseReference databaseReference, FirebaseAuth firebaseAuth, ArrayList<Orders_Class> ordersClassArrayList) {
        this.context = context;
        this.databaseReference = databaseReference;
        this.firebaseAuth = firebaseAuth;
        this.ordersClassArrayList = ordersClassArrayList;
    }

    @Override
    public int getCount() {
        return ordersClassArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (layoutInflater==null){
            layoutInflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        if(convertView==null){
            convertView =layoutInflater.inflate(R.layout.orders_gridview,null);
        }
        TextView orders_id =convertView.findViewById(R.id.orderid);
        TextView order_total_price = convertView.findViewById(R.id.ordertotalprice);
        GridView order_item_grid_view = convertView.findViewById(R.id.ordersitemsgridview);

        orders_id.setText("Order ID : "+"#"+ordersClassArrayList.get(position).getOrderId());
        order_total_price.setText("Total Money : "+ordersClassArrayList.get(position).getFullPay()+" EGP");

        return convertView;
    }
}

this is my Orders_page(activity)

package com.example.safetysouq.Orders_Classes;

import android.os.Bundle;
import android.widget.GridView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.safetysouq.R;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;

import java.util.ArrayList;

public class Orders_Page extends AppCompatActivity {
    private GridView ordersGridview;
    private ArrayList<Orders_Class> ordersClassArrayList;
    private Orders_Adapter ordersAdapter;
    private DatabaseReference databaseReference;
    private FirebaseAuth firebaseAuth;
    private String name;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orders_page);
        ordersGridview=findViewById(R.id.ordersGridview);
        databaseReference = FirebaseDatabase.getInstance().getReference();
        firebaseAuth= FirebaseAuth.getInstance();

        databaseReference=FirebaseDatabase.getInstance().getReference().child("Orders").child(firebaseAuth.getCurrentUser().getUid());
        ordersClassArrayList=new ArrayList<>();
        ordersAdapter = new Orders_Adapter(Orders_Page.this,databaseReference,firebaseAuth,ordersClassArrayList);
        ordersGridview.setAdapter(ordersAdapter);
        databaseReference.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                for(DataSnapshot dataSnapshot:snapshot.getChildren()){
                    Orders_Class ordersClass = dataSnapshot.getValue(Orders_Class.class);
                    ordersClassArrayList.add(ordersClass);
                }
                ordersAdapter.notifyDataSetChanged();
            }
            @Override
            public void onCancelled(@NonNull DatabaseError error) {

            }
        });
    }
}
7
  • What is the value of ordersClassArrayList.get(position).getOrderId() inside your DatabaseReference object?
    – Alex Mamo
    Commented Jul 4, 2024 at 10:00
  • And what's your goal, to get a single object or multiple object within the UID node?
    – Alex Mamo
    Commented Jul 4, 2024 at 10:01
  • @AlexMamo i added all my code and what i need is to get all data inside orders all orders with their ids and even products inside each order names,prices not only the order id and full pay Commented Jul 4, 2024 at 10:33
  • So to understand better, you need to get all orders of all users that exist right under the orders node, right?
    – Alex Mamo
    Commented Jul 4, 2024 at 10:54
  • 1
    @AlexMamo This question is about the Realtime Database, so please don't add a Firestore tag to it. The fact that your answer mentions Firestore is fine, but does not change the fact that the question is solely about Realtime Database. Commented Jul 4, 2024 at 14:05

1 Answer 1

0

You're getting the following error:

Can't convert object of type java.lang.String to type Orders_Class

Because you have created a reference that points to:

db/Orders/$uid

And when you're looping through the results trying to convert the children into objects of type Orders_Class, that is indeed not possible, because, inside that node, there are only strings, represented by the UIDs, not Orders_Class objects, hence the error.

To get all orders of all users that exist right under the orders node, you have to create a reference that points to the orders node, not to the node that corresponds to a single user, and then listen for real-time updates, like in the following lines of code:

DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference ordersRef = db.child("Orders");
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        for(DataSnapshot uidSnapshot : dataSnapshot.getChildren()) {
            for(DataSnapshot orderSnapshot : uidSnapshot.getChildren()) {
                Orders_Class order = orderSnapshot.getValue(Orders_Class.class);
                Log.d("TAG", order.toString());
            }
        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError error) {
        Log.d("TAG", error.getMessage()); //Never ignore potential errors!
    }
};

As you can see, you have to loop twice in order to get the order objects from the database.

However, this solution will only work, if the names of fields inside the class match the ones in the database. So for more info, please check my answer from the following post:

If you consider at some point in time trying to use Cloud Firestore, I recommend you use the following schema:

db
|
--- users (collection)
     |
     --- $uid (document)
          |
          --- order (sub-collection)
               |
               --- $orderId (document)
                    |
                    --- //Order fields

And use a collection group query, to get all orders of all users, in a simpler and elegant way.

1
  • Hey Mustafa. Have you tried my solution above, does it work for you?
    – Alex Mamo
    Commented Jul 5, 2024 at 5:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.