设计一个简单的学生信息管理程序,数据库名称创建为”ciec”,学生信息包括学号(表的主键)、姓名、性别、班级等,结合SQLite数据库实现对学生信息的添加、修改、删除与查询操作。
实验步骤
创建一个Activity,界面布局如图1所示,用户通过界面输入或选择学生信息,点击添加按钮后,将信息保存到数据库中,并在界面中提示操作成功或失败的信息。注意:输入的学号为数据库表的主键,学号不能为空也不能重复,需要在程序中对学号的信息进行合法性验证。
点击修改按钮和删除按钮可以对学生信息进行相应操作,但必须预先输入学号信息,否则提示操作无法成功。
点击查询按钮后,先跳转到新的Activity,在新的界面中展示查询结果,要求将所有的学生信息都查询出来,并用列表控件进行展示,界面布局如图2所示。
图1 图2
写了一天才写完,一开始写的时候一脸懵
说一下总共写了6个文件,Mainactivity,Secondactivity,DatabaseHelper,还有三个xml布局文件
先把布局文件贴出来
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent"
5 android:orientation="vertical">
6
7 <LinearLayout
8 android:layout_width="match_parent"
9 android:layout_height="50dp"
10 android:orientation="horizontal">
11
12 <TextView
13 android:layout_width="match_parent"
14 android:layout_height="match_parent"
15 android:layout_weight="3"
16 android:text=" 学号 : "/>
17 <EditText
18 android:id="@+id/Stdudent_ID"
19 android:layout_width="match_parent"
20 android:layout_height="match_parent"
21 android:layout_weight="1" />
22 </LinearLayout>
23
24 <LinearLayout
25 android:layout_width="match_parent"
26 android:layout_height="50dp"
27 android:orientation="horizontal">
28
29 <TextView
30 android:layout_width="match_parent"
31 android:layout_height="match_parent"
32 android:layout_weight="3"
33 android:text=" 姓名 : "/>
34 <EditText
35 android:id="@+id/Stdudent_NAME"
36 android:layout_width="match_parent"
37 android:layout_height="match_parent"
38 android:layout_weight="1" />
39 </LinearLayout>
40
41 <LinearLayout
42 android:layout_width="match_parent"
43 android:layout_height="50dp"
44 android:orientation="horizontal">
45
46 <TextView
47 android:layout_width="102dp"
48 android:layout_height="match_parent"
49 android:text="性别" />
50
51 <RadioGroup
52 android:id="@+id/Student_SEX"
53 android:layout_width="wrap_content"
54 android:layout_height="wrap_content"
55 android:orientation="horizontal" >
56
57 <RadioButton
58 android:id="@+id/Student_BOY"
59 android:layout_width="118dp"
60 android:layout_height="match_parent"
61 android:text="男" />
62
63 <RadioButton
64 android:id="@+id/Student_GIRL"
65 android:layout_width="110dp"
66 android:layout_height="match_parent"
67 android:text="女" />
68 </RadioGroup>
69 </LinearLayout>
70
71 <LinearLayout
72 android:layout_width="match_parent"
73 android:layout_height="50dp"
74 android:orientation="horizontal">
75
76 <TextView
77 android:layout_width="match_parent"
78 android:layout_height="match_parent"
79 android:layout_weight="3"
80 android:text=" 班级 : "/>
81 <EditText
82 android:id="@+id/Student_CLASS"
83 android:layout_width="match_parent"
84 android:layout_height="match_parent"
85 android:layout_weight="1" />
86 </LinearLayout>
87
88 <LinearLayout
89 android:layout_width="match_parent"
90 android:layout_height="50dp"
91 android:orientation="horizontal">
92
93 <Button
94 android:id="@+id/Stdudent_ADD"
95 android:layout_width="match_parent"
96 android:layout_height="wrap_content"
97 android:layout_weight="1"
98 android:text="添加" />
99 <Button
100 android:id="@+id/Stdudent_MV"
101 android:layout_width="match_parent"
102 android:layout_height="wrap_content"
103 android:layout_weight="1"
104 android:text="修改" />
105 <Button
106 android:id="@+id/Stdudent_RM"
107 android:layout_width="match_parent"
108 android:layout_height="wrap_content"
109 android:layout_weight="1"
110 android:text="删除" />
111 <Button
112 android:id="@+id/Stdudent_FIND"
113 android:layout_width="match_parent"
114 android:layout_height="wrap_content"
115 android:layout_weight="1"
116 android:text="查询" />
117 </LinearLayout>
118
119 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 android:layout_width="match_parent"
4 android:layout_height="match_parent">
5
6 <ListView
7 android:id="@+id/Student_ALL"
8 android:layout_height="fill_parent"
9 android:layout_width="fill_parent"/>
10
11 </LinearLayout>
1 <?xml version="1.0" encoding="utf-8"?>
2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3 xmlns:app="http://schemas.android.com/apk/res-auto"
4 android:layout_width="match_parent"
5 android:layout_height="match_parent">
6
7 <TextView
8 android:id="@+id/tv"
9 android:layout_width="match_parent"
10 android:layout_height="match_parent"/>
11
12 </LinearLayout>
这三个xml,第一个对应Mainactivity,后两个对应Secondactivity。
第一次使用SQLlite,就先使用一下
熟悉用法了,就可以开始写了
sqllite数据库是AndroidSDK自带的,所以我们写一个类继承SQLiteOpenHelper类(这是个抽象类),而且需要在这个类中实现三个方法:构造函数,onCreate,onUpgrade
1 package com.example.app; 2 3 import android.annotation.SuppressLint; 4 import android.content.Context; 5 import android.database.Cursor; 6 import android.database.sqlite.*; 7 8 public class DatabaseHelper extends SQLiteOpenHelper { //带全部参数的构造函数,name为数据库名称 9 public DatabaseHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,int version){ 10 super(context,name,factory,version); 11 } 12 13 @Override 14 public void onCreate(SQLiteDatabase db) { //建表 15 db.execSQL("CREATE TABLE information(\n" + 16 " id INTEGER PRIMARY KEY NOT NULL,\n" + 17 " name TEXT NOT NULL,\n" + 18 " sex TEXT NOT NULL,\n" + 19 " class TEXT NOT NULL\n" + 20 " )"); 21 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202001,\"张三\",\"男\",\"嵌入式1班\");"); 22 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202002,\"王乐\",\"男\",\"嵌入式1班\");"); 23 db.execSQL("INSERT into information(id,name,sex,class) VALUES (202003,\"刘小慧\",\"女\",\"网编1班\");"); 24 } 25 26 @Override 27 public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {//简单demo,就不写这个了 28 29 } 30 //只有conCreate()和onUpgrade是抽象方法,所以重写, 31 32 }
然后写Mainactivity,思路就是点击相对应的按钮做出相对应的操作
1 package com.example.app; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.annotation.SuppressLint; 6 import android.content.ContentValues; 7 import android.content.Intent; 8 import android.database.Cursor; 9 import android.database.sqlite.SQLiteDatabase; 10 import android.os.Bundle; 11 import android.view.View; 12 import android.widget.*; 13 14 public class MainActivity extends AppCompatActivity { 15 16 private EditText Student_ID; 17 private EditText Student_NAME; 18 private EditText Student_CLASS; 19 private RadioGroup Student_SEX; 20 private RadioButton Student_BOY; 21 private RadioButton Student_GIRL; 22 private Button Stdudent_ADD; 23 private Button Stdudent_MV; 24 private Button Stdudent_RM; 25 private Button Stdudent_FIND; 26 27 @Override 28 protected void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.homework_9_1); 31 32 //5.一开始写的时候以为这个语句会一直创建数据库,后来发现如果有这个数据库,就是直接连上去了,哈哈哈 33 //4.因为我们都在mainactivity上操作,所以就不提前在sqllit上建库了,直接在这个建库,开始运行时就把库先建好 34 final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2); 35 SQLiteDatabase db = databaseHelper.getWritableDatabase(); // 这里本来用.getreadableDatebase查一下,后来发现没有用到 36 //具体写的时候的思路都在注释里,写的时候不是线性的那种一路顺下来,就是想一点写一点补一点 37 38 //1.对学号姓名班级进行实例化 39 Student_ID = (EditText) findViewById(R.id.Stdudent_ID); 40 Student_NAME = (EditText) findViewById(R.id.Stdudent_NAME); 41 Student_CLASS = (EditText) findViewById(R.id.Student_CLASS); 42 //2.实例化和监听性别选项 43 Student_SEX = (RadioGroup) findViewById(R.id.Student_SEX); 44 Student_BOY = (RadioButton) findViewById(R.id.Student_BOY); 45 Student_GIRL = (RadioButton) findViewById(R.id.Student_GIRL); 46 47 //Student_SEX.setOnCheckedChangeListener(new MyRadioButtonListener()); 48 //10.应该在点击按钮的时候获取这个单选的值,这里不用了,对应的功能块在最底下被注释了的地方,换了方法请看63到69行 49 50 //6.获取输入框的内容,这里的代码移到了每个按钮点击后的动作里 51 // final String id = Student_ID.getText().toString().trim(); 52 // final String name = Student_NAME.getText().toString().trim(); 53 // final String classes = Student_CLASS.getText().toString().trim(); 54 55 //3.然后写增删改查功能 56 Stdudent_ADD = (Button) findViewById(R.id.Stdudent_ADD);//增 57 Stdudent_ADD.setOnClickListener(new View.OnClickListener() { 58 @Override 59 public void onClick(View v) { 60 final String id = Student_ID.getText().toString().trim(); 61 final String name = Student_NAME.getText().toString().trim(); 62 final String classes = Student_CLASS.getText().toString().trim(); 63 String sex = "0"; 64 if (Student_GIRL.isChecked()){ 65 sex = "女"; 66 } 67 if(Student_BOY.isChecked()){ 68 sex = "男"; 69 } 70 //8.我们设置的是学号姓名班级和性别都不能为空,所以进行判断 71 if (id.isEmpty() | name.isEmpty() | classes.isEmpty() | sex.equals("0")){//为null,则弹出提示框 使用isempty方法代替equals 72 Toast.makeText(MainActivity.this,"请将信息全部填完!!!",Toast.LENGTH_SHORT).show(); 73 }else{ 74 //7.将输入的内容插入数据库 75 //9.因为学号唯一,所以我们还得判断数据库中是否已经存在,如果存在则肯定不能插入了,否则和修改没啥区别了 76 SQLiteDatabase db = databaseHelper.getWritableDatabase(); //获得写入模式的数据库 77 ContentValues values = new ContentValues(); 78 //db.execSQL("select _id from information where _id = "+ id +";"); 79 Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null); 80 if(cursor.getCount()>0){ 81 Toast.makeText(MainActivity.this,"学生信息已经存在!!!",Toast.LENGTH_SHORT).show(); 82 }else { 83 values.put("id",id); 84 values.put("name",name); 85 values.put("sex", sex); 86 values.put("class",classes); 87 db.insert("information",null,values); 88 Toast.makeText(MainActivity.this,"增加成功!!!",Toast.LENGTH_SHORT).show(); 89 } 90 } 91 } 92 }); 93 94 Stdudent_MV = (Button) findViewById(R.id.Stdudent_MV);//改 95 Stdudent_MV.setOnClickListener(new View.OnClickListener() { 96 @Override 97 public void onClick(View v) { 98 final String id = Student_ID.getText().toString().trim(); 99 final String name = Student_NAME.getText().toString().trim(); 100 final String classes = Student_CLASS.getText().toString().trim(); 101 String sex = "0"; 102 if (Student_GIRL.isChecked()){ 103 sex = "女"; 104 } 105 if(Student_BOY.isChecked()){ 106 sex = "男"; 107 } 108 //修改必须有学号,所以点击修改按钮时就会覆盖相对应的学号的其他的值, 109 //就是说学号必须有,如果学号对应的账号信息被删除,则应该提示无此学生信息 110 if (id.isEmpty()){ 111 Toast.makeText(MainActivity.this,"学号不能为空!!!",Toast.LENGTH_SHORT).show(); 112 }else { 113 SQLiteDatabase db = databaseHelper.getWritableDatabase(); 114 ContentValues values2 = new ContentValues(); 115 ContentValues values3 = new ContentValues(); 116 ContentValues values4 = new ContentValues(); 117 Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null); 118 if (cursor.getCount()>0){ 119 values2.put("name",name); 120 values3.put("sex", sex); 121 values4.put("class",classes); 122 db.update("information",values2,"id = ?",new String[]{id}); 123 db.update("information",values3,"id = ?",new String[]{id}); 124 db.update("information",values4,"id = ?",new String[]{id}); 125 Toast.makeText(MainActivity.this,"修改成功!!!",Toast.LENGTH_SHORT).show(); 126 }else { 127 Toast.makeText(MainActivity.this,"无此学生!!!",Toast.LENGTH_SHORT).show(); 128 } 129 } 130 } 131 }); 132 133 Stdudent_RM = (Button) findViewById(R.id.Stdudent_RM);//删 134 Stdudent_RM.setOnClickListener(new View.OnClickListener() { 135 @Override 136 public void onClick(View v) { 137 final String id = Student_ID.getText().toString().trim(); 138 final String name = Student_NAME.getText().toString().trim(); 139 final String classes = Student_CLASS.getText().toString().trim(); 140 //删除只需要有学号就可以 141 if(id.equals("")){ 142 Toast.makeText(MainActivity.this,"学号不能为空!!!",Toast.LENGTH_SHORT).show(); 143 }else { 144 SQLiteDatabase db = databaseHelper.getWritableDatabase(); 145 db.delete("information","id=?",new String[]{id}); 146 Toast.makeText(MainActivity.this,"删除成功!!!",Toast.LENGTH_SHORT).show(); 147 } 148 } 149 }); 150 151 Stdudent_FIND = (Button) findViewById(R.id.Stdudent_FIND);//查 152 Stdudent_FIND.setOnClickListener(new View.OnClickListener() { 153 @Override 154 public void onClick(View v) { 155 //这里跳转到另一个activity,原本的写法是查询在这里完成,然后把数据传到下一个activity中,写的时候发现传过去的数据还要进行处理,就换成在另一个activity中进行查询了 156 startActivity(new Intent(MainActivity.this,SecondActivity.class)); 157 } 158 }); 159 } 160 // static class MyRadioButtonListener implements RadioGroup.OnCheckedChangeListener { //单选的类 161 // @Override 162 // public void onCheckedChanged(RadioGroup group, int checkedId) { 163 // String sex; 164 // // 选中状态改变时被触发 165 // switch (checkedId) { 166 // case R.id.Student_GIRL: 167 // // 当用户选择女性时 168 // sex = "女"; 169 // break; 170 // case R.id.Student_BOY: 171 // // 当用户选择男性时 172 // sex = "男"; 173 // break; 174 // } 175 // } 176 // } 177 178 179 }
然后写Secondactivity
没啥好说的,就是查询,然后将数据展示出来
这里说一个知识点
1 package com.example.app; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 import androidx.appcompat.app.AlertDialog; 5 6 import android.database.Cursor; 7 import android.database.sqlite.SQLiteDatabase; 8 import android.text.TextUtils; 9 10 import android.os.Bundle; 11 import android.view.LayoutInflater; 12 import android.view.View; 13 import android.view.ViewGroup; 14 import android.widget.ArrayAdapter; 15 import android.widget.BaseAdapter; 16 import android.widget.ListView; 17 import android.widget.TextView; 18 19 import java.util.ArrayList; 20 21 public class SecondActivity extends AppCompatActivity { 22 23 private ListView Student_ALL; 24 String[] data; 25 ArrayList<String> stringArrayList = new ArrayList<String>(); 26 27 @Override 28 protected void onCreate(Bundle savedInstanceState) { 29 super.onCreate(savedInstanceState); 30 setContentView(R.layout.homework_9_2); 31 final DatabaseHelper databaseHelper = new DatabaseHelper(this,"ciec.db",null,2); 32 33 Student_ALL = (ListView) findViewById(R.id.Student_ALL); 34 35 SQLiteDatabase db = databaseHelper.getWritableDatabase(); 36 Cursor cursor = db.query("information", new String[]{"id","name","sex","class"}, null, null, null, null, null); 37 String textview_data = ""; 38 //利用游标遍历所有数据对象 39 //为了显示全部,把所有对象连接起来,放到TextView中 40 while(cursor.moveToNext()){ 41 String qwe = cursor.getString(cursor.getColumnIndex("id")); 42 String asd = cursor.getString(cursor.getColumnIndex("name")); 43 String zxc = cursor.getString(cursor.getColumnIndex("sex")); 44 String qaz = cursor.getString(cursor.getColumnIndex("class")); 45 textview_data = qwe + "--" + asd +"--" + zxc +"--" + qaz; 46 stringArrayList.add(textview_data); 47 } 48 //利用arraylist,保存数据,然后在转换成String[]数组 49 String [] stringArray = stringArrayList.toArray(new String[stringArrayList.size()]); 50 data = stringArray; 51 ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,R.id.LS);//新建并配置ArrayAapeter 52 MyBaseAdapter mAdapter = new MyBaseAdapter(); 53 Student_ALL.setAdapter(mAdapter); 54 } 55 56 class MyBaseAdapter extends BaseAdapter { 57 58 @Override 59 public int getCount() { 60 return data.length; 61 } 62 @Override 63 public Object getItem(int position) { 64 return null; 65 } 66 @Override 67 public long getItemId(int position) { 68 return 0; 69 } 70 @Override 71 public View getView(int position, View convertView, ViewGroup parent) { 72 ViewHolder holder; 73 if(convertView == null){ 74 convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.homework_five_2,parent,false); 75 holder = new ViewHolder(); 76 holder.mTextView = (TextView) convertView.findViewById(R.id.tv); 77 convertView.setTag(holder); 78 }else { 79 holder = (ViewHolder) convertView.getTag(); 80 } 81 holder.mTextView.setText(data[position]); 82 return convertView; 83 } 84 class ViewHolder { 85 TextView mTextView; 86 } 87 } 88 }
最后的成品:
到了总结的时候啦!
插入数据:
所谓的内容值,就是一个K,V 键值对,K指明字段名称即列名称,V指明字段值,即单元格内容。然后将这个键值对放到ContentValues的对象values里面,再把携带着键值对的对象values插入user表中
1 ContentValues values = new ContentValues(); 2 values.put("id",id); 3 db.insert("information",null,values);
删除数据:
db.delete("information","id=?",new String[]{id});
第一个参数是表名,第二个参数是删除条件,第三个参数就是你要删除的值,简单理解就是它会赋值给第二个参数的问号。
修改数据:
和插入数据相似,.update中的第一个参数是表名,第二个参数就是我们要修改的列名和值,第三个参数是修改条件,第四个参数是修改条件的值
1 ContentValues values2 = new ContentValues(); 2 values2.put("name",name); 3 db.update("information",values2,"id = ?",new String[]{id});
查询数据:
频繁的用到查询语句,然后查询语句也是我花时间最长的
Cursor cursor = db.query("information", new String[]{"id"},"id = ?", new String[] {id}, null, null, null);
这句写在插入功能,使用了Cursor游标进行查询,后面的循环遍历所有数据就不说了,单说一下这条语句
cursor就是游标对象,查询函数是.query,第一个参数是表名,第二个参数就是select * from 表名 where name = “”;中的*号,第三个参数就是查询条件(where后跟的name = ),第四个参数是查询条件的值,再往后的几个参数就是各种查询约束了,在上面的查询知识点说的很清楚。
还有一种查询函数是.rawQuery,这种查询方式是这样的
.rawQuery(sql,selectionArgs)
第一个参数是sql语句,第二个参数要么是null,要么必须是一个字符串数组,还有第三个参数,没用过不知道是啥
比如这样
Cursor cursor = db.rawQuery("select name from * where id=?", new String[]{"1"});
这两个函数的主要区别是rawQuery是直接使用SQL语句进行查询的,也就是第一个参数字符串,在字符串内的“?”会被后面的String[]数组逐一对换掉;而query函数是Android自己封装的查询API
写代码的时候有好多问题要总结的,结果写博客的时候发现都忘光了,不知道该写什么,哭
补一张图:
加油,未来可期!