Healthware

Healthware

Evelyn

Evelyn

July 1,2023

1 hour read

#mobile #android #e-commerce

Introduction

This is a simple Android ordering system for Healthware, a healthcare company offering products like hair care, vitamins, skincare, and more. With a user-friendly UI built in Android Studio and powered by Firebase, it’s all about making shopping easy and convenient.

Application Features

  1. User login and registration
  2. View list of products with details
  3. Add items to cart
  4. Calculate the total price of the items added to the cart
  5. Check out
  6. View Order History
  7. Edit profile

Print Screen and Code

1. Login Page

login_page.png
When the app opens, the login page appears to authenticate users. It includes fields for Email and Password, plus Login and Sign-Up buttons.

1.1 Handling Login for Users without an Account (Register Page)

register_page.png
If users don’t have an account, they can click Sign-Up to create one where they’ll enter their username, email, contact number, and password. After clicking “Register Now”, users are sent back to the Login Page to verify their new account. Once the correct info is entered, they’re authenticated, logged in, and can start using the app. A** toast message** pops up saying, “You are logged in!”

1.2 Handling Incorrect User Information when Login

login_failed.png
Incorrect Login Information
user’s_information_stored_in_Firebase_Realtime_Database.png

If the credentials are wrong, a toast message pops up saying, “There is no user record for this identifier. The user may have been deleted.” This happens because we’re using Firebase Realtime Database, a cloud-based NoSQL database that syncs and stores data in real time. It ensures your data is always up-to-date during login (Figure 1.5) and improves authentication reliability.

2. Home Page

home_page.png
It is the Healthware homepage where users can browse a list of products. They can scroll through the list and click “View More” to see additional products in the same category. The app also has a menu bar for easy navigation to** Home,**** Category**, Cart, and Account pages.

3. Category Page

category_page.png
This page showcases different product categories on Healthware which has five categories: Hair Care, Vitamins, Skin Care, Diet & Weight Loss, and Sports & Fitness. Users can tap any banner to go to the product details page, where they can check out the price, description, benefits, and ingredients.

4. Cart Page

4.1 Add items into cart

add_items_to_cart.png
When users add an item to the cart, a toast message pops up saying, “Item added to cart.” Then, head to the Cart page, and the item will be waiting for you in the Shopping Bag.

4.2 Remove items from cart

clear_cart.png
It shows the Shopping Bag emptied after clicking the “Clear Cart” button, and a toast message appears confirming the action.

4.3 Checkout and Payment

checkout_and_payment.png
In Figure 2.6, users can click the green button to check out. This takes them to the Order Confirmation Page, where they can review their items and total price. After that, they’ll enter their mailing address and payment details to complete the purchase.

CartActivity.java
public void updateTotalAmount() {
    double totalAmount = calculateTotalAmount();

    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    String formattedTotalAmount = decimalFormat.format(totalAmount);

    textViewTotalAmount.setText("RM " + formattedTotalAmount);
}

private double calculateTotalAmount() {
    double totalAmount = 0;
    for (CartItem cartItem : cartItems) {
        totalAmount += cartItem.getItemPrice() * cartItem.getQuantity();
    }

    DecimalFormat decimalFormat = new DecimalFormat("0.00");
    String formattedTotalAmount = decimalFormat.format(totalAmount);

    textViewTotalAmount.setText("RM " + formattedTotalAmount);
    return totalAmount;
}

The clearCart(View view) method clears the cart, grabs the user ID, locates the user via Firebase, and updates the total. A toast confirms the action. The updateTotalAmount() method adds up the cart total by multiplying itemPrice and quantity, then shows it on the screen. The calculateTotalAmount() method does the same but returns the total as a raw double.

CartActivity.java
private void addToOrder(String selectedState, String selectedCity) {
    if (mAuth.getCurrentUser() != null) {
        String userId = mAuth.getCurrentUser().getUid();

        String currentDate = DateFormat.getDateTimeInstance().format(new Date());

        String orderId = ordersRef.push().getKey();
        Map<String, Object> orderDetails = new HashMap<>();
        orderDetails.put("state", selectedState);
        orderDetails.put("city", selectedCity);
        orderDetails.put("orderDate", currentDate);
        orderDetails.put("orderId", orderId);

        double totalPrice = 0;
        int totalQuantity = 0;

        cartRef.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) {
                if (snapshot.exists()) {
                    for (DataSnapshot cartItemSnapshot : snapshot.getChildren()) {
                        CartItem cartItem = cartItemSnapshot.getValue(CartItem.class);
                        String cartItemId = cartItemSnapshot.getKey();
                        // Add the cart item to the order details
                        ordersRef.child(orderId).child("items").child(cartItemId).setValue(cartItem);
                        double itemPrice = cartItem.getItemPrice();
                        int quantity = cartItem.getQuantity();
                        double itemTotal = itemPrice * quantity;
                        totalPrice += itemTotal; // Update the total price
                    }
                    ordersRef.child(orderId).child("totalPrice").setValue(totalPrice);
                    cartRef.removeValue(); // Clear cart after successful order
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError error) {
                Toast.makeText(Payment.this, "Failed to retrieve cart items", Toast.LENGTH_SHORT).show();
            }
        });

        ordersRef.child(orderId).setValue(orderDetails);  // Save order details in Firebase
    }

    // Redirect to the order confirmation screen
    Intent intent = new Intent(Payment.this, OrderConfirmation.class);
    startActivity(intent);

    // Handle the progress dialog and confirmation message
    int progressDelayMillis = 5000; // Closing progress dialog after 5 seconds
    new CountDownTimer(progressDelayMillis, progressDelayMillis) {
        @Override
        public void onTick(long millisUntilFinished) {}
        @Override
        public void onFinish() {
            progressDialog.dismiss();
        }
    }.start();

    int toastDelayMillis = 1000; // Delay before showing confirmation toast
    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(getApplicationContext(), "Your order has been confirmed!", Toast.LENGTH_LONG).show();
        }
    }, toastDelayMillis);
}

The addToOrder(String selectedState, String selectedCity) method saves the order details to Firebase after payment. It grabs the cart items, calculates the total, and stores everything (like state, city, order date) in Firebase under the user’s orders. Then, it clears the cart and redirects the user to the OrderConfirmation screen after a quick progress update

order_history.png
Once the transaction is complete, users are taken to a page that says, “Your order is on the way!” They can then choose to either view their order history or keep shopping.

OrderHistory.java
private void fetchOrderHistory(String userId) {
  ordersRef.addValueEventListener(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {
          List<Order> orderList = new ArrayList<>();
          for (DataSnapshot orderSnapshot : dataSnapshot.getChildren()) {
              String orderId = orderSnapshot.child("orderId").getValue(String.class);
              String orderDate = orderSnapshot.child("orderDate").getValue(String.class);
              DataSnapshot itemsSnapshot = orderSnapshot.child("items");
              List<String> orderItems = new ArrayList<>();
              double totalOrderPrice = 0;
              int totalQuantity = 0;

              for (DataSnapshot itemSnapshot : itemsSnapshot.getChildren()) {
                  String itemName = itemSnapshot.child("itemName").getValue(String.class);
                  int quantity = itemSnapshot.child("quantity").getValue(Integer.class);
                  double itemPrice = itemSnapshot.child("itemPrice").getValue(Double.class);
                  double itemTotalPrice = itemPrice * quantity;
                  totalOrderPrice += itemTotalPrice;
                  totalQuantity += quantity;

                  orderItems.add(itemName);
              }


              Order order = new Order(orderId, orderItems, totalOrderPrice, totalQuantity, orderDate);
              orderList.add(order);
          }


          OrderAdapter adapter = new OrderAdapter(OrderHistory.this, orderList);
          listViewOrders.setAdapter(adapter);
      }

The fetchOrderHistory() method is used to fetch the order history from Firebase Realtime Database and it iterates over order snapshots and retrieves order ID, order date, and items for each order. “Order” object is also created and added to “orderList” and “OrderAdapter” is set up with “orderList” and assigns it to “listViewOrders” to display the order history.

5. Account Page

account_page.png
This page lets users manage their account—view order history, edit their profile, update their picture, or sign out.

5.1 Update profile picture

update_profile_picture.png
Click the “Choose Picture” button to pick your photo, then hit “Upload” to update your profile picture.

5.2 Update profile information

update_profile_information.png
Click on “Account Settings”, and users will see their personal info (Figure 4.3). To edit, just tap “Edit Profile”, make your changes, and hit “Save” to keep them!

5.3 Logout

Click the “Sign Out” button to log out of the app. A toast message pops up saying, “You are signed out!“

7. Guest Mode

guest_mode.png
If users want to browse without registering, they can click “Continue as Guest”, and a toast will say, “You are now browsing as a Guest!”. However, if they try to buy something, a popup will remind them to sign up to add items to the cart. Also, if they click the Cart or Account menu, a toast will remind them that their details aren’t available as a guest.

Conclusion

The Healthware app consists of 37 Java classes, which together form the foundation for a fully functional healthcare ordering system. All the project requirements have been successfully met and implemented. This project marked my first experience in creating an e-commerce shopping system from the ground up using Java, Android Studio, and Firebase. It was a great learning journey, and I’m really proud of the final result.

Tech Stack

Android StudioAndroid Studio
FirebaseFirebase
JavaJava