Search code examples
javaandroidarraylistandroid-custom-view

How to pass data between ArrayLists?


im new with android studio and im having trouble on how can I pass some specific data/s from one arraylist to another arraylist. Im currently working on with an ordering system. Iam trying to add the specific data (Name, Price & Qty) from my Arraylist to my Arraylist if Qty > 0.

Edited: ProductList

public class product_List extends ListFragment{
ArrayList<product> productList;
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        productList = new ArrayList<product>;

        productList.add(new product("Pasta 1", $10.00, 0(this is for Quantity), R.drawable.pastaIcon1));

        }
}

OrderList

public class order_List extends ListFragment {

ArrayList<order> orderList;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        orderList = new ArrayList<order>;

        // HERE I want to add the product/s if its quantity > 0
        }
}

I have a separate class for the product.class(string, double, int, int) and order.class(string, double, int). I also have an arrayAdapter for productlist that has buttons that will increment/decrement the quantity of the product.


Solution

  • Generally, with the code you've given you can't simply "pass" data between those ArrayList because they are different types, which is not an Android development problem, but purely Java.

    Follow this pattern, and you can "pass data between lists", but the overall solution here, is to restructure your code to follow Object Oriented Principles.

    class Product {
        int id; // Some unique identifer
        String name; // What the product is called
        double cost; // What it costs
        int resourceId; // A resource ID for Android to draw for this
    }
    

    Then, a "coffee" class is too descriptive, rather it is just a "product", where a "coffee" is the instance of that product.

    Product coffee = new Product("coffee");
    ArrayList<Product> orders1 = new ArrayList<>();
    orders.add(coffee);
    
    ArrayList<Product> orders2 = new ArrayList<>();
    orders2.add(orders1.get(0)); // "passing"
    

    You could make an Order class that extends Product, but that doesn't seem entirely necessary; an ArrayList<Product> can be considered an instance of orders, or product inventory, for example.


    More advanced Android-related topics involve implementing Parcelable for that Product class. But, with the above idea in mind, it all comes down to structuring your code more cleanly.