Home > other >  How to add an item to RecyclerView from another class
How to add an item to RecyclerView from another class

Time:01-23

As the title says, I'm trying to add an item from a different class. I get no errors but the item doesn't appear. I've read about updating the recyclerview but I'm still not sure how to do this. Below is the code.

The home page is where the list will be shown and the floating action button will redirect the user to the add item page. Here the user will enter the name, price, description, etc. After pressing the button to add the item, it redirects the user back to the home page and the list should update.

Home.java

public class Home extends AppCompatActivity{

private FirebaseAuth mAuth;

private FloatingActionButton addItemFab;

private RecyclerView recyclerView;

// The adapter is responsible for loading the items in the recycler view we need. This ensures good performance
private RecyclerView.Adapter adapter;
// The layout manager is responsible for laying out the items in the Recycler view
private RecyclerView.LayoutManager layoutManager;

private ArrayList<Item> itemList;

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

    // Initialize Firebase Auth
    mAuth = FirebaseAuth.getInstance();

    // floating action button to add an item page
    addItemFab = findViewById(R.id.addItemFab);

    addItemFab.setOnClickListener(view -> {
        Intent intent = new Intent(Home.this, AddItem.class);
        startActivity(intent);
    });

    itemList = new ArrayList<Item>();

    // add item for testing
    itemList.add(new Item(R.drawable.ic_logo, "Baby Stroller", "A stroller for baby", "59.99"));

    recyclerView = findViewById(R.id.recyclerView);
    recyclerView.setHasFixedSize(true);

    layoutManager = new LinearLayoutManager(this);
    adapter = new Adapter(itemList);

    adapter.notifyItemInserted(itemList.size()-1);

    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(adapter);

}

// log out back to start page
public void goToStart(View view){
    Intent intent = new Intent(this, MainActivity.class);
    startActivity(intent);
}

}

Adapter.java

public class Adapter extends RecyclerView.Adapter<Adapter.ViewHolder>{

private ArrayList<Item> ItemList;

public static class ViewHolder extends RecyclerView.ViewHolder{
    public ImageView item_image;
    public TextView item_name;
    public TextView item_desc;
    public TextView item_price;

    public ViewHolder(@NonNull View itemView) {
        super(itemView);

        item_image = itemView.findViewById(R.id.item_image);
        item_name = itemView.findViewById(R.id.item_name);
        item_desc = itemView.findViewById(R.id.desc);
        item_price = itemView.findViewById(R.id.price);
    }
}

public Adapter(ArrayList<Item> itemList) {ItemList = itemList;}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_items, parent, false);
    ViewHolder vh = new ViewHolder(v);

    return vh;
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    Item currentItem = ItemList.get(position);
    holder.item_image.setImageResource(currentItem.getItemImage());
    holder.item_name.setText(currentItem.getItemName());
    holder.item_desc.setText(currentItem.getItemDesc());
    holder.item_price.setText(currentItem.getItemPrice());
}

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

}

Item.java

public class Item {
private int itemImage;
private String itemName;
private String itemDesc;
private String itemPrice;

public Item(int itemImage, String itemName, String itemDesc, String itemPrice){
    this.itemImage = itemImage;
    this.itemName = itemName;
    this.itemDesc = itemDesc;
    this.itemPrice = itemPrice;
}

public int getItemImage(){return itemImage;}

public String getItemName(){return itemName;}

public String getItemDesc(){return itemDesc;}

public String getItemPrice(){return itemPrice;}

}

AddItem.java

public class AddItem extends AppCompatActivity {

ImageView itemImage;
EditText itemName;
EditText itemPrice;
EditText itemDesc;

private ArrayList<Item> itemList;

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

    itemImage = findViewById(R.id.image_holder);
    itemName = findViewById(R.id.add_item_name);
    itemPrice = findViewById(R.id.add_price);
    itemDesc = findViewById(R.id.add_desc);

    itemList = new ArrayList<Item>();

}

public void addItem(View view) {
    itemList.add(new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString()));
    Intent intent = new Intent(this, Home.class);
    startActivity(intent);
}

}

Thanks for the help.

CodePudding user response:

You should not be updating itemList in AddItem because this array have nothing to do whith the list of your recyclerView, what you should do instead is : Start the AddActivity -> let the user create the Item object -> return the object to the HomeActivity and update your recyclerView there

To do that you can use StartActivityForResult by declaring it in your homeActivity and launch it in FAB:

 ActivityResultLauncher<Intent> mStartForResult =
        registerForActivityResult(new
                        ActivityResultContracts.StartActivityForResult(),
                result -> {
                    if (result.getResultCode() == Activity.RESULT_OK) {
                        Intent intent = result.getData();
                        Item item = (Item) intent.getParcelableExtra("myItem");
                        adapter.addItem(item);
                    }
                });

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    addItemFab.setOnClickListener(view -> {
        Intent intent = new Intent(Home.this, AddItem.class);
        startActivity(intent);
    });
}

With the method addItem in your adapter as :

public void addItem(Item item){
   ItemList.add(item)
   this.notifyDataSetChanged()
}

And you would send back your item in AddItem like that :

 public void addItem(View view) {
    Item newItem = new Item(R.drawable.ic_logo, itemName.getText().toString(), itemPrice.getText().toString(), itemDesc.getText().toString());
    Intent resultIntent = new Intent();
    resultIntent.putExtra("myItem", newItem);
    setResult(RESULT_OK, resultIntent);
    finish();
}

Your Item should implement Parcelable to be able to be accepted in the intent

You can read more about how to communicate between activity here : https://developer.android.com/training/basics/intents/result

And more about Recycler view here : https://developer.android.com/develop/ui/views/layout/recyclerview

  • Related