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

文章目录

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

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

一、数据库设计

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

【Android开发基础】购物车代码整理_第1张图片

  • 实体(接收数据)
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.
     *
     * 

* The SQLite ALTER TABLE documentation can be found * here. 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. *

* This method executes within a transaction. If an exception is thrown, all changes * will automatically be rolled back. *

* * @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界面

  • 样图

【Android开发基础】购物车代码整理_第2张图片

  • UI界面设计

<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">

    
    <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);
    }

}

三、购物车模块

  • 样图

【Android开发基础】购物车代码整理_第3张图片

  • UI设计

<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">

    
    <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);
    }

}

四、添加

  • 样图
    【Android开发基础】购物车代码整理_第4张图片
  • UI界面设计

<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)

你可能感兴趣的:(Android开发,android)