shu数据库操作——商品展示

1.要求:

通过对数据库的增删改查来实现商品展示界面内商品的添加,删除等。

2.实现:

布局效果

1.activity_main.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:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_margin="8dp"
    tools:context="a360.cn.shopshow.MainActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <EditText
            android:id="@+id/nameET"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="商品名称"/>
        <EditText
            android:id="@+id/balanceET"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="2"
            android:hint="金额"/>
        <ImageView
            android:id="@+id/addIV"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="add"
            android:src="@drawable/add"/>
    </LinearLayout>

    <ListView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp">
    </ListView>

</LinearLayout>
2. ListView布局文件


实现代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_margin="10dp">
    <TextView
        android:id="@+id/idTV"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:text="13"
        android:textColor="#000000"
        android:textSize="20sp"/>

    <TextView
        android:id="@+id/nameTV"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="PQ"
        android:textColor="#000000"
        android:textSize="20sp"/>
    <TextView
        android:id="@+id/balanceTV"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="2"
        android:text="12345"
        android:textColor="#000000"
        android:textSize="20sp"/>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <ImageView
            android:id="@+id/upIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="2dp"
            android:src="@android:drawable/arrow_up_float"/>
        <ImageView
            android:id="@+id/downIV"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@android:drawable/arrow_down_float"/>
    </LinearLayout>
    <ImageView
        android:id="@+id/deleteIV"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:src="@android:drawable/ic_menu_delete"/>
</LinearLayout>
	数据库操作

创建数据库:DBHelper

package a360.cn.shopshow;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.Settings;

public class DBHelper extends SQLiteOpenHelper {
    private Context context;
    public static final String DB_NAME = "GoodsStore.db";
    public static final String CREATE_GOODS = "create table goods(id integer primary key autoincrement,name varchar(20),balance integer)";//商品名称列和金额列

    public DBHelper(Context context) {
        super(context, DB_NAME, null, 2);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        System.out.println("create succeed");
        db.execSQL(CREATE_GOODS);
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
        System.out.println("onUpgrade succeed");
    }

}
Goods类:

package a360.cn.shopshow;

public class Goods {
    private long id;
    private String name;
    private Integer balance;

    public Long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public Integer getBalance() {
        return balance;
    }

    public void setBalance(Integer balance) {
        this.balance = balance;
    }

    public Goods(Long id, String name, Integer balance) {
        super();
        this.id=id;
        this.balance = balance;
        this.name = name;
    }
    public Goods(String name,Integer balance){
        super();
        this.name=name;
        this.balance=balance;
    }
    public Goods(){
        super();
    }

    public String toString() {
        return "名称" + name + "价格" + balance;
    }
}
操作数据:GoodsDao.java

package a360.cn.shopshow;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;

public class GoodsDao {
    private DBHelper helper;

    public GoodsDao(Context context) {
        //创建Dao时,创建Helper
        helper = new DBHelper(context);
    }

    public void insert(Goods goods) {
        //获取数据库对象
        SQLiteDatabase db = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", goods.getName());
        values.put("balance", goods.getBalance());
        long id = db.insert("goods", null, values);
        goods.setId(id);
        db.close();//关闭数据库
    }
    //根据id删除数据
    public int detele(long id) {
        SQLiteDatabase db = helper.getWritableDatabase();
        int count = db.delete("goods", "id=?", new String[]{id + ""});
        db.close();
        return count;
    }
    //更新数据
    public int update(Goods goods) {
        SQLiteDatabase DB = helper.getWritableDatabase();
        ContentValues values = new ContentValues();
        values.put("name", goods.getName());
        values.put("balance", goods.getBalance());
        int count = DB.update("goods", values, "id=?", new String[]{goods.getId() + ""});
        DB.close();
        return count;
    }
    //查询所有数据倒序排列
    public List<Goods> queryAll() {
        SQLiteDatabase db = helper.getReadableDatabase();
        Cursor curor = db.query("goods", null, null, null, null, null, "balance DESC");
        List<Goods> list = new ArrayList<Goods>();
        while (curor.moveToNext()) {
            long id = curor.getLong(curor.getColumnIndex("id"));
            String name = curor.getString(1);
            int balance = curor.getInt(2);
            list.add(new Goods(id, name, balance));
        }
        db.close();
        curor.close();
        return list;
    }
}

编写界面交互:MainActivity.java

package a360.cn.shopshow;

import android.app.Activity;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView goodsLV;
    private GoodsDao goodsdao;
    private EditText nameET;
    private EditText balanceET;
    private MyAdapter adapter;
    private List<Goods> list;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        goodsdao = new GoodsDao(this);
        list = goodsdao.queryAll();
        adapter = new MyAdapter();
        goodsLV.setAdapter(adapter);
    }
    private void initView() {
        goodsLV = (ListView) findViewById(R.id.listView);
        nameET = (EditText) findViewById(R.id.nameET);
        balanceET = (EditText) findViewById(R.id.balanceET);
        goodsLV.setOnItemClickListener(new MyOnItemClickListener());

    }
    //点击事件触发
    public void add(View view) {
        String name = nameET.getText().toString().trim();
        String balance = balanceET.getText().toString().trim();
        Goods goods = new Goods(name, balance.equals("") ? 0 : Integer.parseInt(balance));
        goodsdao.insert(goods);
        list.add(goods);
        adapter.notifyDataSetChanged();
        goodsLV.setSelection(goodsLV.getCount() - 1);
        nameET.setText("");
        balanceET.setText("");
    }
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View item = convertView != null ? convertView : View.inflate(getApplicationContext(), R.layout.item, null);
            TextView idTV = (TextView) item.findViewById(R.id.idTV);
            TextView nameTV = (TextView) item.findViewById(R.id.nameTV);
            TextView balanceTV = (TextView) item.findViewById(R.id.balanceTV);
            final Goods g = list.get(position);
            idTV.setText(g.getId() + "");
            nameTV.setText(g.getName());
            balanceTV.setText(g.getBalance() + "");
            ImageView upIV = (ImageView) item.findViewById(R.id.upIV);
            ImageView downIV = (ImageView) item.findViewById(R.id.downIV);
            ImageView deleteIV = (ImageView) item.findViewById(R.id.deleteIV);
            //向上箭头的点击事件
            upIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    g.setBalance(g.getBalance() + 1);
                    notifyDataSetChanged();
                    goodsdao.update(g);
                }
            });
            //向下箭头的点击事件
            downIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    g.setBalance(g.getBalance() - 1);
                    notifyDataSetChanged();
                    goodsdao.update(g);
                }
            });
            //删除图片的点击事件
            deleteIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    android.content.DialogInterface.OnClickListener listener = new android.content.DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            list.remove(g);
                            goodsdao.detele(g.getId());
                            notifyDataSetChanged();
                        }
                    };
                    //创建对话框
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("确定要删除吗?");
                    builder.setPositiveButton("确定", listener);
                    builder.setNegativeButton("取消", null);
                    builder.show();
                }
            });
            return item;
        }
    }
    //ListView的点击事件
    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            Goods goods = (Goods) adapterView.getItemAtPosition(i);
            Toast.makeText(getApplicationContext(), goods.toString(), Toast.LENGTH_SHORT).show();
        }
    }
}
运行效果图:


 删除效果: 




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值