Android实战之SQLite
使用AS 完成SQLite数据库的简单CRUD操作的一个小demo
效果图
核心代码
1.MainActivity.java
public class MainActivity extends Activity implements View.OnClickListener {
private MyDAO myDAO; //数据库访问对象
private ListView listView;
private List<Map<String,Object>> listData;
private Map<String,Object> listItem;
private SimpleAdapter listAdapter;
private EditText et_name;
private EditText et_age;
private String selId=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bt_add= (Button) findViewById(R.id.bt_add);bt_add.setOnClickListener(this);
Button bt_modify=(Button)findViewById(R.id.bt_modify);bt_modify.setOnClickListener(this);
Button bt_del=(Button)findViewById(R.id.bt_del);bt_del.setOnClickListener(this);
et_name=(EditText)findViewById(R.id.et_name);
et_age=(EditText)findViewById(R.id.et_age);
myDAO = new MyDAO(this);
if(myDAO.getRecordsNumber()==0) {
myDAO.insertInfo("zzh", 20);
myDAO.insertInfo("zjh", 10);
}
displayRecords(); //显示记录
}
public void displayRecords(){ //显示记录方法定义
listView = (ListView)findViewById(R.id.listView);
listData = new ArrayList<Map<String,Object>>();
Cursor cursor = myDAO.allQuery();
while (cursor.moveToNext()){
int id=cursor.getInt(0); //获取字段值
String name=cursor.getString(1);
//int age=cursor.getInt(2);
int age=cursor.getInt(cursor.getColumnIndex("age"));//推荐此种方式
listItem=new HashMap<String,Object>(); //必须在循环体里新建
listItem.put("_id", id); //第1参数为键名,第2参数为键值
listItem.put("name", name);
listItem.put("age", age);
listData.add(listItem); //添加一条记录
}
listAdapter = new SimpleAdapter(this,
listData,
R.layout.list_item, //自行创建的列表项布局
new String[]{"_id","name","age"},
new int[]{R.id.tv_id,R.id.tvname,R.id.tvage});
listView.setAdapter(listAdapter); //应用适配器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { //列表项监听
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Map<String,Object> rec= (Map<String, Object>) listAdapter.getItem(position); //从适配器取记录
et_name.setText(rec.get("name").toString()); //刷新文本框
et_age.setText(rec.get("age").toString());
Log.i("ly",rec.get("_id").toString());
selId=rec.get("_id").toString(); //供修改和删除时使用
}
});
}
public void onClick(View v) { //实现的接口方法
if(selId!=null) { //选择了列表项后,可以增加/删除/修改
String p1 = et_name.getText().toString().trim();
int p2 = Integer.parseInt(et_age.getText().toString());
switch (v.getId()){
case R.id.bt_add:
myDAO.insertInfo(p1,p2);
break;
case R.id.bt_modify:
myDAO.updateInfo(p1,p2,selId);
Toast.makeText(getApplicationContext(),"更新成功!",Toast.LENGTH_SHORT).show();
break;
case R.id.bt_del:
myDAO.deleteInfo(selId);
Toast.makeText(getApplicationContext(),"删除成功!",Toast.LENGTH_SHORT).show();
et_name.setText(null);et_age.setText(null); selId=null; //提示
}
}else{ //未选择列表项
if(v.getId()==R.id.bt_add) { //单击添加按钮
String p1 = et_name.getText().toString();
String p2=et_age.getText().toString();
if(p1.equals("")||p2.equals("")){ //要求输入了信息
Toast.makeText(getApplicationContext(),"姓名和年龄都不能空!",Toast.LENGTH_SHORT).show();
}else{
myDAO.insertInfo(p1, Integer.parseInt(p2)); //第2参数转型
}
} else{ //单击了修改或删除按钮
Toast.makeText(getApplicationContext(),"请先选择记录!",Toast.LENGTH_SHORT).show();
}
}
displayRecords();//刷新ListView对象
}
}
2.MyDAO.java
package com.example.mysqlite;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import myDBHelper.DbHelper;
public class MyDAO {
private SQLiteDatabase myDb; //类的成员
private DbHelper dbHelper; //类的成员
public MyDAO(Context context) { //构造方法,参数为上下文对象
//第1参数为上下文,第2参数为数据库名
dbHelper = new DbHelper(context,"test.db",null,1);
}
public Cursor allQuery(){ //查询所有记录
myDb = dbHelper.getReadableDatabase();
return myDb.rawQuery("select * from friends",null);
}
public int getRecordsNumber(){ //返回数据表记录数
myDb = dbHelper.getReadableDatabase();
Cursor cursor= myDb.rawQuery("select * from friends",null);
return cursor.getCount();
}
public void insertInfo(String name,int age){ //插入记录
myDb = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
long rowid=myDb.insert(DbHelper.TB_NAME, null, values);
if(rowid==-1)
Log.i("myDbDemo", "数据插入失败!");
else
Log.i("myDbDemo", "数据插入成功!"+rowid);
}
public void deleteInfo(String selId){ //删除记录
String where = "_id=" + selId;
int i = myDb.delete(DbHelper.TB_NAME, where, null);
if (i > 0)
Log.i("myDbDemo", "数据删除成功!");
else
Log.i("myDbDemo", "数据未删除!");
}
public void updateInfo(String name,int age,String selId){ //修改记录
//方法中的第三参数用于修改选定的记录
ContentValues values = new ContentValues();
values.put("name", name);
values.put("age", age);
String where="_id="+selId;
int i=myDb.update(DbHelper.TB_NAME, values, where, null);
//上面几行代码的功能可以用下面的一行代码实现
//myDb.execSQL("update friends set name = ? ,age = ? where _id = ?",new Object[]{name,age,selId});
if(i>0)
Log.i("myDbDemo","数据更新成功!");
else
Log.i("myDbDemo","数据未更新!");
}
}
3.DbHelper.java
package myDBHelper;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DbHelper extends SQLiteOpenHelper {
public static final String TB_NAME = "friends";
public DbHelper( Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS " +
TB_NAME + "( _id integer primary key autoincrement," +
"name varchar," + "age integer"+ ")");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TB_NAME);
onCreate(db);
}
}
项目地址:
码云仓库