DEV Community

Sanskar Singh
Sanskar Singh

Posted on

Grocery List

// MainActivity.java

package com.example.grocerylist;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private EditText itemNameEditText;
    private EditText itemCostEditText;
    private Button addItemButton;
    private Spinner itemsSpinner;
    private LinearLayout selectedItemsLayout;
    private TextView totalCostTextView;
    private Button calculateTotalButton;

    private SQLiteDatabase database;
    private static final String DATABASE_NAME = "GroceryList";
    private static final String TABLE_GROCERY = "grocery_items";
    private static final String COLUMN_ID = "id";
    private static final String COLUMN_NAME = "name";
    private static final String COLUMN_COST = "cost";

    private List<String> itemNames = new ArrayList<>();
    private Map<String, Double> itemCosts = new HashMap<>();
    private Map<String, Boolean> selectedItems = new HashMap<>();

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

        // Initialize UI elements
        itemNameEditText = findViewById(R.id.itemNameEditText);
        itemCostEditText = findViewById(R.id.itemCostEditText);
        addItemButton = findViewById(R.id.addItemButton);
        itemsSpinner = findViewById(R.id.itemsSpinner);
        selectedItemsLayout = findViewById(R.id.selectedItemsLayout);
        totalCostTextView = findViewById(R.id.totalCostTextView);
        calculateTotalButton = findViewById(R.id.calculateTotalButton);

        // Create or open the database
        database = openOrCreateDatabase(DATABASE_NAME, MODE_PRIVATE, null);

        // Create the grocery table if it doesn't exist
        database.execSQL(
                "CREATE TABLE IF NOT EXISTS " + TABLE_GROCERY + " (" +
                        COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                        COLUMN_NAME + " TEXT UNIQUE, " +
                        COLUMN_COST + " REAL)");

        // Load grocery items from database
        loadGroceryItems();

        // Set up spinner
        setupSpinner();

        // Add item button click listener
        addItemButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addGroceryItem();
            }
        });

        // Calculate total button click listener
        calculateTotalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                calculateTotal();
            }
        });
    }

    private void setupSpinner() {
        ArrayAdapter<String> adapter = new ArrayAdapter<>(
                this, android.R.layout.simple_spinner_item, itemNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        itemsSpinner.setAdapter(adapter);

        itemsSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String selectedItem = itemNames.get(position);
                addItemToSelection(selectedItem);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
                // Do nothing
            }
        });
    }

    private void loadGroceryItems() {
        // Clear existing data
        itemNames.clear();
        itemCosts.clear();

        // Query all items from the database
        Cursor cursor = database.rawQuery("SELECT * FROM " + TABLE_GROCERY, null);

        if (cursor.moveToFirst()) {
            int nameIndex = cursor.getColumnIndex(COLUMN_NAME);
            int costIndex = cursor.getColumnIndex(COLUMN_COST);

            if (nameIndex >= 0 && costIndex >= 0) {
                do {
                    String name = cursor.getString(nameIndex);
                    double cost = cursor.getDouble(costIndex);

                    itemNames.add(name);
                    itemCosts.put(name, cost);
                } while (cursor.moveToNext());
            }
        }

        cursor.close();
    }

    private void addGroceryItem() {
        String itemName = itemNameEditText.getText().toString().trim();
        String costString = itemCostEditText.getText().toString().trim();

        if (itemName.isEmpty() || costString.isEmpty()) {
            Toast.makeText(this, "Please enter both item name and cost", Toast.LENGTH_SHORT).show();
            return;
        }

        try {
            double cost = Double.parseDouble(costString);

            ContentValues values = new ContentValues();
            values.put(COLUMN_NAME, itemName);
            values.put(COLUMN_COST, cost);

            // Try to insert the item
            long result = database.insert(TABLE_GROCERY, null, values);

            if (result == -1) {
                // If insert failed, try to update instead (item might already exist)
                int updateResult = database.update(TABLE_GROCERY, values, COLUMN_NAME + " = ?",
                        new String[]{itemName});

                if (updateResult > 0) {
                    Toast.makeText(this, "Item updated successfully", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Failed to add item", Toast.LENGTH_SHORT).show();
                    return;
                }
            } else {
                Toast.makeText(this, "Item added successfully", Toast.LENGTH_SHORT).show();
            }

            // Clear input fields
            itemNameEditText.setText("");
            itemCostEditText.setText("");

            // Reload grocery items
            loadGroceryItems();

            // Update spinner
            ((ArrayAdapter) itemsSpinner.getAdapter()).notifyDataSetChanged();

        } catch (NumberFormatException e) {
            Toast.makeText(this, "Please enter a valid cost", Toast.LENGTH_SHORT).show();
        }
    }

    private void addItemToSelection(final String itemName) {
        // Check if the item is already in the selection layout
        for (int i = 0; i < selectedItemsLayout.getChildCount(); i++) {
            View view = selectedItemsLayout.getChildAt(i);
            if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;
                if (checkBox.getText().toString().equals(itemName)) {
                    // Item already exists in selection, just return
                    return;
                }
            }
        }

        // Create a new checkbox for the selected item
        final CheckBox itemCheckBox = new CheckBox(this);
        itemCheckBox.setText(itemName);
        itemCheckBox.setChecked(true);

        // Add the item to the selected items map
        selectedItems.put(itemName, true);

        // Set checkbox change listener
        itemCheckBox.setOnCheckedChangeListener((buttonView, isChecked) -> {
            selectedItems.put(itemName, isChecked);
        });

        // Add checkbox to layout
        selectedItemsLayout.addView(itemCheckBox);
    }

    private void calculateTotal() {
        double total = 0.0;

        // Iterate through selected items
        for (Map.Entry<String, Boolean> entry : selectedItems.entrySet()) {
            if (entry.getValue()) {
                String itemName = entry.getKey();
                Double cost = itemCosts.get(itemName);
                if (cost != null) {
                    total += cost;
                }
            }
        }

        // Display the total cost
        totalCostTextView.setText(String.format("Total Cost: $%.2f", total));
    }

    @Override
    protected void onDestroy() {
        database.close();
        super.onDestroy();
    }
}
Enter fullscreen mode Exit fullscreen mode

//main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Grocery List"
        android:textSize="24sp"
        android:textStyle="bold"
        android:gravity="center"
        android:layout_marginBottom="16dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Grocery Item"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginBottom="8dp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="8dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Item Name:"
            android:layout_gravity="center_vertical" />

        <EditText
            android:id="@+id/itemNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter item name"
            android:minHeight="48dp"
            android:inputType="text"
            android:layout_marginStart="8dp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginBottom="16dp">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Item Cost: $"
            android:layout_gravity="center_vertical" />

        <EditText
            android:id="@+id/itemCostEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Enter cost"
            android:minHeight="48dp"
            android:inputType="numberDecimal"
            android:layout_marginStart="8dp" />
    </LinearLayout>

    <Button
        android:id="@+id/addItemButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Add Item"
        android:minHeight="48dp"
        android:layout_marginBottom="24dp" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Select Items"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginBottom="8dp" />

    <Spinner
        android:id="@+id/itemsSpinner"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:minHeight="48dp"
        android:layout_marginBottom="16dp" />

    <TextView
        android:id="@+id/selectedItemsLabel"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Selected Items"
        android:textSize="18sp"
        android:textStyle="bold"
        android:layout_marginBottom="8dp" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:contentDescription="List of selected grocery items"
        android:importantForAccessibility="yes"
        android:labelFor="@id/selectedItemsLayout">

        <LinearLayout
            android:id="@+id/selectedItemsLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" />
    </ScrollView>

    <Button
        android:id="@+id/calculateTotalButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Calculate Total"
        android:minHeight="48dp"
        android:layout_marginTop="16dp"
        android:layout_marginBottom="8dp" />

    <TextView
        android:id="@+id/totalCostTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Total Cost: $0.00"
        android:textSize="20sp"
        android:textStyle="bold"
        android:gravity="center" />

</LinearLayout>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)