项目下载:http://download.csdn.net/detail/iwanghang/9601862
manifests:
MainActivity:
package com.iwanghang.sqlitedemo;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
import com.iwanghang.sqlitedemo.dialog.DeleteDialog;
import com.iwanghang.sqlitedemo.dialog.InsertDialog;
import com.iwanghang.sqlitedemo.dialog.UpdateDialog;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements View.OnClickListener {
private SQLiteHelper db;
private ListAdapter listAdapter;
/**
* 插入请求代码
*/
private static final int INSERT_REQUESTCODE = 1;
/**
* 插入结果代码
*/
private static final int INSERT_RESULTCODE = 1;
/**
* 删除请求代码
*/
private static final int DELETE_REQUESTCODE = 2;
/**
* 删除结果代码
*/
private static final int DELETE_RESULTCODE = 2;
/**
* 修改请求代码
*/
private static final int UPDATE_REQUESTCODE = 3;
/**
* 修改结果代码
*/
private static final int UPDATE_RESULTCODE = 3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = new SQLiteHelper(this, "person.db", null, 1);
init();
}
private void init() {
findViewById(R.id.btn_insert).setOnClickListener(this);
findViewById(R.id.btn_delete).setOnClickListener(this);
findViewById(R.id.btn_update).setOnClickListener(this);
findViewById(R.id.btn_query).setOnClickListener(this);
listAdapter = new ListAdapter(new ArrayList(), this);
findViewById(R.id.list_data, ListView.class).setAdapter(listAdapter);
}
private T findViewById(int id, Class c) {
return (T) findViewById(id);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_insert: // 插入
insert();
break;
case R.id.btn_delete: // 删除
delete();
break;
case R.id.btn_update: // 修改
update();
break;
case R.id.btn_query: // 查询
query();
break;
}
}
/**
* 添加
*/
private void insert() {
Intent intent = new Intent(this, InsertDialog.class);
startActivityForResult(intent, INSERT_REQUESTCODE);
}
/**
* 删除
*/
private void delete() {
Intent intent = new Intent(this, DeleteDialog.class);
startActivityForResult(intent, DELETE_REQUESTCODE);
}
/**
* 更新
*/
private void update() {
Intent intent = new Intent(this, UpdateDialog.class);
startActivityForResult(intent, UPDATE_REQUESTCODE);
}
/**
* 查询
*/
private void query() {
List list = db.queryAllPerson(); // 查询所有的Person
loadData(list); // 加载数据到ListView上面
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case INSERT_REQUESTCODE:
if (resultCode == INSERT_RESULTCODE) { // 插入请求
if (data != null) {
db.addPerson((Person) data.getSerializableExtra("person"));
showMessage("插入成功!");
query();
} else {
showMessage("取消插入!");
}
}
break;
case DELETE_REQUESTCODE:
if (resultCode == DELETE_RESULTCODE) { // 删除请求
if (data != null) {
int _id = data.getIntExtra("_id", -1);
if (_id != -1) {
if (db.queryPersonById(_id) != null) {
db.deletePerson(_id);
showMessage("删除成功!");
query();
} else {
showMessage("删除失败\t_id:" + _id + "不存在!");
}
} else {
showMessage("删除失败!");
}
} else {
showMessage("取消删除!");
}
}
break;
case UPDATE_REQUESTCODE:
if (resultCode == UPDATE_RESULTCODE) { // 修改请求
if (data != null) {
Person person = (Person) data
.getSerializableExtra("person");
int _id = person.get_id();
if (db.queryPersonById(person.get_id()) != null) {
db.updatePerson(person);
showMessage("修改成功!");
query();
} else {
showMessage("修改失败\t_id:" + _id + "不存在!");
}
} else {
showMessage("取消修改!");
}
}
break;
}
}
/**
* 显示消息
*
* @param msg
* 消息
*/
private void showMessage(String msg) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
/**
* 加载数据到ListView
*
* @param list
* Person集合
*/
private void loadData(List list) {
listAdapter.setList(list);
listAdapter.notifyDataSetChanged(); // 刷新数据
}
}
Person:
package com.iwanghang.sqlitedemo;
import java.io.Serializable;
/**
* 人
*/
public class Person implements Serializable {
/**
* 序列化的版本号
*/
private static final long serialVersionUID = 1L;
/**
* 组件
*/
private int _id;
/**
* 姓名
*/
private String name;
/**
* 年龄
*/
private int age;
/**
* 性别
*/
private String sex;
/**
* set方法
* get方法
*/
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
ListAdapter:
package com.iwanghang.sqlitedemo;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.List;
public class ListAdapter extends BaseAdapter {
private List list;
private LayoutInflater inflater;
public ListAdapter(List list, Context context) {
this.list = list;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setList(List list) {
this.list = list;
}
@Override
public int getCount() {
return list.size();
}
@Override
public Object getItem(int position) {
return list.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null)
convertView = inflater.inflate(R.layout.activity_main_list1, null);
TextView idView = (TextView) convertView.findViewById(R.id.text_id);
TextView nameView = (TextView) convertView.findViewById(R.id.text_name);
TextView ageView = (TextView) convertView.findViewById(R.id.text_age);
TextView sexView = (TextView) convertView.findViewById(R.id.text_sex);
Person person = list.get(position);
idView.setText(String.valueOf(person.get_id()));
nameView.setText(person.getName());
ageView.setText(String.valueOf(person.getAge()));
sexView.setText(String.valueOf(person.getSex()));
return convertView;
}
}
SQLiteHelper:
package com.iwanghang.sqlitedemo;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
/**
* 数据库创建、更新
*/
public class SQLiteHelper extends SQLiteOpenHelper {
/**
* @param context
* 上下文
* @param name
* 数据库名称
* @param factory
* 游标工厂
* @param version
* 数据库版本
*/
public SQLiteHelper(Context context, String name, SQLiteDatabase.CursorFactory factory,
int version) {
super(context, name, factory, version);
}
// 创建数据库
@Override
public void onCreate(SQLiteDatabase db) {
Log.e("SqliteHelper", "数据库创建");
String sql = "create table person(_id integer Primary Key autoincrement,name varchar(20), age integer,sex varchar(20))";
db.execSQL(sql);
}
// 数据库更新
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.e("SqliteHelper", "数据库更新");
}
/**
* 添加Person到数据库
*
* @param person
* Person
*/
public void addPerson(Person person) {
Log.e("SqliteHelper", "插入");
SQLiteDatabase db = getWritableDatabase(); // 以读写的形式打开数据库
// db.execSQL("insert into person(name,age) values("
// + String.format("'%s'", person.getName()) + ","
// + person.getAge() + ");"); // 插入数据库
// insert into person(name,age,sex) values('liudehua',50,'man')
// db.execSQL(
// "insert into person(name,age,sex) values("
// + String.format("'%s'", person.getName()) + ","
// + person.getAge() + ","
// + String.format("'%s'", person.getSex()) +
// ");"
// ); // 插入数据库
db.execSQL(
"insert into person(name,age,sex) values("
+ String.format("'%s'", person.getName()) + ","
+ person.getAge() + ","
+ String.format("'%s'", person.getSex()) +
");"
); // 插入数据库
db.close(); // 关闭数据库连接
}
/**
* 更新Person
*
* @param person
* Person
*/
public void updatePerson(Person person) {
Log.e("SqliteHelper", "更新");
SQLiteDatabase db = getWritableDatabase(); // 以读写的形式打开数据库
// String sql = "update person set name="
// + String.format("'%s'", person.getName()) + ",age="
// + person.getAge() + " where _id=" + person.get_id();
String sql = "update person set name="
+ String.format("'%s'", person.getName())
+ ",age=" + person.getAge()
+ ",sex=" + String.format("'%s'", person.getSex())
+ " where _id=" + person.get_id();
Log.e("updatePerson", sql);
db.execSQL(sql); // 更新数据库
db.close(); // 关闭数据库连接
}
/**
* 删除Person
*
* @param _id
* Person的id
*/
public void deletePerson(int _id) {
Log.e("SqliteHelper", "删除");
SQLiteDatabase db = getWritableDatabase(); // 以读写的形式打开数据库
String sql = "_id = ?";
String wheres[] = { String.valueOf(_id) };
db.delete("person", sql, wheres); // 数据库删除
db.close(); // 关闭数据库
}
/**
* 查询所有的Person
*
* @return 所有Person集合
*/
public List queryAllPerson() {
List list = new ArrayList();
SQLiteDatabase db = getReadableDatabase(); // 以只读的方式打开数据库
String sql = "select * from person;";
Cursor cursor = db.rawQuery(sql, null);
while (cursor.moveToNext()) {
int _id = cursor.getInt(cursor.getColumnIndex("_id"));
String name = cursor.getString(cursor.getColumnIndex("name"));
int age = cursor.getInt(cursor.getColumnIndex("age"));
String sex = cursor.getString(cursor.getColumnIndex("sex"));
Person person = new Person();
person.set_id(_id);
person.setName(name);
person.setAge(age);
person.setSex(sex);
System.out.println(" ---- sex = " + sex);
list.add(person); // 添加到数组
}
cursor.close(); // 关闭游标
db.close(); // 关闭数据库
return list;
}
/**
* 根据id查询Person
*
* @param _id
* id
* @return Person
*/
public Person queryPersonById(int _id) {
Person person = null;
SQLiteDatabase db = getReadableDatabase(); // 以只读方式打开数据库
// String[] columns = { "_id", "name", "age" };
String[] columns = { "_id", "name", "age", "sex" };
String selection = "_id=?";
String[] selectionArgs = { String.valueOf(_id) };
Cursor cursor = db.query("person", columns, selection, selectionArgs,
null, null, null);
if (cursor.moveToNext()) {
person = new Person();
person.set_id(cursor.getInt(cursor.getColumnIndex("_id")));
person.setAge(cursor.getInt(cursor.getColumnIndex("age")));
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setName(cursor.getString(cursor.getColumnIndex("sex")));
}
return person;
}
}
InsertDialog:
package com.iwanghang.sqlitedemo.dialog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import com.iwanghang.sqlitedemo.Person;
import com.iwanghang.sqlitedemo.R;
/**
* 插入对话框
*/
public class InsertDialog extends Activity implements View.OnClickListener {
/**
* 插入请求代码 大于0
*/
private static final int INSERT_REQUESTCODE = 1;
/**
* 姓名控件
*/
private EditText nameView;
/**
* 年龄控件
*/
private EditText ageView;
/**
* 性别控件
*/
private EditText sexView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉标题栏
setContentView(R.layout.insert_dialog);
init();
}
private void init() {
findViewById(R.id.insert_confirm).setOnClickListener(this);
findViewById(R.id.insert_cancel).setOnClickListener(this);
nameView = (EditText) findViewById(R.id.insert_edit_name);
ageView = (EditText) findViewById(R.id.insert_edit_age);
sexView = (EditText) findViewById(R.id.insert_edit_sex);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.insert_confirm:
confirm(); // 确认插入
break;
case R.id.insert_cancel:
cancel(); // 取消插入
break;
}
}
/**
* 确认插入
*/
private void confirm() {
String name = String.valueOf(nameView.getText());
int age = Integer.valueOf(String.valueOf(ageView.getText()));
String sex = String.valueOf(sexView.getText());
Person person = new Person();
person.setName(name);
person.setAge(age);
person.setSex(sex);
Intent intent = new Intent();
intent.putExtra("person", person);
setResult(INSERT_REQUESTCODE, intent);
finish();
}
/**
* 取消插入
*/
private void cancel() {
setResult(INSERT_REQUESTCODE);
finish();
}
}
UpdateDialog:
package com.iwanghang.sqlitedemo.dialog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import com.iwanghang.sqlitedemo.Person;
import com.iwanghang.sqlitedemo.R;
/**
* 修改对话框
*/
public class UpdateDialog extends Activity implements View.OnClickListener {
/**
* 修改请求代码
*/
private static final int UPDATE_REQUESTCODE = 3;
/**
* id控件
*/
private EditText idView;
/**
* 姓名控件
*/
private EditText nameView;
/**
* 年龄控件
*/
private EditText ageView;
/**
* 性别控件
*/
private EditText sexView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉标题栏
setContentView(R.layout.update_dialog);
init();
}
private void init() {
findViewById(R.id.update_confirm).setOnClickListener(this);
findViewById(R.id.update_cancel).setOnClickListener(this);
idView = (EditText) findViewById(R.id.update_edit_id);
nameView = (EditText) findViewById(R.id.update_edit_name);
ageView = (EditText) findViewById(R.id.update_edit_age);
sexView = (EditText) findViewById(R.id.update_edit_sex);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.update_confirm:
confirm(); // 确认修改
break;
case R.id.update_cancel:
cancel(); // 取消修改
break;
}
}
/**
* 确认修改
*/
private void confirm() {
int _id = Integer.valueOf(String.valueOf(idView.getText()));
String name = String.valueOf(nameView.getText());
int age = Integer.valueOf(String.valueOf(ageView.getText()));
String sex = String.valueOf(sexView.getText());
Person person = new Person();
person.set_id(_id);
person.setAge(age);
person.setName(name);
person.setSex(sex);
Intent intent = new Intent();
intent.putExtra("person", person);
setResult(UPDATE_REQUESTCODE, intent);
finish();
}
/**
* 取消修改
*/
private void cancel() {
setResult(UPDATE_REQUESTCODE);
finish();
}
}
DeleteDialog:
package com.iwanghang.sqlitedemo.dialog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import com.iwanghang.sqlitedemo.R;
/**
* 删除对话框
*/
public class DeleteDialog extends Activity implements View.OnClickListener {
/**
* 插入请求代码
*/
private static final int DELETE_REQUESTCODE = 2;
/**
* id控件
*/
private EditText idView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //去掉标题栏
setContentView(R.layout.delete_dialog);
init();
}
private void init() {
findViewById(R.id.delete_confirm).setOnClickListener(this);
findViewById(R.id.delete_cancel).setOnClickListener(this);
idView = (EditText) findViewById(R.id.delete_edit_id);
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.delete_confirm:
confirm(); // 确认删除
break;
case R.id.delete_cancel:
cancel(); // 取消删除
break;
}
}
/**
* 确认删除
*/
private void confirm() {
int _id = Integer.valueOf(String.valueOf(idView.getText()));
Intent intent = new Intent();
intent.putExtra("_id", _id);
setResult(DELETE_REQUESTCODE, intent);
finish();
}
/**
* 取消删除
*/
private void cancel() {
setResult(DELETE_REQUESTCODE);
finish();
}
}
activity_main.xml
activity_main_list1.xml:
insert_dialog.xml:
update_dialog.xml:
delete_dialog.xml:
strings.xml:
Android_SQLite_Demo
Settings
插入
删除
修改
查询
姓名
年龄
性别
确认插入
取消插入
ID
确定删除
取消删除
ID
姓名
年龄
性别
确认更新
取消更新