編輯:關於Android編程
這是作為上一篇Android 數據存儲 如何搞定SQLite Database的實例練習,之所以單獨列出來是因為除了數據庫方面的知識,還涉及其它方面的知識,所以就寫的詳細點,啰嗦點。希望對初學者有所幫助。當然這個Demo比較簡單,有很多可以改進的地方,但那不是這裡探討的重點,重點學習如何將SQLiteDatabase數據綁定到我們的界面!
本文代碼地址:UseSQLitDatabase
我們要做一個簡單的學生管理的demo,創建student.db,包括name,grade字段,實現增、刪、改、查的功能;
實現效果:
我們先不忙著碼代碼,先來看看這樣一個簡單的Demo**基本的界面結構**:
主界面是一個ListView用來顯示學生信息,底部有兩個Button,用來添加和查找學生信息; 點擊**“添加”**Button,進入添加界面,輸入姓名,分數,添加成功後返回主界面; 點擊**“查找”**Button,彈出查找對話框,查找對話框此時包含一個EditView用來輸入學生姓名和一個“查找”Button,當點擊查找Button後,顯示查找結果,如果查找結果為空,提示無此信息,如果不為空,點擊結果可進入詳細界面。 點擊ListView Item可查看學生詳細信息,在詳細信息界面可對學生信息進行編輯修改和刪除。Intent
和startActivityForResult()
等的使用。 SQLiteDatabase的基本使用:這也是我們這個練習的重點,不熟悉的建議先看上篇文章Android 數據存儲 如何搞定SQLite Database;
創建項目後,根據上一篇文章所說,我們按照以下步驟來完成我們的Demo:
通過界面分析我們可以看出:MainActivity用來顯示所有學生列表信息,其他界面提供查看或者編輯修改以及刪除的功能,在界面布局上非常相似,所以我們將它們放到同一個布局裡面,只不過根據具體的情況,設置個某些控件的Visibility
屬性為GONE
或者VISIBLE
;
主界面布局:res/layout/activity_main.xml
,包含一個ListView和兩個Button
詳細界面(增刪改界面)布局:res/layout/student.xml
,在布局文件裡面我們先將**查找**Button的Visibility屬性設置為GONE,即不可見(注意區分:INVISIBLE為不可見但占據布局位置,GONE不可見且不占據位置)。
ListView Item布局:,用來顯示學生頭像,姓名和分數,res/layout/list_item.xml
布局效果:
查找對話框布局:我們還需要為查找對話框做一個布局,res/layout/dialog_search.xml
,注意,剛開始搜索時,只顯示EditView用來輸入學生姓名,顯示搜索結果時EditView不可見而顯示一個ListView,所以布局中先將ListView的Visibility屬性為GONE
布局效果:
Student.java
:為其提供構造函數和setget方法;
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;
}
}
DatabaseHandler.java
:編寫構造函數,覆寫onCreate(),onUpgrade()方法,以及提供增刪改查student的方法:
addStudent(Student student)
;添加student getStudent(String name)
,通過name獲取student getAllStudent()
;獲取所有的student getStudentCounts()
;獲取student數目 updateStudent(Student student)
;更新student deleteStudent(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 getALllStudent(){
List studentList=new ArrayList();
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();
}
}
public class StudentAdapter extends BaseAdapter {
private List students;
private Context context;
public StudentAdapter(Context context,List 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;
}
}
public class MainActivity extends Activity implements View.OnClickListener{
private ListView students;
private StudentAdapter adapter;
private Button btnAdd,btnSearch;
private DatabaseHandler dbHandler;
private List 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 resultList = new ArrayList();
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);
}
}
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;
}
}
}
事實上,如果你對startActivityForResult()方法和Intent在Activity之間傳遞值等比較熟悉的話,這個Demo顯得很簡單,另外我們還用到了如何使用自定義View的ALertDialog和自定義View的ListView。還有一種比較常用的方法就是使用
CursorAdapter
來直接將數據庫數據填充到ListView上,可以參考下面的文章。最後,對SQLiteDatabase在使用中的一些常用步驟需要了解,懂得如何封裝我們所需要的操作,當然,最好自己能夠動手實踐,這樣才能找到自己不熟悉或者出錯的地方,下面幾篇文章或許對你有所幫助~。
在我們的日常開發中自定義控件還是用的挺多的,設計師或者產品為了更好的漂亮,美觀,交互都會做一寫牛逼的ui效果圖,但是最後實現的還是我們程序員啊。所以說 自定義view你還
main.xml Main.javapackage com.wty.mydemoviewflipper;import android.app.Activity;im
首先我將貼出幾種實現圓角邊框的dmeo程序效果圖:方式一:使用shape元素填充背景,設置圓角/帶弧度的角1、首先在 \res\drawable下新建Shape為根元素的
package com.gc.textswitcherdemo; /* * 文本切換器(TextSwitcher): * 1、TextSwitcher繼承了ViewS