国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

購物車程序?qū)崿F(xiàn)教程

這篇具有很好參考價值的文章主要介紹了購物車程序?qū)崿F(xiàn)教程。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

購物車程序?qū)崿F(xiàn)教程

在本教程中,我們將實現(xiàn)一個購物車程序,實現(xiàn)在界面中以列表的形式顯示購物車的商品信息。商品信息包含商品名稱,價格和數(shù)量,并能實現(xiàn)對應的增刪改查操作。我們將使用 Android Studio 和 SQLite 數(shù)據(jù)庫來完成這個任務。

程序運行截圖

編寫一個購物車程序,android,sqlite,數(shù)據(jù)庫
編寫一個購物車程序,android,sqlite,數(shù)據(jù)庫
編寫一個購物車程序,android,sqlite,數(shù)據(jù)庫

程序設計與說明

我們的購物車程序由以下四個主要類組成:

  1. MainActivity
  2. ProductAdapter
  3. Product
  4. ProductDBHelper

MainActivity

MainActivity 是應用程序的主界面,負責展示購物車內(nèi)的商品列表,并提供商品的增刪改查操作。

主要方法和功能:

  • onCreate(): 初始化界面和設置相應的事件監(jiān)聽器。
  • addPredefinedProducts(): 向數(shù)據(jù)庫添加預定義的商品數(shù)據(jù)。
  • addProduct(): 添加新商品到購物車。
  • loadProducts(): 從數(shù)據(jù)庫加載購物車內(nèi)的商品列表并更新 RecyclerView。
  • onProductClick(): 處理商品點擊事件,用于彈出編輯商品信息的對話框。
  • showEditProductDialog(): 顯示用于編輯商品信息的對話框。
package com.example.shoppingcart;

import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;

public class MainActivity extends AppCompatActivity implements ProductAdapter.OnProductClickListener {

    private List<Product> productList = new ArrayList<>();
    private ProductAdapter productAdapter;
    private ProductDBHelper dbHelper;

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

        dbHelper = new ProductDBHelper(this);

        SharedPreferences sharedPreferences = getSharedPreferences("ShoppingCartPreferences", MODE_PRIVATE);
        boolean isFirstRun = sharedPreferences.getBoolean("isFirstRun", true);
        if (isFirstRun) {
            addPredefinedProducts();

            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putBoolean("isFirstRun", false);
            editor.apply();
        }

        RecyclerView shoppingCartList = findViewById(R.id.shopping_cart_list);
        shoppingCartList.setLayoutManager(new LinearLayoutManager(this));
        productAdapter = new ProductAdapter(productList, this);
        shoppingCartList.setAdapter(productAdapter);

        Button addItemButton = findViewById(R.id.add_item_button);
        addItemButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addProduct();
            }
        });

        Button viewCartButton = findViewById(R.id.view_cart_button);
        viewCartButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showCartDialog();
            }
        });

        loadProducts();
    }


    private void addPredefinedProducts() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();

        // 商品列表
        List<Product> predefinedProducts = new ArrayList<>();
        predefinedProducts.add(new Product("iPhone 13", 1099.00, 1));
        predefinedProducts.add(new Product("Samsung Galaxy S22", 999.00, 1));
        predefinedProducts.add(new Product("Google Pixel 6", 899.00, 1));

        for (Product product : predefinedProducts) {
            ContentValues values = new ContentValues();
            values.put(ProductDBHelper.COLUMN_NAME, product.getName());
            values.put(ProductDBHelper.COLUMN_PRICE, product.getPrice());
            values.put(ProductDBHelper.COLUMN_QUANTITY, product.getQuantity());

            long newRowId = db.insert(ProductDBHelper.TABLE_NAME, null, values);
            if (newRowId == -1) {
                Toast.makeText(this, "添加商品失敗", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void addProduct() {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put(ProductDBHelper.COLUMN_NAME, "商品" + (productList.size() + 1));
        values.put(ProductDBHelper.COLUMN_PRICE, 9.99);
        values.put(ProductDBHelper.COLUMN_QUANTITY, 1);

        long newRowId = db.insert(ProductDBHelper.TABLE_NAME, null, values);
        if (newRowId != -1) {
            loadProducts();
            Toast.makeText(this, "商品已添加", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "添加商品失敗", Toast.LENGTH_SHORT).show();
        }
    }

    private void loadProducts() {
        productList.clear();
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        String[] projection = {
                ProductDBHelper.COLUMN_ID,
                ProductDBHelper.COLUMN_NAME,
                ProductDBHelper.COLUMN_PRICE,
                ProductDBHelper.COLUMN_QUANTITY
        };

        Cursor cursor = db.query(
                ProductDBHelper.TABLE_NAME,
                projection,
                null,
                null,
                null,
                null,
                null
        );

        while (cursor.moveToNext()) {
            String name = cursor.getString(cursor.getColumnIndex(ProductDBHelper.COLUMN_NAME));
            double price = cursor.getDouble(cursor.getColumnIndex(ProductDBHelper.COLUMN_PRICE));
            int quantity = cursor.getInt(cursor.getColumnIndex(ProductDBHelper.COLUMN_QUANTITY));
            int id = cursor.getInt(cursor.getColumnIndex(ProductDBHelper.COLUMN_ID));
            productList.add(new Product(id, name, price, quantity));
        }
        cursor.close();
        productAdapter.notifyDataSetChanged();
    }


    @Override
    public void onProductClick(Product product) {
        showEditProductDialog(product);
    }

    private void showEditProductDialog(final Product product) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("編輯商品");

        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);

        final EditText nameEditText = new EditText(this);
        nameEditText.setText(product.getName());
        layout.addView(nameEditText);

        final EditText priceEditText = new EditText(this);
        priceEditText.setText(String.valueOf(product.getPrice()));
        layout.addView(priceEditText);

        final NumberPicker quantityPicker = new NumberPicker(this);
        quantityPicker.setMinValue(1);
        quantityPicker.setMaxValue(100);
        quantityPicker.setValue(product.getQuantity());
        layout.addView(quantityPicker);

        builder.setView(layout);

        builder.setPositiveButton("保存", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String newName = nameEditText.getText().toString();
                double newPrice = Double.parseDouble(priceEditText.getText().toString());
                int newQuantity = quantityPicker.getValue();

                Product updatedProduct = new Product(product.getId(), newName, newPrice, newQuantity);
                dbHelper.updateProduct(updatedProduct);
                loadProducts();
            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.setNeutralButton("刪除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dbHelper.deleteProduct(product.getId());
                loadProducts();
            }
        });

        builder.show();
    }
    private void showCartDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("購物車");

        StringBuilder cartItems = new StringBuilder();
        double total = 0;
        for (Product product : productList) {
            if (product.isSelected()) {
                cartItems.append(product.getName())
                        .append(" x ")
                        .append(product.getQuantity())
                        .append(" = ")
                        .append(String.format(Locale.getDefault(), "%.2f", product.getPrice() * product.getQuantity()))
                        .append("\n");
                total += product.getPrice() * product.getQuantity();
            }
        }

        cartItems.append("\n總計:").append(String.format(Locale.getDefault(), "%.2f", total));
        builder.setMessage(cartItems.toString());
        builder.setPositiveButton("確定", (dialog, which) -> dialog.dismiss());

        builder.setNegativeButton("清空購物車", (dialog, which) -> {
            for (Product product : productList) {
                product.setSelected(false);
            }
            productAdapter.notifyDataSetChanged();
            dialog.dismiss();
        });

        builder.show();
    }

}

ProductAdapter

ProductAdapter 是一個自定義的 RecyclerView.Adapter,負責將商品數(shù)據(jù)與 RecyclerView 中的視圖進行綁定。

主要方法和功能:

  • onCreateViewHolder(): 創(chuàng)建 ViewHolder,用于承載商品視圖。
  • onBindViewHolder(): 將商品數(shù)據(jù)與視圖進行綁定。
  • getItemCount(): 返回購物車內(nèi)商品的數(shù)量。
  • OnProductClickListener: 定義一個接口,用于處理商品點擊事件。
package com.example.shoppingcart;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Locale;

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

    private List<Product> productList;
    private OnProductClickListener onProductClickListener;

    public ProductAdapter(List<Product> productList, OnProductClickListener onProductClickListener) {
        this.productList = productList;
        this.onProductClickListener = onProductClickListener;
    }
    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.product_item, parent, false);
        return new ViewHolder(view, onProductClickListener);
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        Product product = productList.get(position);
        holder.nameTextView.setText(product.getName());
        holder.priceTextView.setText(String.format(Locale.getDefault(), "%.2f", product.getPrice()));
        holder.quantityTextView.setText(String.valueOf(product.getQuantity()));
        holder.selectedCheckbox.setChecked(product.isSelected());

        // Handle checkbox click
        holder.selectedCheckbox.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                product.setSelected(!product.isSelected());
            }
        });
    }

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

    public interface OnProductClickListener {
        void onProductClick(Product product);
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView nameTextView;
        public TextView priceTextView;
        public TextView quantityTextView;
        CheckBox selectedCheckbox;

        public ViewHolder(View itemView, OnProductClickListener onProductClickListener) {
            super(itemView);
            nameTextView = itemView.findViewById(R.id.product_name);
            priceTextView = itemView.findViewById(R.id.product_price);
            quantityTextView = itemView.findViewById(R.id.product_quantity);
            itemView.setOnClickListener(this);
            selectedCheckbox = itemView.findViewById(R.id.product_selected_checkbox);
        }

        @Override
        public void onClick(View v) {
            if (onProductClickListener != null) {
                onProductClickListener.onProductClick(productList.get(getAdapterPosition()));
            }
        }
    }
}


Product

Product 類表示購物車內(nèi)的商品,包含商品的基本信息,如 ID、名稱、價格和數(shù)量。

主要方法和功能:

  • 構(gòu)造函數(shù): 初始化商品實例。
  • Getter 和 Setter 方法: 訪問和修改商品屬性。
package com.example.shoppingcart;

public class Product {
    private int id;
    private String name;
    private double price;
    private int quantity;
    private boolean selected;

    public Product(int id, String name, double price, int quantity) {
        this.id = id;
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public Product(String name, double price, int quantity) {
        this.name = name;
        this.price = price;
        this.quantity = quantity;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public int getQuantity() {
        return quantity;
    }

    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    public boolean isSelected() {
        return selected;
    }

    public void setSelected(boolean selected) {
        this.selected = selected;
    }
}

ProductDBHelper

ProductDBHelper 是一個自定義的 SQLiteOpenHelper 類,負責管理商品數(shù)據(jù)的數(shù)據(jù)庫操作,如創(chuàng)建表、更新表、查詢數(shù)據(jù)、更新數(shù)據(jù)和刪除數(shù)據(jù)。

主要方法和功能:

  • onCreate(): 創(chuàng)建商品表。
  • onUpgrade(): 刪除舊的商品表,并重新創(chuàng)建。
  • updateProduct(): 更新商品信息。
  • deleteProduct(): 刪除商品。
package com.example.shoppingcart;

import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class ProductDBHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "shopping_cart.db";
    private static final int DATABASE_VERSION = 1;

    public static final String TABLE_NAME = "products";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_PRICE = "price";
    public static final String COLUMN_QUANTITY = "quantity";

    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + TABLE_NAME + " (" +
                    COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
                    COLUMN_NAME + " TEXT," +
                    COLUMN_PRICE + " REAL," +
                    COLUMN_QUANTITY + " INTEGER)";

    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + TABLE_NAME;

    public ProductDBHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL(SQL_DELETE_ENTRIES);
        onCreate(db);
    }

    public int updateProduct(Product product) {
        SQLiteDatabase db = getWritableDatabase();

        ContentValues values = new ContentValues();
        values.put(COLUMN_NAME, product.getName());
        values.put(COLUMN_PRICE, product.getPrice());
        values.put(COLUMN_QUANTITY, product.getQuantity());

        String selection = COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(product.getId())};

        return db.update(TABLE_NAME, values, selection, selectionArgs);
    }

    public int deleteProduct(int productId) {
        SQLiteDatabase db = getWritableDatabase();

        String selection = COLUMN_ID + " = ?";
        String[] selectionArgs = {String.valueOf(productId)};

        return db.delete(TABLE_NAME, selection, selectionArgs);
    }
}

總結(jié)

通過這四個類的協(xié)同工作,實現(xiàn)了購物車程序的核心功能。具體來說,MainActivity 負責展示商品列表和操作界面,ProductAdapter 負責將商品數(shù)據(jù)綁定到視圖上,Product 類表示購物車中的商品,而 ProductDBHelper 負責對商品數(shù)據(jù)進行增刪改查操作。希望本教程對你有所幫助!

源碼

源碼地址
轉(zhuǎn)載請標注,希望點個訂閱!文章來源地址http://www.zghlxwxcb.cn/news/detail-766266.html

到了這里,關于購物車程序?qū)崿F(xiàn)教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領支付寶紅包贊助服務器費用

相關文章

  • 使用Vue.js框架的指令和事件綁定實現(xiàn)一個購物車的頁面布局

    使用了v-model指令來實現(xiàn)全選/全不選的功能,當全選框被點擊時,isAllChecked的值會被改變。 使用了v-if指令來判斷購物車中是否有商品,如果有商品則渲染商品列表,否則顯示購物車為空的提示。 使用了v-for指令來遍歷datalist數(shù)組,渲染每個商品項。 使用了@change事件來監(jiān)聽商

    2024年02月12日
    瀏覽(23)
  • Android商城開發(fā)----點擊加入購物車,購物車商品的增刪減

    Android商城開發(fā)----點擊加入購物車,購物車商品的增刪減

    上一章節(jié):【分類頁面】點擊左側(cè)類別,實現(xiàn)右側(cè)對應類別商品的展示 本文是在上一章節(jié)基礎上開發(fā)的,點擊【分類】頁面商品的加入購物車按鈕,實現(xiàn)將商品加入購物車的功能。 本文主要實現(xiàn)的功能是: 1.點擊加入購物車按鈕,將商品加入購物車。 2.點擊相同的商品加入

    2024年02月03日
    瀏覽(32)
  • 【uniapp 開發(fā)小程序】購物車功能,實現(xiàn)全選、反選、單選、計算總價

    【uniapp 開發(fā)小程序】購物車功能,實現(xiàn)全選、反選、單選、計算總價

    uniapp 開發(fā)小程序,實現(xiàn)購物車功能,實現(xiàn)全選、反選、單選、計算總價 關鍵代碼: return totalPrice.toFixed(2); // 保留兩位小數(shù) 否則會出現(xiàn)多位小數(shù)現(xiàn)象:

    2024年02月11日
    瀏覽(23)
  • Android -- 購物車

    Android -- 購物車

    購物車功能描述 ????????第一次進入購物車頁面,購物車里面是空的,同時提示去逛手機商場, 如 首次進入的頁面 圖所示。接著去商場頁面選購手機,隨便挑了幾部手機加入購物車,再返回購物車頁面,即可看 到購物車的商品列表,如 購物車已選列表圖 所示,有商品

    2023年04月08日
    瀏覽(20)
  • Vue項目商品購物車前端本地緩存邏輯(適用H5/ipad/PC端)——前端實現(xiàn)購物車刪除商品、購物車增減數(shù)量,清空購物車功能

    Vue項目商品購物車前端本地緩存邏輯(適用H5/ipad/PC端)——前端實現(xiàn)購物車刪除商品、購物車增減數(shù)量,清空購物車功能

    Vue3 + Vite + Ts開源后臺管理系統(tǒng)模板 基于ElementUi或AntdUI再次封裝基礎組件文檔 基于Element-plus再次封裝基礎組件文檔(vue3+ts)

    2024年02月12日
    瀏覽(31)
  • maui sqlite開發(fā)一個商城加購物車的演示(3)
  • 11、微信小程序——購物車

    11、微信小程序——購物車

    目錄 1、代碼分析 1.1? dom結(jié)構(gòu)分析 1.2? 全選控制反選 1.3? 反選控制全選 1.4、計算總價 1.4 加、減 2、效果、代碼演示? 1.1? dom結(jié)構(gòu)分析 購物車的組件結(jié)構(gòu)主要由兩部分組成: 多選框部分( checkbox-group ) + 全選框部分( view ) 1.2? 全選控制反選 業(yè)務邏輯: 1、全選框(選中)——

    2024年02月02日
    瀏覽(24)
  • 商城小程序(8.購物車頁面)

    商城小程序(8.購物車頁面)

    本章主要完成pages下的cart購物頁面編寫 定義如下UI結(jié)構(gòu) 美化樣式 通過 mapState 輔助函數(shù),將Store中的cart數(shù)組映射到當前頁面中使用: 在UI結(jié)構(gòu)中,通過v-for渲染自定義組件my-goods 打開my-goods.vue組件,為商品左側(cè)圖片區(qū)域添加radio足跡 并美化UI ,使radio組件和image組件左右布局

    2024年01月23日
    瀏覽(19)
  • 微信小程序(五)購物車

    微信小程序(五)購物車

    shoppingcart.wxml shoppingcart.js shoppingcart.wxss 效果圖 ?

    2024年02月16日
    瀏覽(19)
  • 商城小程序(7.加入購物車)

    商城小程序(7.加入購物車)

    新建store目錄,并創(chuàng)建store.js文件用于管理vuex相關內(nèi)容 在store.js中 初始化store的實例對象 在main.js 中導入store實例對象并掛載到vue的實例上 同樣目錄下創(chuàng)建cart.js模塊 在cart.js中,初始化如下的vuex模塊 在store/store.js 模塊中,導入并掛載購物車中的vue模塊 商品詳情頁面測試,是

    2024年02月02日
    瀏覽(22)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領取紅包,優(yōu)惠每天領

二維碼1

領取紅包

二維碼2

領紅包