数据库的增删改查案例

来源:互联网 发布:ubuntu如何重置系统 编辑:程序博客网 时间:2024/05/22 03:22
一、
首先创建一个名为“商品展示”的应用程序。

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:layout_width="match_parent"    android:layout_height="match_parent"    android:layout_margin="8dp"    android:orientation="vertical"    tools:context="com.example.thinkpad.myapplication.MainActivity">    <LinearLayout        android:id="@+id/addLL"        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="1"            android:hint="商品名称"            android:inputType="textPersonName" />        <EditText            android:id="@+id/balanceET"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:hint="金额"            android:inputType="number" />        <ImageView            android:id="@+id/addIV"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:onClick="add"            android:src="@android:drawable/ic_input_add" />    </LinearLayout>    <ListView        android:id="@+id/accountLV"        android:layout_width="match_parent"        android:layout_height="match_parent"        android:layout_below="@id/addLL"></ListView></LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47

ImageView用来显示图片,使用了ImageView的属性Android:src来指定ImageView要显示的图片,但是只显示图片原图大小。但如果使用android:backgroud属性,图片的大小会根据ImageView的大小进行拉伸。

有一个“添加”按钮和两个EditText分别用于输入商品名称和金额。

item.xml:

<?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="wrap_content"    android:layout_margin="10dp"    android:orientation="horizontal">、    //数据的id    <TextView        android:id="@+id/idTV"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="1"        android:text="13"        android:textColor="@color/black"        android:textSize="20sp" />    //商品名称    <TextView        android:id="@+id/nameTV"        android:layout_width="0dp"        android:layout_height="wrap_content"        android:layout_weight="2"        android:singleLine="true"        android:text="PQ"        android:textColor="@color/black"        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="@color/black"        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="wrap_content"        android:layout_height="wrap_content"        android:src="@android:drawable/ic_menu_delete" /></LinearLayout>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70

此案例中用到了ListView布局,因此要编写一个ListViewItem的布局。我们添加三个TextView,分别用于显示数据库中的某条数据的id、商品名称、金额,三个ImageView用于增加金额、减少金额、删除数据。

MyHelper:

package com.example.thinkpad.myapplication;import android.content.Context;import android.database.sqlite.SQLiteDatabase;import android.database.sqlite.SQLiteOpenHelper;public class MyHelper extends SQLiteOpenHelper {    // 由于父类没有无参构造函数, 所以子类必须指定调用父类哪个有参的构造函数    public MyHelper(Context context) {        super(context, "itcast.db", null, 2);    }    public void onCreate(SQLiteDatabase db) {        System.out.println("onCreate");        db.execSQL("CREATE TABLE account(_id INTEGER PRIMARY KEY AUTOINCREMENT,"                + "name VARCHAR(20)," + // 姓名列                "balance INTEGER)"); // 金额列    }    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {        System.out.println("onUpgrade");    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

注意: 
MyHelper类一定要继承自SQLiteOpenHelper,重写onCreate()方法,并在该方法中执行创建数据库的命令。

实体类Account:

package com.example.thinkpad.myapplication;public class Account {    public Account() {        super();    }    public Account(String name, Integer balance) {        this.name = name;        this.balance = balance;    }    public Long getId() {        return id;    }    public Account(Long id, String name, Integer balance) {        this.id = id;        this.name = name;        this.balance = balance;    }    public String getName() {        return name;    }    public Integer getBalance() {        return balance;    }    public void setId(Long id) {        this.id = id;    }    public void setName(String name) {        this.name = name;    }    public void setBalance(Integer balance) {        this.balance = balance;    }    private Long id;    private String name;    private Integer balance;    @Override    public String toString() {        return "[序号:" + id + ", 商品名称:" + name + " ,余额:" + balance + "]";    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52

数据逻辑操作类AccountDao:

package com.example.thinkpad.myapplication;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 AccountDao {    private MyHelper helper;    public AccountDao(Context context) {        helper = new MyHelper(context);         // 创建Dao时, 创建Helper    }    public void insert(Account account) {        SQLiteDatabase db = helper.getWritableDatabase();         // 获取数据库对象        // 用来装载要插入的数据的 Map<列名, 列的值>        ContentValues values = new ContentValues();        values.put("name", account.getName());        values.put("balance", account.getBalance());        // 向account表插入数据values        long id = db.insert("account", null, values);         account.setId(id);  // 得到id        db.close();         // 关闭数据库    }    //根据id 删除数据    public int delete(long id) {        SQLiteDatabase db = helper.getWritableDatabase();        // 按条件删除指定表中的数据, 返回受影响的行数        int count = db.delete("account", "_id=?", new String[] { id + "" });        db.close();        return count;    }    //更新数据    public int update(Account account) {        SQLiteDatabase db = helper.getWritableDatabase();        ContentValues values = new ContentValues();        // 要修改的数据        values.put("name", account.getName());        values.put("balance", account.getBalance());        int count = db.update("account", values, "_id=?", new String[] { account.getId() + "" });         // 更新并得到行数        db.close();        return count;    }    //查询所有数据倒序排列    public List<Account> queryAll() {        SQLiteDatabase db = helper.getReadableDatabase();        Cursor c = db.query("account", null, null, null, null, null,                "balance DESC");        List<Account> list = new ArrayList<Account>();        while (c.moveToNext()) {            long id = c.getLong(c.getColumnIndex("_id"));             // 可以根据列名获取索引            String name = c.getString(1);            int balance = c.getInt(2);            list.add(new Account(id, name, balance));        }        c.close();        db.close();        return list;    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69

该类是对数据进行增、删、改、查操作的方法。

long id = db.insert("account", null, values);         // 向account表插入数据values
  • 1
  • 2
  • 3
  • 1
  • 2
  • 3

上述代码中insert()方法调用了db.insert()方法,这个方法第二个参数如果传入null,是无法插入一条空数据的。如果想插入一条空数据,第二个参数必须写一个列名(任意列),传入的这个列名是用来拼接SQL语句的,如下:

insert into account(null) values(null);
  • 1
  • 1

MainActivity:

package com.example.thinkpad.myapplication;import android.content.DialogInterface;import android.support.v7.app.AlertDialog;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.view.View;import android.view.ViewGroup;import android.widget.AdapterView;import android.widget.BaseAdapter;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 List<Account> list;    // 数据库增删改查操作类    private AccountDao dao;    // 输入姓名的EditText    private EditText nameET;    // 输入金额的EditText    private EditText balanceET;    // 适配器    private MyAdapter adapter;    // ListView    private ListView accountLV;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //初始化控件        initView();        dao = new AccountDao(this);        //从数据库中查询出所有数据        list = dao.queryAll();        adapter = new MyAdapter();        accountLV.setAdapter(adapter);//给ListView添加适配器(自动把数据生成条目)    }    //初始化控件    private void initView() {        accountLV = (ListView) findViewById(R.id.accountLV);        nameET = (EditText) findViewById(R.id.nameET);        balanceET = (EditText) findViewById(R.id.balanceET);        //添加监听器,监听条目点击事件        accountLV.setOnItemClickListener(new MyOnItemClickListener());    }    //activity_mian.xml 对应ImageView的点击事件触发的方法    public void add(View v) {        String name = nameET.getText().toString().trim();        String balance = balanceET.getText().toString().trim();        //三目运算 balance.equals(“”) 则等于0        //如果balance 不是空字符串 则进行类型转换        Account a = new Account(name, balance.equals("") ? 0 : Integer.parseInt(balance));        dao.insert(a);                      // 插入数据库        list.add(a);                        // 插入集合        adapter.notifyDataSetChanged(); // 刷新界面        // 选中最后一个        accountLV.setSelection(accountLV.getCount() - 1);        nameET.setText("");        balanceET.setText("");    }    // 自定义一个适配器(把数据装到ListView的工具)    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;        }        //获取一个条目视图        public View getView(int position, View convertView, ViewGroup parent) {            // 重用convertView            View item = convertView != null ? convertView : View.inflate(getApplicationContext(), R.layout.item, null);            // 获取该视图中的TextView            TextView idTV = (TextView) item.findViewById(R.id.idTV);            TextView nameTV = (TextView) item.findViewById(R.id.nameTV);            TextView balanceTV = (TextView) item.findViewById(R.id.balanceTV);            // 根据当前位置获取Account对象            final Account a = list.get(position);            // 把Account对象中的数据放到TextView中            idTV.setText(a.getId() + "");            nameTV.setText(a.getName());            balanceTV.setText(a.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() {                public void onClick(View v) {                    a.setBalance(a.getBalance() + 1); // 修改值                    notifyDataSetChanged(); // 刷新界面                    dao.update(a); // 更新数据库                }            });            //向下箭头的点击事件触发的方法            downIV.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {                    a.setBalance(a.getBalance() - 1);                    notifyDataSetChanged();                    dao.update(a);                }            });            //删除图片的点击事件触发的方法            deleteIV.setOnClickListener(new View.OnClickListener() {                public void onClick(View v) {                    //删除数据之前首先弹出一个对话框                    android.content.DialogInterface.OnClickListener listener =                            new android.content.DialogInterface.OnClickListener() {                                public void onClick(DialogInterface dialog, int which) {                                    list.remove(a);          // 从集合中删除                                    dao.delete(a.getId()); // 从数据库中删除                                    notifyDataSetChanged();// 刷新界面                                }                            };                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this); // 创建对话框                    builder.setTitle("确定要删除吗?");                    // 设置标题                    // 设置确定按钮的文本以及监听器                    builder.setPositiveButton("确定", listener);                    builder.setNegativeButton("取消", null);         // 设置取消按钮                    builder.show(); // 显示对话框                }            });            return item;        }    }    //ListView的Item点击事件    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {            // 获取点击位置上的数据            Account a = (Account) parent.getItemAtPosition(position);            Toast.makeText(getApplicationContext(), a.toString(), Toast.LENGTH_SHORT).show();        }    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
ListView的setOnItemClickListener()方法:该方法用于监听Item的点击事件,在使用该方法时需要传入一个OnItemClickListener的实现类对象,并且需要实现onItemClick方法。当点击ListView的Item时就会触发Item的点击事件然后会回调onItemClick()方法。ListView的setSelection()方法:该方法的作用是设置当前选中的条目。假设当前屏幕一屏只能显示10条数据,当添加地11条数据时,调用此方法就会将地11条数据显示在屏幕上,将第一条数据滑出屏幕外。Adapter的notifyDataSetChange()方法:该方法是用于刷新数据,当数据适配器中的内容发生变化时,会调用此方法,重新执行BaseAdapter中的getView()方法。
0 0
原创粉丝点击