android studio SQLite Database小例 | cfanr
##简述
SQLiteDatabase是一个可以进行增(Create)、查(Retrieve)、改(Update)、删(Delete)数据,即CRUD操作的类。
下面教程将向你展示如何使用SQLiteDatabase在Android中实现CRUD操作。
工具使用:
Android studio 1.1.0
TODO
在这个教程中,我们将创建一个app,允许对一个student表进行增查改删的数据操作。
很容易吗?是的,如果你知道怎样做的话 :)
##表结构
这个student表将用于存储学生的详细数据,为了简单,只创建3个域,如下图:

id是主键,允许自增
##页面布局
创建两个页面布局,第一个页面展示所有学生名字,如下图:

第二个页面是学生的详细信息的页面,用户点击listview的每个item时,将会进入这个页面,如下图:

##布局实现
1.新建一个SQLiteDemo的project;
2.实现第一个页面布局activity_main.xml
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 | <RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Add" android:id="@+id/btnAdd" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true" /> <ListView android:id="@android:id/list" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/btnAdd" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="List All" android:id="@+id/btnGetAll" android:layout_alignParentBottom="true" android:layout_toRightOf="@+id/btnAdd"/> </RelativeLayout> |
你需要修改ListView的id为 android:id=”@+id/listView” 如果你选择继承ListActivity在你的Activity类,否则将会出错;content必须有一个ListView,它的id的属性是‘android.R.id.list’
3.创建另一个activity,StudentDetail.java,其布局为第二个页面activity_student_detail.xml
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 | <RelativeLayout 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:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context="cn.cfanr.sqlitedemo.StudentDetail"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:id="@+id/tvName" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Email" android:id="@+id/tvEmail" android:layout_below="@id/tvName" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="30dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Age" android:id="@+id/tvAge" android:layout_below="@id/tvEmail" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:layout_marginTop="30dp" /> <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/etName" android:inputType="textPersonName" android:ems="10" android:layout_above="@id/tvEmail" android:layout_toRightOf="@id/tvName" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/etEmail" android:layout_toRightOf="@id/tvEmail" android:inputType="textEmailAddress" android:ems="10" android:layout_above="@id/tvAge" android:layout_alignParentRight="true" android:layout_alignParentEnd="true" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/etAge" android:inputType="number" android:ems="10" android:layout_alignBottom="@id/tvAge" android:layout_alignLeft="@id/etEmail" android:layout_alignStart="@id/etEmail" android:layout_alignRight="@id/etEmail" android:layout_alignEnd="@id/etEmail" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnClose" android:text="Close" android:layout_alignParentBottom="true" android:layout_alignParentRight="true" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnSave" android:text="Save" android:layout_alignParentBottom="true" android:layout_toLeftOf="@id/btnClose"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/btnDelete" android:text="Delete" android:layout_alignParentBottom="true" android:layout_toLeftOf="@id/btnSave"/> </RelativeLayout> |
4.当用户点击ListView的item时展示学生的详细信息的activity,所以我们需要一个特殊的id来检索学生的详细信息,并且这个id必须来自ListView,可以通过两个方法实现:
- 最简单的方法,可以放id和name进listview的item中,展示给用户(不好的UI设计),当用户点击选中item时,将检索的记录传递到StudentDetail.java的activity。
- 创建一个layout作为listview的item,通过item中包含学生的id(不过设置成隐藏)来检索学生的详细信息;
采用第二种方法,创建一个新的layout,view_student_entry.xml,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/student_Id" android:visibility="gone"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingLeft="6dip" android:paddingTop="6dip" android:textSize="22sp" android:textStyle="bold"/> </LinearLayout> |
##编码
1.创建Student类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | package cn.cfanr.sqlitedemo; /** * Created by ifanr on 2015/3/29. */ public class Student { //表名 public static final String TABLE="Student"; //表的各域名 public static final String KEY_ID="id"; public static final String KEY_name="name"; public static final String KEY_email="email"; public static final String KEY_age="age"; //属性 public int student_ID; public String name; public String email; public int age; } |
2.为了创建表,需要使用到SQLiteDatabase类(实现CRUD操作)和SQLiteOpenHelper(用于数据库的创建和版本管理),下面先创建一个DBHelper类
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 | package cn.cfanr.sqlitedemo; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.content.Context; /** * Created by ifanr on 2015/3/29. */ public class DBHelper extends SQLiteOpenHelper { //数据库版本号 private static final int DATABASE_VERSION=4; //数据库名称 private static final String DATABASE_NAME="crud.db"; public DBHelper(Context context){ super(context,DATABASE_NAME,null,DATABASE_VERSION); } public void onCreate(SQLiteDatabase db) { //创建数据表 String CREATE_TABLE_STUDENT="CREATE TABLE "+ Student.TABLE+"(" +Student.KEY_ID+" INTEGER PRIMARY KEY AUTOINCREMENT ," +Student.KEY_name+" TEXT, " +Student.KEY_age+" INTEGER, " +Student.KEY_email+" TEXT)"; db.execSQL(CREATE_TABLE_STUDENT); } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { //如果旧表存在,删除,所以数据将会消失 db.execSQL("DROP TABLE IF EXISTS "+ Student.TABLE); //再次创建表 onCreate(db); } } |
3.新建StudentRepo类,编写CRUD函数。
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 | package cn.cfanr.sqlitedemo; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import java.util.ArrayList; import java.util.HashMap; /** * Created by ifanr on 2015/3/29. */ public class StudentRepo { private DBHelper dbHelper; public StudentRepo(Context context){ dbHelper=new DBHelper(context); } public int insert(Student student){ //打开连接,写入数据 SQLiteDatabase db=dbHelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put(Student.KEY_age,student.age); values.put(Student.KEY_email,student.email); values.put(Student.KEY_name,student.name); // long student_Id=db.insert(Student.TABLE,null,values); db.close(); return (int)student_Id; } public void delete(int student_Id){ SQLiteDatabase db=dbHelper.getWritableDatabase(); db.delete(Student.TABLE,Student.KEY_ID+"=?", new String[]{String.valueOf(student_Id)}); db.close(); } public void update(Student student){ SQLiteDatabase db=dbHelper.getWritableDatabase(); ContentValues values=new ContentValues(); values.put(Student.KEY_age,student.age); values.put(Student.KEY_email,student.email); values.put(Student.KEY_name,student.name); db.update(Student.TABLE,values,Student.KEY_ID+"=?",new String[] { String.valueOf(student.student_ID) }); db.close(); } public ArrayList<HashMap<String, String>> getStudentList(){ SQLiteDatabase db=dbHelper.getReadableDatabase(); String selectQuery="SELECT "+ Student.KEY_ID+","+ Student.KEY_name+","+ Student.KEY_email+","+ Student.KEY_age+" FROM "+Student.TABLE; ArrayList<HashMap<String,String>> studentList=new ArrayList<HashMap<String, String>>(); Cursor cursor=db.rawQuery(selectQuery,null); if(cursor.moveToFirst()){ do{ HashMap<String,String> |