##简述
SQLiteDatabase是一个可以进行增(Create)、查(Retrieve)、改(Update)、删(Delete)数据,即CRUD操作的类。
下面教程将向你展示如何使用SQLiteDatabase在Android中实现CRUD操作。

工具使用:
Android studio 1.1.0

TODO
在这个教程中,我们将创建一个app,允许对一个student表进行增查改删的数据操作。
很容易吗?是的,如果你知道怎样做的话 :)

##表结构
这个student表将用于存储学生的详细数据,为了简单,只创建3个域,如下图:

student表.jpg

id是主键,允许自增

##页面布局
创建两个页面布局,第一个页面展示所有学生名字,如下图:

学生列表.jpg

第二个页面是学生的详细信息的页面,用户点击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);
}
@Override
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);
}
@Override
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> student=new HashMap<String,String>();
student.put("id",cursor.getString(cursor.getColumnIndex(Student.KEY_ID)));
student.put("name",cursor.getString(cursor.getColumnIndex(Student.KEY_name)));
studentList.add(student);
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return studentList;
}
public Student getStudentById(int Id){
SQLiteDatabase db=dbHelper.getReadableDatabase();
String selectQuery="SELECT "+
Student.KEY_ID + "," +
Student.KEY_name + "," +
Student.KEY_email + "," +
Student.KEY_age +
" FROM " + Student.TABLE
+ " WHERE " +
Student.KEY_ID + "=?";
int iCount=0;
Student student=new Student();
Cursor cursor=db.rawQuery(selectQuery,new String[]{String.valueOf(Id)});
if(cursor.moveToFirst()){
do{
student.student_ID =cursor.getInt(cursor.getColumnIndex(Student.KEY_ID));
student.name =cursor.getString(cursor.getColumnIndex(Student.KEY_name));
student.email =cursor.getString(cursor.getColumnIndex(Student.KEY_email));
student.age =cursor.getInt(cursor.getColumnIndex(Student.KEY_age));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
return student;
}
}

4.用户点击item,进入的详细页面StudentDetail

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
package cn.cfanr.sqlitedemo;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class StudentDetail extends ActionBarActivity implements View.OnClickListener {
private Button btnSave,btnDelete;
private Button btnClose;
private EditText etName;
private EditText etEmail;
private EditText etAge;
private int _student_id=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_detail);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnClose = (Button) findViewById(R.id.btnClose);
etName = (EditText) findViewById(R.id.etName);
etEmail = (EditText) findViewById(R.id.etEmail);
etAge = (EditText) findViewById(R.id.etAge);
btnSave.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnClose.setOnClickListener(this);
_student_id =0;
Intent intent = getIntent();
_student_id =intent.getIntExtra("student_Id", 0);
StudentRepo repo = new StudentRepo(this);
Student student = new Student();
student = repo.getStudentById(_student_id);
etAge.setText(String.valueOf(student.age));
etName.setText(student.name);
etEmail.setText(student.email);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_student_detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onClick(View v) {
if(v==findViewById(R.id.btnSave)){
StudentRepo repo=new StudentRepo(this);
Student student=new Student();
student.age=Integer.parseInt(etAge.getText().toString());
student.email=etEmail.getText().toString();
student.name=etName.getText().toString();
student.student_ID=_student_id;
if(_student_id==0){
_student_id=repo.insert(student);
Toast.makeText(this,"New Student Insert",Toast.LENGTH_SHORT).show();
}else{
repo.update(student);
Toast.makeText(this,"Student Record updated",Toast.LENGTH_SHORT).show();
}
}else if (v== findViewById(R.id.btnDelete)){
StudentRepo repo = new StudentRepo(this);
repo.delete(_student_id);
Toast.makeText(this, "Student Record Deleted", Toast.LENGTH_SHORT);
finish();
}else if (v== findViewById(R.id.btnClose)){
finish();
}
}
}

5.在MainActivity实现获取学生列表和跳转到StudentDetail页面

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
package cn.cfanr.sqlitedemo;
import android.app.ListActivity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
public class MainActivity extends ListActivity implements android.view.View.OnClickListener {
private Button btnAdd,btnGetAll;
private TextView student_Id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnGetAll = (Button) findViewById(R.id.btnGetAll);
btnGetAll.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v== findViewById(R.id.btnAdd)){
Intent intent = new Intent(this,StudentDetail.class);
intent.putExtra("student_Id",0);
startActivity(intent);
}else {
StudentRepo repo = new StudentRepo(this);
ArrayList<HashMap<String, String>> studentList = repo.getStudentList();
if(studentList.size()!=0) {
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
student_Id = (TextView) view.findViewById(R.id.student_Id);
String studentId = student_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(),StudentDetail.class);
objIndent.putExtra("student_Id", Integer.parseInt( studentId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter( MainActivity.this,studentList, R.layout.view_student_entry, new String[] { "id","name"}, new int[] {R.id.student_Id, R.id.student_name});
setListAdapter(adapter);
}else{
Toast.makeText(this, "No student!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

6.运行结果如下:

学生列表(添加数据后,原来为空)

学生详细信息页面.png

参考http://instinctcoder.com/android-studio-sqlite-database-example/

另外,SQLite的详细资料,Android中SQLite应用详解