【Android开发基础】购物车代码整理

news2024/11/24 17:20:06

文章目录

    • 一、数据库设计
    • 二、Home界面
    • 三、购物车模块
    • 四、添加
    • 五、源代码

这个月总算忙完了,总算能够抽出时间来,认真写一下博客了。整理一下购物车的代码

一、数据库设计

  • 基于SqLite简单设计一个数据存储逻辑

在这里插入图片描述

  • 实体(接收数据)
import androidx.lifecycle.LiveData;

public class Cart extends LiveData<Cart> {

    int id;
    int shop_id;
    int number;
    Shop shop;

    public int getId() {
        return id;
    }

    public int getShop_id() {
        return shop_id;
    }

    public int getNumber() {
        return number;
    }

    public Shop getShop() {
        return shop;
    }

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

    public void setShop_id(int shop_id) {
        this.shop_id = shop_id;
        postValue(this);
    }

    public void setNumber(int number) {
        this.number = number;
        postValue(this);
    }

    public void setShop(Shop shop) {
        this.shop = shop;
        postValue(this);
    }

    @Override
    public String toString() {
        return "Cart{" +
                "id=" + id +
                ", shop_id=" + shop_id +
                ", number=" + number +
                ", shop=" + shop +
                '}';
    }
}
import androidx.lifecycle.LiveData;

public class Shop extends LiveData<Shop> {

    int id;
    String image;
    String name;
    int price;
    String bus;
    float dis;
    String time;
    String des;

    public int getId() {
        return id;
    }

    public String getImage() {
        return image;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    public String getBus() {
        return bus;
    }

    public float getDis() {
        return dis;
    }

    public String getTime() {
        return time;
    }

    public String getDes() {
        return des;
    }

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

    public void setImage(String image) {
        this.image = image;
        postValue(this);
    }

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

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

    public void setBus(String bus) {
        this.bus = bus;
        postValue(this);
    }

    public void setDis(float dis) {
        this.dis = dis;
        postValue(this);
    }

    public void setTime(String time) {
        this.time = time;
        postValue(this);
    }

    public void setDes(String des) {
        this.des = des;
        postValue(this);
    }

    @Override
    public String toString() {
        return "Shop{" +
                "id=" + id +
                ", image='" + image + '\'' +
                ", name='" + name + '\'' +
                ", price=" + price +
                ", bus='" + bus + '\'' +
                ", dis=" + dis +
                ", time='" + time + '\'' +
                ", des='" + des + '\'' +
                '}';
    }
}
  • SQL实现类
public class CartOrder {

    public static final String DATABASE_DATA = "db_cart";    // 数据库名
    public static final String DATABASE_TABLE = "xpq_cart";  // 表名
    public static final int DATABASE_INS = 1;

    public static final String NOTEPAD_ID = "id";
    public static final String NOTEPAD_SHOP_ID = "shop_id";
    public static final String NOTEPAD_NUMBER = "number";

}
public class ShopOrder {

    public static final String DATABASE_DATA = "db_data";    // 数据库名
    public static final String DATABASE_TABLE = "xpq_shop";  // 表名
    public static final int DATABASE_INS = 1;

    public static final String NOTEPAD_ID = "id";
    public static final String NOTEPAD_Image = "image";    // 图
    public static final String NOTEPAD_NAME = "name";      // 名
    public static final String NOTEPAD_PRICE = "price";    // 价格
    public static final String NOTEPAD_BUS = "business";   // 商家
    public static final String NOTEPAD_DIS = "discount";   // 折扣
    public static final String NOTEPAD_TIME = "time";      // 时间
    public static final String NOTEPAD_DES = "des";        // 描述

}
  • IDUS

SqlCart.java

public class SqlCart extends SQLiteOpenHelper {

    SQLiteDatabase sqLiteDatabase;
    private SqlShop sqlShop;

    public SqlCart(@Nullable Context context) {
        super(context, CartOrder.DATABASE_DATA, null, CartOrder.DATABASE_INS);
        sqLiteDatabase = this.getWritableDatabase();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + CartOrder.DATABASE_TABLE + "("
                + CartOrder.NOTEPAD_ID + " integer primary key autoincrement,"
                + CartOrder.NOTEPAD_SHOP_ID + " integer,"
                + CartOrder.NOTEPAD_NUMBER + " integer)");
    }

    /**
     * 增
     * @param c
     * @return
     */
    public boolean insert(Cart c) {
        ContentValues values = new ContentValues();
        values.put(CartOrder.NOTEPAD_SHOP_ID, c.getShop_id());
        values.put(CartOrder.NOTEPAD_NUMBER, c.getNumber());
        return
                sqLiteDatabase.insert(CartOrder.DATABASE_TABLE, null, values) > 0;
    }

    /**
     * 改
     * @param c
     * @return
     */
    public boolean update(Cart c) {
        ContentValues values = new ContentValues();
        values.put(CartOrder.NOTEPAD_NUMBER, c.getNumber());
        String sql = CartOrder.NOTEPAD_ID + "=?";
        String[] id = new String[]{String.valueOf(c.getId())};
        return
                sqLiteDatabase.update(CartOrder.DATABASE_TABLE, values, sql, id) > 0;
    }


    /**
     * 删
     * @param id
     * @return
     */
    public boolean delete(int id) {
        String sql = CartOrder.NOTEPAD_ID + "=?";
        String[] va = new String[]{String.valueOf(id)};
        return
                sqLiteDatabase.delete(CartOrder.DATABASE_TABLE, sql, va) > 0;
    }

    /**
     * 查
     * @return
     */
    public List<Cart> select(View v) { // 全表遍历
        sqlShop = new SqlShop(v.getContext());
        List<Cart> list = new ArrayList<Cart>();
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + CartOrder.DATABASE_TABLE,
                    null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    Cart d = new Cart();
                    String id = cursor.getString(cursor.getColumnIndex(CartOrder.NOTEPAD_ID));
                    int ids = Integer.valueOf(id);
                    int shop_id = cursor.getInt(cursor.getColumnIndex(CartOrder.NOTEPAD_SHOP_ID));
                    d.setId(ids);
                    d.setShop_id(shop_id);
                    d.setNumber(cursor.getInt(cursor.getColumnIndex(CartOrder.NOTEPAD_NUMBER)));
                    d.setShop(sqlShop.select(shop_id));
                    list.add(d);
                }
                cursor.close();
            } else {
                Log.i("SqlCart-select", "获取Data的信息出现问题!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public List<Cart> select(View v, int sid) { // 全表遍历
        sqlShop = new SqlShop(v.getContext());
        List<Cart> list = new ArrayList<Cart>();
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + CartOrder.DATABASE_TABLE +
                            " where " + CartOrder.NOTEPAD_SHOP_ID + "=" + sid,
                    null,null );
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    Cart d = new Cart();
                    String id = cursor.getString(cursor.getColumnIndex(CartOrder.NOTEPAD_ID));
                    int ids = Integer.valueOf(id);
                    int shop_id = cursor.getInt(cursor.getColumnIndex(CartOrder.NOTEPAD_SHOP_ID));
                    d.setId(ids);
                    d.setShop_id(shop_id);
                    d.setNumber(cursor.getInt(cursor.getColumnIndex(CartOrder.NOTEPAD_NUMBER)));
                    d.setShop(sqlShop.select(shop_id));
                    list.add(d);
                }
                cursor.close();
            } else {
                Log.i("SqlCart-select", "获取Data的信息出现问题!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

}

SqlShop.java

public class SqlShop extends SQLiteOpenHelper {

    SQLiteDatabase sqLiteDatabase;

    /**
     * Create a helper object to create, open, and/or manage a database.
     * This method always returns very quickly.  The database is not actually
     * created or opened until one of {@link #getWritableDatabase} or
     * {@link #getReadableDatabase} is called.
     *
     * @param context to use for locating paths to the the database
     *                {@link #onUpgrade} will be used to upgrade the database; if the database is
     *                newer, {@link #onDowngrade} will be used to downgrade the database
     */
    public SqlShop(@Nullable Context context) {
        super(context, ShopOrder.DATABASE_DATA, null, ShopOrder.DATABASE_INS);
        sqLiteDatabase = this.getWritableDatabase();
    }

    /**
     * Called when the database is created for the first time. This is where the
     * creation of tables and the initial population of the tables should happen.
     *
     * @param db The database.
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("create table " + ShopOrder.DATABASE_TABLE + "("
                + ShopOrder.NOTEPAD_ID + " integer primary key autoincrement,"
                + ShopOrder.NOTEPAD_Image + " VARCHAR(25),"
                + ShopOrder.NOTEPAD_NAME + " VARCHAR(50),"
                + ShopOrder.NOTEPAD_PRICE + " integer,"
                + ShopOrder.NOTEPAD_BUS + " VARCHAR(25),"
                + ShopOrder.NOTEPAD_DIS + " float,"
                + ShopOrder.NOTEPAD_TIME + " VARCHAR(25),"
                + ShopOrder.NOTEPAD_DES + " VARCHAR(25));");
    }

    /**
     * Called when the database needs to be upgraded. The implementation
     * should use this method to drop tables, add tables, or do anything else it
     * needs to upgrade to the new schema version.
     *
     * <p>
     * The SQLite ALTER TABLE documentation can be found
     * <a href="http://sqlite.org/lang_altertable.html">here</a>. If you add new columns
     * you can use ALTER TABLE to insert them into a live table. If you rename or remove columns
     * you can use ALTER TABLE to rename the old table, then create the new table and then
     * populate the new table with the contents of the old table.
     * </p><p>
     * This method executes within a transaction.  If an exception is thrown, all changes
     * will automatically be rolled back.
     * </p>
     *
     * @param db         The database.
     * @param oldVersion The old database version.
     * @param newVersion The new database version.
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 增
     * @param s
     * @return
     */
    public boolean insert(Shop s) {
        ContentValues values = new ContentValues();
        values.put(ShopOrder.NOTEPAD_Image, s.getImage());
        values.put(ShopOrder.NOTEPAD_NAME, s.getName());
        values.put(ShopOrder.NOTEPAD_PRICE, s.getPrice());
        values.put(ShopOrder.NOTEPAD_BUS, s.getBus());
        values.put(ShopOrder.NOTEPAD_DIS, s.getDis());
        values.put(ShopOrder.NOTEPAD_TIME, s.getTime());
        values.put(ShopOrder.NOTEPAD_DES, s.getDes());
        return
                sqLiteDatabase.insert(ShopOrder.DATABASE_TABLE, null, values) > 0;
    }

    /**
     * 删
     * @param id
     * @return
     */
    public boolean delete(int id) {
        String sql = ShopOrder.NOTEPAD_ID + "=?";
        String[] va = new String[]{String.valueOf(id)};
        return
                sqLiteDatabase.delete(ShopOrder.DATABASE_TABLE, sql, va) > 0;
    }

    /**
     * 查
     * @return
     */
    public List<Shop> select() { // 全表遍历
        List<Shop> list = new ArrayList<Shop>();
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + ShopOrder.DATABASE_TABLE,
                    null, null);
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    Shop s = new Shop();
                    String id = cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_ID));
                    int ids = Integer.valueOf(id);
                    s.setId(ids);
                    s.setImage(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_Image)));
                    s.setName(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_NAME)));
                    s.setPrice(cursor.getInt(cursor.getColumnIndex(ShopOrder.NOTEPAD_PRICE)));
                    s.setBus(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_BUS)));
                    s.setDis(cursor.getFloat(cursor.getColumnIndex(ShopOrder.NOTEPAD_DIS)));
                    s.setTime(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_TIME)));
                    s.setDes(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_DES)));
                    list.add(s);
                }
                cursor.close();
            } else {
                Log.i("DataSql-select", "获取Data的信息出现问题!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    public Shop select(int i) {
        Shop s = null;
        try {
            Cursor cursor = sqLiteDatabase.rawQuery("select * from " + ShopOrder.DATABASE_TABLE +
                            " where " + ShopOrder.NOTEPAD_ID + "=" + i,
                    null,null );
            if (cursor.moveToNext()){
                s = new Shop();
                String id = cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_ID));
                int ids = Integer.valueOf(id);
                s.setId(ids);
                s.setImage(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_Image)));
                s.setName(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_NAME)));
                s.setPrice(cursor.getInt(cursor.getColumnIndex(ShopOrder.NOTEPAD_PRICE)));
                s.setBus(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_BUS)));
                s.setDis(cursor.getFloat(cursor.getColumnIndex(ShopOrder.NOTEPAD_DIS)));
                s.setTime(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_TIME)));
                s.setDes(cursor.getString(cursor.getColumnIndex(ShopOrder.NOTEPAD_DES)));
            } else {
                Log.i("DataSql-select", "连接异常!!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

}

二、Home界面

  • 样图

在这里插入图片描述

  • UI界面设计
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.home.HomeFragment"
    android:paddingBottom="?attr/actionBarSize"
    android:background="#F0F0F0"
    android:padding="5dp">

    <!--    listFile模块    -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listShop"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:background="@drawable/shape"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="right|bottom"
        android:paddingBottom="80dp"
        android:paddingRight="10dp">

        <Button
            android:id="@+id/homeCart"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:background="@drawable/shape_circular"/>

    </RelativeLayout>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="right|bottom"
        android:paddingBottom="115dp"
        android:layout_marginRight="5dp">

        <TextView
            android:id="@+id/homeCartNumber"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:padding="4dp"
            android:background="@drawable/shape_circular_number"
            android:textColor="#FFF"
            android:textSize="10dp"/>

    </RelativeLayout>

</RelativeLayout>
  • 内部逻辑

HomeFragment.java

public class HomeFragment extends Fragment {

    private HomeViewModel homeViewModel;
    private RecyclerView listShop;          // 数据渲染控件
    private List<Shop> shopList;            // 数据地址
    private List<Cart> cartList;            // 数据地址
    private SqlShop sqlShop;                // sqLite数据库
    private SqlCart sqlCart;                // sqLite数据库 SqlCart
    private Button homeCart;
    private TextView homeCartNumber;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        homeViewModel =
                ViewModelProviders.of(this).get(HomeViewModel.class);
        View root = inflater.inflate(R.layout.fragment_home, container, false);
        init(root);           // 初始化
        return root;
    }

    private void init(View root) {
        // SQL
        sqlShop = new SqlShop(root.getContext());
        sqlCart = new SqlCart(root.getContext());
        // Model
        shopList = homeViewModel.getListShop(sqlShop);
        cartList = homeViewModel.getCartList(sqlCart, root);
        // View
        listShop = root.findViewById(R.id.listShop);
        homeCart = root.findViewById(R.id.homeCart);
        homeCartNumber = root.findViewById(R.id.homeCartNumber);
        // UI渲染
        homeCart.setText(XpqIcoMoon.CART);
        XpqIcoMoonUtils.setIOC(homeCart);
        homeCartNumber.setText(String.valueOf(alg.CountZPrice(cartList).get("number")));
        // 数据渲染
        getListAdapter();
    }

    // List适配器
    private void getListAdapter() {
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        listShop.setLayoutManager(layoutManager);
        ListAdapter adapter = new ListAdapter(shopList, homeCartNumber);
        listShop.setAdapter(adapter);
    }
}

HomeViewModel.java

public class HomeViewModel extends ViewModel {

    public List<Shop> getListShop(SqlShop sqlShop) {
        return sqlShop.select();
    }

    public List<Cart> getCartList(SqlCart sqlCart, View root) {
        return sqlCart.select(root);
    }

}

三、购物车模块

  • 样图

在这里插入图片描述

  • UI设计
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.dashboard.DashboardFragment"
    android:paddingBottom="?attr/actionBarSize"
    android:background="#F0F0F0">

    <!--    listFile模块    -->
    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/listCart"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:layout_margin="5dp"
        android:background="@drawable/shape"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="bottom">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="right">

            <Button
                android:id="@+id/cart_z_price"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginRight="30dp"
                android:layout_marginBottom="10dp"
                android:background="@drawable/shape_z_price"/>

        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
  • 后台逻辑

DashboardFragment.java

public class DashboardFragment extends Fragment {

    private DashboardViewModel dashboardViewModel;
    private RecyclerView listCart;
    List<Cart> cartList;            // 数据地址
    private SqlCart sqlCart;                // sqLite数据库 SqlCart
    private Button cart_z_price;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        dashboardViewModel =
                ViewModelProviders.of(this).get(DashboardViewModel.class);
        View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
        // 初始化
        init(root);
        return root;
    }

    private void init(View root) {
        sqlCart = new SqlCart(root.getContext());
        listCart = root.findViewById(R.id.listCart);
        cart_z_price = root.findViewById(R.id.cart_z_price);
        cartList = dashboardViewModel.getCartList(sqlCart, root);
        // 渲染结算
        cart_z_price = root.findViewById(R.id.cart_z_price);
        cart_z_price.setText("结算: ¥ " + String.format("%.2f", alg.CountZPrice(cartList).get("price")));
        // 数据渲染
        getCartAdapter();
    }

    // List适配器
    private void getCartAdapter() {
        StaggeredGridLayoutManager layoutManager = new StaggeredGridLayoutManager(1,StaggeredGridLayoutManager.VERTICAL);
        listCart.setLayoutManager(layoutManager);
        CartAdapter adapter = new CartAdapter(cartList, cart_z_price);
        listCart.setAdapter(adapter);
    }
}

DashboardViewModel.java

public class DashboardViewModel extends ViewModel {

    public List<Cart> getCartList(SqlCart sqlCart, View root) {
        return sqlCart.select(root);
    }

}

四、添加

  • 样图
    在这里插入图片描述
  • UI界面设计
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".ui.notifications.NotificationsFragment"
    android:padding="50dp"
    android:background="#F0F0F0">

    <TableRow>
        <TextView
            android:layout_width="100dp"
            android:text="图片:"
            android:textSize="20dp"/>

        <!--    (获取本地图片下次再说)    -->
        <ImageButton
            android:layout_width="150dp"
            android:layout_height="150dp"
            android:background="@drawable/ic_launcher_background"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="名称:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/name"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="价格:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/price"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="商家:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/bus"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="折扣:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/dis"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="时间:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/time"/>
    </TableRow>

    <TableRow>
        <TextView
            android:text="描述:"
            android:textSize="20dp"/>

        <EditText
            android:id="@+id/des"/>
    </TableRow>

    <TableRow
        android:layout_marginTop="20dp">

        <Button
            android:id="@+id/qk"
            android:text="清空"/>

        <Button
            android:id="@+id/add"
            android:text="添加"/>

    </TableRow>

</TableLayout>
  • 后台逻辑

NotificationsFragment.java

public class NotificationsFragment extends Fragment {

    private NotificationsViewModel notificationsViewModel;
    private Button add, qk;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        // 数据
        notificationsViewModel =
                ViewModelProviders.of(this).get(NotificationsViewModel.class);
        View root = inflater.inflate(R.layout.fragment_notifications, container, false);
        // 绑定事件
        onClicks(root);
        return root;
    }

    private void onClicks(final View root) {
        add = root.findViewById(R.id.add);
        qk = root.findViewById(R.id.qk);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationsViewModel.setShop(root);
            }
        });
        qk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notificationsViewModel.qkEditText(root);
            }
        });
    }
}

NotificationsViewModel.java

public class NotificationsViewModel extends ViewModel {

    private Shop shop;
    private EditText name, price, bus, dis, time, des;
    private SqlShop sqlShop;

    // 存储数据
    public void setShop(View root) {
        sqlShop = new SqlShop(root.getContext());  // 初始化数据库
        shop = new Shop();                         // 定义实体
        name = root.findViewById(R.id.name);
        price = root.findViewById(R.id.price);
        bus = root.findViewById(R.id.bus);
        dis = root.findViewById(R.id.dis);
        time = root.findViewById(R.id.time);
        des = root.findViewById(R.id.des);
        shop.setImage("");
        shop.setName(name.getText().toString());
        shop.setBus(bus.getText().toString());
        shop.setTime(time.getText().toString());
        shop.setDes(des.getText().toString());
        try {   // 存在两个非String类型数据需要做转型异常判断
            shop.setPrice(Integer.valueOf(price.getText().toString()));
            shop.setDis(Float.valueOf(dis.getText().toString()));
        } catch (NumberFormatException e) {
            Toast.makeText(root.getContext(), "请输入正确的数据!", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
        if (sqlShop.insert(shop)) {  // 数据库字段有长度限定。如果需要具体到每个字段,自己写判断语句。
            Log.i("data", shop.toString());
            Toast.makeText(root.getContext(), "数据库插入成功!", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(root.getContext(), "数据库插入失败!", Toast.LENGTH_SHORT).show();
        }
    }

    public void qkEditText(View root) {
        name = root.findViewById(R.id.name);
        price = root.findViewById(R.id.price);
        bus = root.findViewById(R.id.bus);
        dis = root.findViewById(R.id.dis);
        time = root.findViewById(R.id.time);
        des = root.findViewById(R.id.des);
        name.setText("");
        price.setText("");
        bus.setText("");
        dis.setText("");
        time.setText("");
        des.setText("");
    }
}

五、源代码

关于效果展示,前往(http://t.csdn.cn/KcvTk)
关于适配器Adapter的学习,前往(http://t.csdn.cn/hEXUF)
关于源代码,前往(https://download.csdn.net/download/weixin_48916759/87844422)

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/599648.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【数据加密】古典密码Playfair

文章目录 一、引言1、主要任务2、分支3、密码体制分类4、攻击密码系统 二、普莱费厄体制1、构造字母表&#xff0c;设为密钥矩阵2、设立加密方法3、加密解密4、字典集合5、结果 一、引言 1、主要任务 解决信息的保密性和可认证问题&#xff0c;保证信息在生成、传递、处理、保…

Swin-Transformer详解

Swin-Transformer详解 0. 前言1. Swin-Transformer结构简介2. Swin-Transformer结构详解2.1 Patch Partition2.2 Patch Merging2.3 Swin Transformer Block2.3.1 W-MSA2.3.2 SW-MSA 3. 模型配置总结 0. 前言 Swin-Transformer是2021年微软研究院发表在ICCV上的一篇文章&#x…

数据的存储(浮点型)

目录 浮点型存储的规则 1.前面我们已经学过了整形在数据中的存储是以原码&#xff0c;反码&#xff0c;补码的形式在内存中存储的&#xff0c;那么浮点数是以什么样的形式存储的呢&#xff1f; 接下来我们通过一段代码来观察——> int main() {int n 9;float* p (float*…

String AOP的使用

面向切面编程&#xff0c;面向特定方法编程&#xff0c;以方法为对象&#xff0c;在不修改原方法的基础上&#xff0c;对方法进行操作扩展等&#xff0c;底层是通过动态代理实现的 使用开发步骤&#xff1a; 1、创建一个类&#xff0c;加上Aspect声明为一个AOP切面类&#xff…

2023 重新开始

感觉搞 IT 的日子最近都有点不太好过。 早上接到公司电话说今天是一个大日子。 为什么是大日子&#xff0c;相信所有人都是懂的。这次公司将会经历一次非常大的裁员&#xff0c;很不幸也在列表中。不过感觉这个好像也没有什么关系。 因为早就在意料之中的事情&#xff0c;经历…

c语言之结构体(初阶)

目录 1&#xff1a;结构体类型的声明 2&#xff1a;结构体初始化 3&#xff1a;结构体成员访问 4&#xff1a;结构体传参 1&#xff1a;结构体类型的声明 1&#xff1a;为啥要有结构体&#xff0c;因为当我们描述一个复杂对象的时候&#xff0c;可能平时我们的一个类型不能…

常见的五种排序

&#x1f436;博主主页&#xff1a;ᰔᩚ. 一怀明月ꦿ ❤️‍&#x1f525;专栏系列&#xff1a;线性代数&#xff0c;C初学者入门训练&#xff0c;题解C&#xff0c;C的使用文章&#xff0c;「初学」C &#x1f525;座右铭&#xff1a;“不要等到什么都没有了&#xff0c;才下…

批量提取某音视频文案(二)

牙叔教程 简单易懂 之前写过一篇 批量提取某音视频文案 , 在之前的教程中, 我用的是微软的语音转文字功能, 今天我们换个方法, 使用 逗哥配音 的 文案提取 功能 准备工作 下载视频和音频 我在github找到的是这个仓库 https://github.com/Johnserf-Seed/TikTokDownload 注意一…

VLANIF虚接口案例实践

1&#xff09;拓扑 2&#xff09;需求&#xff1a; -所有PC能够ping通自己的网关 -实现vlan间互通&#xff0c;实现所有的PC互通 3&#xff09;配置步骤&#xff1a; 第一步&#xff1a;给pc配置IP地址 第二步&#xff1a;交换机创建vlan,做access和trunk -所有的交换机都配…

传统图形学对nerf的对比与应用落地

作者今年参加了China3DV的盛会&#xff0c;大会的发表、线下讨论、学者、工业界等等的交流着实对于Nerf有了更深的思考&#xff0c;以下是作者的抛砖引玉&#xff0c;如有不当之处敬请指出~ 传统图形学与nerf的简介&#xff1a; 传统图形学&#xff1a;显示表达几何表达方式&…

【CloudCompare教程】010:点云的裁剪功能(分段、裁剪、筛选)

本文讲解CloudCompare点云的裁剪功能(分段、裁剪、筛选)。 文章目录 一、点云的分段二、点云的裁剪三、点云的筛选一、点云的分段 加载案例点云数据,如下图所示: 选中图层点云,点击工具栏中的【分割】工具。 点击【激活线状选择】工具: 在需要裁剪的点云上绘制现状裁剪范…

使用免费的SSL证书将nginx配置的普通网站修改为HTTPS网站

一、需求说明 已经在Centos8系统中使用nginx搭建了网站;但是该网站没有实现HTTPS协议不安全;现需要将网站升级为HTTPS站点。 Linux环境对Nginx开源版源码下载、编译、安装、开机自启https://blog.csdn.net/xiaochenXIHUA/article/details/130265983?spm=1001.2014.3001.5501

chatgpt赋能python:Python交易接口简介

Python交易接口简介 Python作为一种高级编程语言&#xff0c;被广泛用于各种不同的领域&#xff0c;其中包括金融市场交易。Python交易接口提供了一种优雅而简单的方式&#xff0c;使得交易者能够方便地执行自己的交易策略。 什么是Python交易接口&#xff1f; Python交易接…

Effective第三版 中英 | 第2章 创建和销毁对象 | 考虑静态工厂方法而不是构造函数

文章目录 Effective第三版第2章 创建和销毁对象前言考虑静态工厂方法而不是构造函数 Effective第三版 第2章 创建和销毁对象 前言 大家好&#xff0c;这里是 Rocky 编程日记 &#xff0c;喜欢后端架构及中间件源码&#xff0c;目前正在阅读 effective-java 书籍。同时也把自己…

基于SSM的人才招聘网站

末尾获取源码 开发语言&#xff1a;Java Java开发工具&#xff1a;JDK1.8 后端框架&#xff1a;SSM 前端&#xff1a;采用JSP技术开发 数据库&#xff1a;MySQL5.7和Navicat管理工具结合 服务器&#xff1a;Tomcat8.5 开发软件&#xff1a;IDEA / Eclipse 是否Maven项目&#x…

模拟实现库函数:strcpy

目录 通过cplusplus网站了解函数功能&#xff1a; 断言assert的使用&#xff1a; 关于const&#xff1a; 本篇你最应该了解的内容&#xff1a; 通过cplusplus网站了解函数功能&#xff1a; 要模拟实现库函数&#xff0c;首先我们需要了解这个函数的参数&#xff0c;函数的…

主机加固介绍

最近公司做服务器安全&#xff0c;开始在市场了解产品&#xff0c;对这一块算是短暂的研究了一段时间&#xff0c;有一点心得给大家分享一下。 主机加固 最近主机加固的概念被炒得火热&#xff0c;主机加固的功能也正在被致力于服务器安全的相关人士所关注。 那么究竟什么是主…

【CVPR2022】CSWin Transformer详解

【CVPR2022】CSWin Transformer详解 0. 引言1. 网络结构2. 创新点2.1 Cross-Shaped Window Self-Attention2.2 Locally-Enhanced Positional Encoding(LePE) 3. 实验总结 0. 引言 Transformer设计中一个具有挑战性的问题是&#xff0c;全局自注意力的计算成本非常高&#xff0…

chatgpt赋能python:Python代码怎么敲:了解Python编程语言

Python代码怎么敲&#xff1a;了解Python编程语言 Python是一种高级编程语言&#xff0c;具有易读易用和高效性等优点。这使得Python成为了程序员的最佳选择&#xff0c;并成为了广泛应用于机器学习、Web开发、数据分析等领域。 Python代码敲法&#xff1a;小技巧 Python代码…

chatgpt赋能python:Python主要语句介绍

Python主要语句介绍 Python是一种广泛使用的高级编程语言&#xff0c;其语法简介、易于学习&#xff0c;并有丰富的库和工具支持。在Python中&#xff0c;主要的语句可以帮助开发人员快速编写代码&#xff0c;实现各种各样的任务。在本文中&#xff0c;我们将介绍Python中的主…