Android 資料儲存 利用SQLiteDatabase實現簡單的學生管理
這是作為上一篇Android 資料儲存 如何搞定SQLite Database的例項練習,之所以單獨列出來是因為除了資料庫方面的知識,還涉及其它方面的知識,所以就寫的詳細點,囉嗦點。希望對初學者有所幫助。當然這個Demo比較簡單,有很多可以改進的地方,但那不是這裡探討的重點,重點學習如何將SQLiteDatabase資料繫結到我們的介面!
我們要做一個簡單的學生管理的demo,建立student.db,包括name,grade欄位,實現增、刪、改、查的功能;
實現效果:
1,介面分析
我們先不忙著碼程式碼,先來看看這樣一個簡單的Demo**基本的介面結構**:
- 主介面是一個ListView用來顯示學生資訊,底部有兩個Button,用來新增和查詢學生資訊;
- 點選**“新增”**Button,進入新增介面,輸入姓名,分數,新增成功後返回主介面;
- 點選**“查詢”**Button,彈出查詢對話方塊,查詢對話方塊此時包含一個EditView用來輸入學生姓名和一個“查詢”Button,當點選查詢Button後,顯示查詢結果,如果查詢結果為空,提示無此資訊,如果不為空,點選結果可進入詳細介面。
- 點選ListView Item可檢視學生詳細資訊,在詳細資訊介面可對學生資訊進行編輯修改和刪除。
2,需要的的知識點:
- 自定義View的AlertDialog
- 自定義Adapter的ListView:用來展示學生資訊的ListView需要我們自定義Adapter將資料庫中的資料填充到ListView。
- Activity之間的資訊傳遞:我們需要將學生資訊從一個Activity傳遞到另一個Activity,比如檢視學生資訊,或者新增成功後返回主介面,涉及到
Intent
和startActivityForResult()
等的使用。 - SQLiteDatabase的基本使用:這也是我們這個練習的重點,不熟悉的建議先看上篇文章Android 資料儲存 如何搞定SQLite Database
3,具體實現
建立專案後,根據上一篇文章所說,我們按照以下步驟來完成我們的Demo:
1,介面佈局
通過介面分析我們可以看出:MainActivity用來顯示所有學生列表資訊,其他介面提供檢視或者編輯修改以及刪除的功能,在介面佈局上非常相似,所以我們將它們放到同一個佈局裡面,只不過根據具體的情況,設定個某些控制元件的Visibility
屬性為GONE
或者VISIBLE
;
主介面佈局:res/layout/activity_main.xml
,包含一個ListView和兩個Button
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="@+id/stduent_list"
android:layout_alignParentTop="true"
android:divider="#5ABC4F"
android:dividerHeight="1dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<LinearLayout
android:layout_alignParentBottom="true"
android:orientation="horizontal"
android:layout_marginTop="3dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<Button
android:id="@+id/btn_add"
android:text="添 加"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:layout_marginRight="5dp"
android:background="#5ABC4F"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="45dp" />
<Button
android:id="@+id/btn_search"
android:text="查 找"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:layout_marginLeft="5dp"
android:background="#5ABC4F"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="45dp" />
</LinearLayout>
</RelativeLayout>
詳細介面(增刪改介面)佈局:res/layout/student.xml
,在佈局檔案裡面我們先將**查詢**Button的Visibility屬性設定為GONE,即不可見(注意區分:INVISIBLE為不可見但佔據佈局位置,GONE不可見且不佔據位置)。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:src="@mipmap/boy"
android:id="@+id/student_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/student_name"
android:hint="輸入姓名"
android:gravity="center"
android:textSize="20sp"
android:textColor="#5ABC4F"
android:layout_marginTop="20dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:id="@+id/student_grade"
android:hint="輸入分數"
android:gravity="center"
android:textSize="15sp"
android:textColor="#5ABC4F"
android:layout_marginTop="10dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_change"
android:text="修 改"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:layout_margin="10dp"
android:background="#5ABC4F"
android:layout_width="match_parent"
android:layout_height="45dp" />
<Button
android:id="@+id/btn_delete"
android:text="刪 除"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:layout_margin="10dp"
android:background="#5ABC4F"
android:layout_width="match_parent"
android:layout_height="45dp" />
<Button
android:id="@+id/btn_add_student"
android:text="添 加"
android:visibility="gone"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:layout_margin="10dp"
android:background="#5ABC4F"
android:layout_width="match_parent"
android:layout_height="45dp" />
</LinearLayout>
ListView Item佈局:,用來顯示學生頭像,姓名和分數,res/layout/list_item.xml
佈局效果:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:src="@mipmap/boy"
android:id="@+id/image"
android:layout_alignParentLeft="true"
android:padding="4dp"
android:layout_width="80dp"
android:layout_height="80dp" />
<TextView
android:id="@+id/name"
android:text="姓名"
android:textSize="20sp"
android:textColor="#5ABC4F"
android:layout_toRightOf="@+id/image"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/grade"
android:layout_toRightOf="@+id/image"
android:layout_below="@+id/name"
android:text="分數"
android:textSize="15sp"
android:textColor="#5ABC4F"
android:layout_marginTop="8dp"
android:layout_marginLeft="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
查詢對話方塊佈局:我們還需要為查詢對話方塊做一個佈局,res/layout/dialog_search.xml
,注意,剛開始搜尋時,只顯示EditView用來輸入學生姓名,顯示搜尋結果時EditView不可見而顯示一個ListView,所以佈局中先將ListView的Visibility屬性為GONE
佈局效果:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:gravity="center"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/search_name"
android:gravity="center"
android:textSize="20sp"
android:textColor="#5ABC4F"
android:hint="學生姓名"
android:layout_width="wrap_content"
android:layout_margin="10dp"
android:layout_height="50dp" />
<ListView
android:id="@+id/search_result"
android:visibility="gone"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
<Button
android:id="@+id/btn_search_dialog"
android:layout_margin="10dp"
android:text="查 找"
android:textSize="25sp"
android:textColor="#ffffff"
android:gravity="center"
android:background="#5ABC4F"
android:layout_width="match_parent"
android:layout_height="45dp" />
</LinearLayout>
2,建立Student類:首先需要為我們儲存的資料建立一個Model類,便於在使用中獲取欄位和物件。
Student.java
:為其提供建構函式和set\get方法;
public class Student implements Serializable{
private int id;
private String name;
private String grade;
public Student(){}
public Student(int id, String name, String grade) {
this.id = id;
this.name = name;
this.grade = grade;
}
public Student(String name, String grade) {
this.name = name;
this.grade = grade;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getGrade() {
return grade;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setGrade(String grade) {
this.grade = grade;
}
}
3,建立DatabaseHandler類:用來封裝我們的資料庫操作
DatabaseHandler.java
:編寫建構函式,覆寫onCreate(),onUpgrade()方法,以及提供增刪改查student的方法:
addStudent(Student student)
;新增studentgetStudent(String name)
,通過name獲取studentgetAllStudent()
;獲取所有的studentgetStudentCounts()
;獲取student數目updateStudent(Student student)
;更新studentdeleteStudent(Student student)
;刪除student
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME="Test";
private static final String TABLE_NAME="student";
private static final int VERSION=1;
private static final String KEY_ID="id";
private static final String KEY_NAME="name";
private static final String KEY_GRADE="grade";
//建表語句
private static final String CREATE_TABLE="create table "+TABLE_NAME+"("+KEY_ID+
" integer primary key autoincrement,"+KEY_NAME+" text not null,"+
KEY_GRADE+" text not null);";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(CREATE_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(sqLiteDatabase);
}
public void addStudent(Student student){
SQLiteDatabase db=this.getWritableDatabase();
//使用ContentValues新增資料
ContentValues values=new ContentValues();
values.put(KEY_NAME,student.getName());
values.put(KEY_GRADE,student.getGrade());
db.insert(TABLE_NAME, null, values);
db.close();
}
public Student getStudent(String name){
SQLiteDatabase db=this.getWritableDatabase();
//Cursor物件返回查詢結果
Cursor cursor=db.query(TABLE_NAME,new String[]{KEY_ID,KEY_NAME,KEY_GRADE},
KEY_NAME+"=?",new String[]{name},null,null,null,null);
Student student=null;
//注意返回結果有可能為空
if(cursor.moveToFirst()){
student=new Student(cursor.getInt(0),cursor.getString(1), cursor.getString(2));
}
return student;
}
public int getStudentCounts(){
String selectQuery="SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery(selectQuery,null);
cursor.close();
return cursor.getCount();
}
//查詢所有student
public List<Student> getALllStudent(){
List<Student> studentList=new ArrayList<Student>();
String selectQuery="SELECT * FROM "+TABLE_NAME;
SQLiteDatabase db=this.getReadableDatabase();
Cursor cursor=db.rawQuery(selectQuery,null);
if(cursor.moveToFirst()){
do{
Student student=new Student();
student.setId(Integer.parseInt(cursor.getString(0)));
student.setName(cursor.getString(1));
student.setGrade(cursor.getString(2));
studentList.add(student);
}while(cursor.moveToNext());
}
return studentList;
}
//更新student
public int updateStudent(Student student){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(KEY_NAME,student.getName());
values.put(KEY_GRADE,student.getGrade());
return db.update(TABLE_NAME,values,KEY_ID+"=?",new String[]{String.valueOf(student.getId())});
}
public void deleteStudent(Student student){
SQLiteDatabase db=this.getWritableDatabase();
db.delete(TABLE_NAME,KEY_ID+"=?",new String[]{String.valueOf(student.getId())});
db.close();
}
}
4,自定義Adapter:StudentAdapter:ListView需要自定義Adapter來顯示檢視,自定義Adapter擴充套件自BaseAdapter,覆寫其中四個方法即可,其中getView()方法用來控制沒個ListView item的具體顯示。
public class StudentAdapter extends BaseAdapter {
private List<Student> students;
private Context context;
public StudentAdapter(Context context,List<Student> students) {
super();
this.students=students;
this.context=context;
}
@Override
public int getCount() {
return students.size();
}
@Override
public Object getItem(int i) {
return students.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
if(view==null){
view= LayoutInflater.from(context).inflate(R.layout.list_item,viewGroup,false);
}
ImageView imageView= (ImageView) view.findViewById(R.id.image);
TextView tvName= (TextView) view.findViewById(R.id.name);
TextView tvGrade= (TextView) view.findViewById(R.id.grade);
//隨機為學生匹配頭像
if(students.get(i).getId()%2==0)
{
imageView.setImageResource(R.mipmap.girl1);
}else{
imageView.setImageResource(R.mipmap.boy2);
}
tvName.setText("姓名 "+students.get(i).getName());
tvGrade.setText("分數 "+students.get(i).getGrade());
return view;
}
}
5,完成MainActivity:在這裡要注意startActivityForResult()的使用,和為自定義View的AlertDialog新增事件監聽。
public class MainActivity extends Activity implements View.OnClickListener{
private ListView students;
private StudentAdapter adapter;
private Button btnAdd,btnSearch;
private DatabaseHandler dbHandler;
private List<Student> studentList;
private SQLiteDatabase db;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
students= (ListView) findViewById(R.id.stduent_list);
btnAdd= (Button) findViewById(R.id.btn_add);
btnSearch= (Button) findViewById(R.id.btn_search);
btnSearch.setOnClickListener(this);
btnAdd.setOnClickListener(this);
dbHandler=new DatabaseHandler(this);
//獲取全部學生資訊
studentList=dbHandler.getALllStudent();
adapter=new StudentAdapter(this,studentList);
students.setAdapter(adapter);
//點選ListView item跳轉到詳細介面
students.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Intent intent=new Intent(MainActivity.this,StudentActivity.class);
//注意這裡的request是為了區分是通過什麼跳轉到詳細介面的
intent.putExtra("request","Look");
intent.putExtra("id",studentList.get(i).getId());
intent.putExtra("name",studentList.get(i).getName());
intent.putExtra("grade",studentList.get(i).getGrade());
//
startActivityForResult(intent, 0);
}
});
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_add:
Intent i=new Intent(MainActivity.this,StudentActivity.class);
i.putExtra("request","Add");
startActivityForResult(i, 1);
break;
case R.id.btn_search:
AlertDialog.Builder builder=new AlertDialog.Builder(this);
//自定義View的Dialog
final LinearLayout searchView= (LinearLayout) getLayoutInflater().inflate(R.layout.dialog_search,null);
builder.setView(searchView);
final AlertDialog dialog=builder.create();
dialog.show();
//為自定義View的Dialog的控制元件新增事件監聽。
final EditText searchName= (EditText) searchView.findViewById(R.id.search_name);
Button btnDialogSearch= (Button) searchView.findViewById(R.id.btn_search_dialog);
btnDialogSearch.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
searchName.setVisibility(View.GONE);
ListView list = (ListView) searchView.findViewById(R.id.search_result);
List<Student> resultList = new ArrayList<Student>();
final Student searchStudent = dbHandler.getStudent(searchName.getText().toString());
if (searchStudent != null) {
resultList.add(searchStudent);
StudentAdapter resultAdapter = new StudentAdapter(getApplicationContext(), resultList);
list.setAdapter(resultAdapter);
list.setVisibility(View.VISIBLE);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
dialog.dismiss();
Intent intent = new Intent(MainActivity.this, StudentActivity.class);
intent.putExtra("request", "Look");
intent.putExtra("id", searchStudent.getId());
intent.putExtra("name", searchStudent.getName());
intent.putExtra("grade", searchStudent.getGrade());
startActivityForResult(intent, 0);
}
});
} else {
//關閉Dialog
dialog.dismiss();
Toast.makeText(getApplicationContext(), "無此學生", Toast.LENGTH_SHORT).show();
}
}
});
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//根據返回的resultCode判斷是通過哪種操作返回的,並提示相關資訊;
switch (requestCode){
case 0:
if (resultCode==2)
Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
if (resultCode==3)
Toast.makeText(this,"已刪除",Toast.LENGTH_SHORT).show();
break;
case 1:
if (resultCode==RESULT_OK)
Toast.makeText(this,"新增成功",Toast.LENGTH_SHORT).show();
break;
}
/**
* 如果這裡僅僅使用adapter.notifyDataSetChanged()是不會重新整理介面ListView的,
* 因為此時adapter中傳入的studentList並沒有給重新整理,即adapter也沒有被重新整理,所以你可以
* 重新獲取studentList後再改變adapter,我這裡通過呼叫onCreate()重新重新整理了整個介面
*/
// studentList=dbHandler.getALllStudent();
// adapter=new StudentAdapter(this,studentList);
// students.setAdapter(adapter);
onCreate(null);
}
}
6,建立StudentActivity:用來展示詳細資訊和修改,刪除。
public class StudentActivity extends Activity implements View.OnClickListener{
private EditText etName,etGrade;
private ImageView imageView;
private Button btnChange,btnDelete,btnAdd;
private int id;
private DatabaseHandler handler;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.student);
etName= (EditText) findViewById(R.id.student_name);
etGrade= (EditText) findViewById(R.id.student_grade);
btnChange= (Button) findViewById(R.id.btn_change);
btnDelete= (Button) findViewById(R.id.btn_delete);
btnAdd= (Button) findViewById(R.id.btn_add_student);
imageView= (ImageView) findViewById(R.id.student_image);
handler=new DatabaseHandler(this);
//獲取傳遞過來的intent
intent=getIntent();
//通過request判斷,是通過那個Button點選進入的,之後隱藏或者顯示相應的Button
String request=intent.getStringExtra("request");
switch (request){
//點選新增按鈕進入的,則只顯示btnAdd
case "Add":
btnChange.setVisibility(View.GONE);
btnDelete.setVisibility(View.GONE);
btnAdd.setVisibility(View.VISIBLE);
break;
//通過ListView Item進入的
case "Look":
id=intent.getExtras().getInt("id");
etName.setText(intent.getStringExtra("name"));
etGrade.setText(intent.getStringExtra("grade"));
//隨機設定頭像
if(id%2==0)
{
imageView.setImageResource(R.mipmap.girl1);
}else{
imageView.setImageResource(R.mipmap.boy2);
}
break;
}
btnAdd.setOnClickListener(this);
btnChange.setOnClickListener(this);
btnDelete.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_add_student:
Student newStudent=new Student(id,etName.getText().toString(),etGrade.getText().toString());
handler.addStudent(newStudent);
setResult(RESULT_OK, intent);
finish();
break;
case R.id.btn_change:
Student student=new Student(id,etName.getText().toString(),etGrade.getText().toString());
handler.updateStudent(student);
//這裡設定resultCode是為了區分是修改後返回主介面的還是刪除後返回主介面的。
setResult(2,intent);
finish();
break;
case R.id.btn_delete:
Student s=new Student(id,etName.getText().toString(),etGrade.getText().toString());
handler.deleteStudent(s);
setResult(3, intent);
finish();
break;
}
}
}
7,Manifest.xml:記得將StudentActivity新增進Manifest.xml
<activity android:name=".StudentActivity"/>
總結:
事實上,如果你對startActivityForResult()方法和Intent在Activity之間傳遞值等比較熟悉的話,這個Demo顯得很簡單,另外我們還用到了如何使用自定義View的ALertDialog和自定義View的ListView。還有一種比較常用的方法就是使用
CursorAdapter
來直接將資料庫資料填充到ListView上,可以參考下面的文章。最後,對SQLiteDatabase在使用中的一些常用步驟需要了解,懂得如何封裝我們所需要的操作,當然,最好自己能夠動手實踐,這樣才能找到自己不熟悉或者出錯的地方,下面幾篇文章或許對你有所幫助~。
參考資料: