1

I have an array of data which I am retrieving from firebase. I am using a recyclerview to display the data but my adapter is not working correctly.I tried adding the arraylist in the adapter but this is not working. It is saying the adapter is not attached and I am having a blank activity.

Any help on this ? Here are my details.

Modal Class

public class Order {
    private String ProductId;
    private String ProductName;
    private String Quantity;

    public Order() {
    }

    public String getProductId() {
        return ProductId;
    }

    public void setProductId(String productId) {
        ProductId = productId;
    }

    public String getProductName() {
        return ProductName;
    }

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

    public String getQuantity() {
        return Quantity;
    }

    public void setQuantity(String quantity) {
        Quantity = quantity;
    }

    public Order(String productId, String productName, String quantity) {
        ProductId = productId;
        ProductName = productName;
        Quantity = quantity;
    }

}

Adapter

public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersViewHolder> {

    List<Order> myfoods;

    public AllOrdersAdapter(List<Order> myfoods) {
        this.myfoods = myfoods;
    }

    @NonNull
    @Override
    public AllOrdersViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.allorders_layout,parent,false);
        return new AllOrdersViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(@NonNull AllOrdersViewHolder holder, int position) {
        holder.foodname.setText(myfoods.get(position).getProductName());
        holder.foodquantity.setText(myfoods.get(position).getQuantity());
        holder.foodId.setText(myfoods.get(position).getProductId());
    }

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


}

Test Class

public class Test extends AppCompatActivity {

    FirebaseDatabase db;
    DatabaseReference requests;
    RecyclerView lstFoods;
    RecyclerView.LayoutManager layoutManager;
    TextView food_id,food_quan,food_name;
//    List foods = new ArrayList<>();
//    RecyclerView.Adapter<AllOrder> adapter;
//    List<String> myOrders = new ArrayList<String>();

//    ArrayList<String> foods=new ArrayList<>();
    List<String> myfoods = new ArrayList<String>();
    AllOrdersAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        //firebase
        db = FirebaseDatabase.getInstance();
        requests= db.getReference().child("Requests");

        lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
        lstFoods.setHasFixedSize(true);
        layoutManager = new LinearLayoutManager(this);
        lstFoods.setLayoutManager(layoutManager);

        loadOrderss();

    }
    private void loadOrderss() {

        requests.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                    if (postSnapshot.getValue() != null) {
//                        List ingredients = new ArrayList<>();
                        for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
//                            String data = String.valueOf(postSnapshot.getValue(Order.class));
                            myfoods.add(ing.child("quantity").getValue(String.class));
                            myfoods.add(ing.child("productName").getValue(String.class));
                            myfoods.add(ing.child("productId").getValue(String.class));
//                            myfoods.add(String.valueOf(Order.class));
                            System.out.println("Gained data: " + ing.child("productName").getValue(String.class));

                        }

                    }
                }
                adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
                lstFoods.setAdapter(adapter);
               adapter.notifyDataSetChanged();
            }

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

            }
        });
            }
Stefano Tokyo
  • 85
  • 1
  • 10

2 Answers2

1

There seems to be a couple things wrong with the code. As it is posted I would be surprised if it compiles.

In your Adapter you have:

List<Order> myfoods;

and

public AllOrdersAdapter(List<Order> myfoods) {
    this.myfoods = myfoods;
}

but in your activity code you pass:

adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);

one is a ArrayList of String the other of Order !

You also need to change your adapter class to something like:

public class AllOrdersAdapter extends RecyclerView.Adapter<AllOrdersAdapter.AllOrdersViewHolder> {
    private static final String TAG = AllOrdersAdapter.class.getSimpleName();

    private ArrayList<Order> mData;

    public class AllOrdersViewHolder extends RecyclerView.ViewHolder {
        public TextView mTvFoodname;
        public TextView mTvFoodQuantity;
        public TextView mTvFoodId;

        public AllOrdersViewHolder(View v){
            super(v);
            // TODO:  You need to assign the appropriate View Id's instead of the placeholders ????
            mTvFoodQuantity = v.findViewById(R.id.????);
            mTvFoodname = v.findViewById(R.id.????);
            mTvFoodId = v.findViewById(R.id.????);
        }
    }


    public AllOrdersAdapter(ArrayList<Order> data){
        this.mData = data;
    }


    @Override
    public AllOrdersViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
        View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.business_list_card_view, parent, false);
        return new AllOrdersViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(final AllOrdersViewHolder holder, final int position){
        //TODO: You need to decide whether you want to pass a string or order object
        Order data = mData.get(position);

        final String name = data.getProductName();
        final String quantity = data.getQuantity();
        final String id = data.getProductId();


        holder.mTvFoodname.setText(name);
        holder.mTvFoodQuantity.setText(quantity );
        holder.mTvFoodId.setText(id)
    }


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

Note: That since I can not know, whether an ArrayList of String or of Order should be used the parameters in either the Activity or Adapter will need to be changed. Also how you assign the data to the RecyclerView will be affected in the onBindViewHolder method.

You should also follow the advice given by Frank.


EDIT

Change your onDataChange() method to this:

@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
        if (postSnapshot.getValue() != null) {
            List ingredients = new ArrayList<>();
            for (DataSnapshot ing : postSnapshot.child("foods").getChildren()) {
                String name = ing.child("productName").getValue(String.class);
                String quantity = ing.child("quantity").getValue(String.class);
                String productId = ing.child("productId").getValue(String.class);
                // Using your overloaded class constructor to populate the Order data
                Order order = new Order(productId, name, quantity);

                // here we are adding the order to the ArrayList
                myfoods.add(order);
                Log.e(TAG, "Gained data: " + name)
            }
        }
    }
    adapter.notifyDataSetChanged();
}

In your Activity you will need to change the ArrayList class variable "myfoods" to this:

ArrayList(Order) myfoods = new ArrayList<>();

and in your onCreate() method you can now change:

adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);

to simply this:

adapter = new AllOrdersAdapter(myfoods);

Also notice that I have made some changes in my original code above.

Barns
  • 4,850
  • 3
  • 17
  • 31
  • I have a modal class called Order , thats why I am using it in my arraylist , so that I can get the setter and getters methods. – Stefano Tokyo Sep 16 '18 at 00:41
  • Okay I have added the Order Class – Stefano Tokyo Sep 16 '18 at 00:46
  • Thank you a lot , it works fine now. Btw one more little question , is it possible to group common data ? For example group the quantity of the foods with the same productId and display it in the recycler ? – Stefano Tokyo Sep 16 '18 at 01:28
  • Glad It works for you, now. --- Yes, theoretically you could construct any type of groups you want. You could create a query for your database selecting all orders with a specific product id then put them in an `ArrayList` so that you could display the data in a new `RecyclerView`. Go ahead and attempt it. If you have any issues, just post a new question. I will look for your you new question...but probably someone will beat me to it. Happy Coding... – Barns Sep 16 '18 at 01:34
0

You'll want to create the adapter, and attach it to the view, straight in onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_test);
    //firebase
    db = FirebaseDatabase.getInstance();
    requests= db.getReference().child("Requests");

    lstFoods = (RecyclerView)findViewById(R.id.lstAllFoods);
    lstFoods.setHasFixedSize(true);
    layoutManager = new LinearLayoutManager(this);
    lstFoods.setLayoutManager(layoutManager);

    adapter = new AllOrdersAdapter((ArrayList<String>) myfoods);
    lstFoods.setAdapter(adapter);

    loadOrders();
}

This also means you should declare myfoods as a ArrayList<String>, which saves you from having to downcast it. Something like:

ArrayList<String> myfoods = new ArrayList<String>();

Now in loadOrders you simple add the items to the list, and then notify the adapter that its data has changed (so that it repaints the view):

private void loadOrders() {
    requests.child("foods").addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
                for (DataSnapshot ing: postSnapshot.getChildren()) {
                    myfoods.add(ing.child("quantity").getValue(String.class));
                    myfoods.add(ing.child("productName").getValue(String.class));
                    myfoods.add(ing.child("productId").getValue(String.class));
                }
            }
           adapter.notifyDataSetChanged();
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            throw databaseError.toException(); // don't ignore errors
        }
    });
  }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807