最近有同学找我要安卓数据库相关的demo,于是我找到之前研究ormlite和SQLite的demo。该demo也是从网上某个大神那里下载的,自己做了一些修改,先感谢大神的代码,废话不多说。
首先先看效果图:
数据库插入数据,后一页有两种数据库操作的按钮,由于只是对数据库操作,
数据变化并未实时展现到界面,读者可自行切换更新下数据查看。
本文主要介绍下两种数据库操作的不同,上代码:
//ormlite查询
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
stuDao = getHelper().getStudentDao();
students = stuDao.queryBuilder().where().eq("stuNO", etx.getText().toString()).query();
mStudent = students.get(position);
Intent intent = new Intent();
intent.setClass(mContext, MainActivity.class);
intent.putExtra("action", "viewone");
intent.putExtra("entity",mStudent);
startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
/ormlite删除
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
stuDao = getHelper().getStudentDao();
students = stuDao.queryBuilder().where().eq("stuNO", etx.getText().toString()).query();
stuDao.delete(students); //删除记录
queryListViewItem();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
///ormlite更新学号为3的学生姓名,<span style="font-family: Arial, Helvetica, sans-serif;">需要存在学号为3信息</span>
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
UpdateBuilder<Student, Integer> updateBuilder = stuDao.updateBuilder();
updateBuilder.updateColumnValue("name", etx.getText().toString());
updateBuilder.where().eq("stuNO", "3");
@SuppressWarnings("unused")
int rowsUpdated = updateBuilder.update();
queryListViewItem();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
///
//sqlite查询
btn4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String NO = null,name = null,sex = null,address = null;
int age = 0;
double score = 0;
Cursor cursor = db.rawQuery("select * from Student where stuNO = ?", new String[]{"'"+etx.getText().toString()+"'"});
while (cursor.moveToNext()) {
NO = cursor.getString(0);
name = cursor.getString(1);
age = cursor.getInt(2);
sex = cursor.getString(3);
score = cursor.getDouble(4);
address = cursor.getString(5);
}
//show.setText("学号:"+NO+" "+"姓名:"+name+" "+"年龄:"+age+" "+"性别"+sex+" "+"分数:"+score+" "+"地址:"+address);
show.setText(NO+" "+name+" "+age+" "+sex+" "+score+" "+address);
cursor.close();
db.close();
}
});
//sqlite删除
btn5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sql = "delete from Student where stuNO= '"+etx.getText().toString()+"'";//删除操作的SQL语句
db.execSQL(sql);
}
});
//sqlite更新学号为3的学生姓名,需要存在学号为3信息
btn6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sql = "update Student set name= '"+etx.getText().toString()+"'"+" where stuNO = '3' ";//删除操作的SQL语句
db.execSQL(sql);
}
});
上述代码主要实现的最简单的删除,查询和更新。添加数据代码实现在MainActivity
当中。项目主要有四个类,MainActivity主要是添加数据,以及查看数据:
package com.andyidea.ormsqlite;
import java.sql.SQLException;
import com.andyidea.bean.Student;
import com.andyidea.db.DatabaseHelper;
import com.example.ormsqlitedemo.R;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
public class MainActivity extends OrmLiteBaseActivity<DatabaseHelper> {
private EditText stuNO;
private EditText stuName;
private EditText stuAge;
private EditText stuSex;
private EditText stuScore;
private EditText stuAddress;
private Student mStudent;
private Dao<Student,Integer> stuDao;
private final int MENU_ADD = Menu.FIRST;
private final int MENU_VIEWALL = Menu.FIRST+1;
private final int MENU_EDIT = Menu.FIRST+2;
private final int MENU_FIND = Menu.FIRST+3;
private Bundle mBundle = new Bundle();
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
}
/**
* 初始化UI界面
*/
private void initializeViews(){
stuNO = (EditText)findViewById(R.id.stuno);
stuName = (EditText)findViewById(R.id.name);
stuAge = (EditText)findViewById(R.id.age);
stuSex = (EditText)findViewById(R.id.sex);
stuScore = (EditText)findViewById(R.id.score);
stuAddress = (EditText)findViewById(R.id.address);
mBundle = getIntent().getExtras();
if(mBundle!=null && mBundle.getString("action").equals("viewone")){
mStudent = (Student)getIntent().getSerializableExtra("entity");
setStudentUIData(mStudent);
}
if(mBundle!=null && mBundle.getString("action").equals("Sviewone")){
mStudent = (Student)getIntent().getSerializableExtra("entity");
setStudentUIData(mStudent);
}
if(mBundle!=null && mBundle.getString("action").equals("edit")){
mStudent = (Student)getIntent().getSerializableExtra("entity");
setStudentUIData(mStudent);
}
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
if(mBundle!=null && mBundle.getString("action").equals("viewone"))
return false;
else
return super.onPrepareOptionsMenu(menu);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if(mBundle!=null && mBundle.getString("action").equals("edit")){
menu.add(1,MENU_EDIT,0,"保存");
}else{
menu.add(0,MENU_ADD,0,"增加");
menu.add(0,MENU_VIEWALL,0,"查看");
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_ADD:
try {
stuDao = getHelper().getStudentDao();
getStudentData();
if(mStudent != null){
//创建记录项
stuDao.create(mStudent);
}
} catch (SQLException e) {
e.printStackTrace();
}
break;
case MENU_VIEWALL:
Intent intent = new Intent();
intent.setClass(MainActivity.this, StudentListActivity.class);
startActivity(intent);
break;
case MENU_EDIT:
try {
getStudentData();
stuDao = getHelper().getStudentDao();
if(mStudent != null){
//更新某记录项
stuDao.update(mStudent);
}
} catch (SQLException e) {
e.printStackTrace();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* 获取界面值(实体信息)
*/
private void getStudentData(){
mStudent = new Student();
mStudent.setStuNO(stuNO.getText().toString());
mStudent.setName(stuName.getText().toString());
mStudent.setAge(Integer.parseInt(stuAge.getText().toString()));
mStudent.setSex(stuSex.getText().toString());
mStudent.setScore(Double.parseDouble(stuScore.getText().toString()));
mStudent.setAddress(stuAddress.getText().toString());
}
/**
* 赋值给UI界面
* @param student
*/
private void setStudentUIData(Student student){
stuNO.setText(student.getStuNO());
stuName.setText(student.getName());
stuAge.setText(String.valueOf(student.getAge()));
stuSex.setText(student.getSex());
stuScore.setText(String.valueOf(student.getScore()));
stuAddress.setText(student.getAddress());
}
}
DatabaseHelper定义数据库创建与更新:
package com.andyidea.db;
import java.sql.SQLException;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import com.andyidea.bean.Student;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final String DATABASE_NAME = "ormlite.db";
private static final int DATABASE_VERSION = 1;
private Dao<Student,Integer> stuDao = null;
public DatabaseHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* 创建SQLite数据库
*/
@Override
public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {
try {
TableUtils.createTable(connectionSource, Student.class);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
}
}
/**
* 更新SQLite数据库
*/
@Override
public void onUpgrade(
SQLiteDatabase sqliteDatabase,
ConnectionSource connectionSource,
int oldVer,
int newVer) {
try {
TableUtils.dropTable(connectionSource, Student.class, true);
onCreate(sqliteDatabase, connectionSource);
} catch (SQLException e) {
Log.e(DatabaseHelper.class.getName(),
"Unable to upgrade database from version " + oldVer + " to new "
+ newVer, e);
}
}
public Dao<Student,Integer> getStudentDao() throws SQLException{
if(stuDao == null){
stuDao = getDao(Student.class);
}
return stuDao;
}
}
以及无参构造函数,用来返回实体对象:
package com.andyidea.bean;
import java.io.Serializable;
import com.j256.ormlite.field.DatabaseField;
public class Student implements Serializable {
private static final long serialVersionUID = -5683263669918171030L;
@DatabaseField(id=true)
private String stuNO;
@DatabaseField
private String name;
@DatabaseField
private int age;
@DatabaseField
private String sex;
@DatabaseField
private double score;
@DatabaseField
private String address;
public String getStuNO() {
return stuNO;
}
public void setStuNO(String stuNO) {
this.stuNO = stuNO;
}
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;
}
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
最后是具体的操作:
package com.andyidea.ormsqlite;
import java.sql.SQLException;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.andyidea.bean.Student;
import com.andyidea.db.DatabaseHelper;
import com.example.ormsqlitedemo.R;
import com.j256.ormlite.android.apptools.OrmLiteBaseActivity;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.GenericRawResults;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.UpdateBuilder;
public class StudentListActivity extends OrmLiteBaseActivity<DatabaseHelper> {
private Context mContext;
private ListView lvStudents;
private Dao<Student,Integer> stuDao;
private List<Student> students;
private StudentsAdapter adapter;
private Student mStudent;
private EditText etx;
private Button btn1,btn2,btn3,btn4,btn5,btn6;
private TextView show;
private String str;
private SQLiteDatabase db;
private final int MENU_VIEW = Menu.FIRST;
private final int MENU_EDIT = Menu.FIRST+1;
private final int MENU_DELETE = Menu.FIRST+2;
private int position;
protected GenericRawResults<String[]> rmStudent;
public Object myHandler;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.students);
//
DatabaseHelper database = new DatabaseHelper(this);//这段代码放到Activity类中才用this
db = database.getReadableDatabase();;
///
mContext = getApplicationContext();
lvStudents = (ListView)findViewById(R.id.stulist);
registerForContextMenu(lvStudents); //注册上下文菜单
etx = (EditText) findViewById(R.id.findContent);
btn1 = (Button) findViewById(R.id.OsurestuNo);
btn2 = (Button) findViewById(R.id.OsureDle);
btn3 = (Button) findViewById(R.id.OsureChange);
btn4 = (Button) findViewById(R.id.SsurestuNo);
btn5 = (Button) findViewById(R.id.SsureDle);
btn6 = (Button) findViewById(R.id.SsureChange);
show = (TextView) findViewById(R.id.ends);
//ormlite查询
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
stuDao = getHelper().getStudentDao();
students = stuDao.queryBuilder().where().eq("stuNO", etx.getText().toString()).query();
mStudent = students.get(position);
Intent intent = new Intent();
intent.setClass(mContext, MainActivity.class);
intent.putExtra("action", "viewone");
intent.putExtra("entity",mStudent);
startActivity(intent);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
/ormlite删除
btn2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
stuDao = getHelper().getStudentDao();
students = stuDao.queryBuilder().where().eq("stuNO", etx.getText().toString()).query();
stuDao.delete(students); //删除记录
queryListViewItem();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
///ormlite更新学号为3的学生姓名
btn3.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try {
UpdateBuilder<Student, Integer> updateBuilder = stuDao.updateBuilder();
updateBuilder.updateColumnValue("name", etx.getText().toString());
updateBuilder.where().eq("stuNO", "3");
@SuppressWarnings("unused")
int rowsUpdated = updateBuilder.update();
queryListViewItem();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
///
//sqlite查询
btn4.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String NO = null,name = null,sex = null,address = null;
int age = 0;
double score = 0;
Cursor cursor = db.rawQuery("select * from Student where stuNO = ?", new String[]{"'"+etx.getText().toString()+"'"});
while (cursor.moveToNext()) {
NO = cursor.getString(0);
name = cursor.getString(1);
age = cursor.getInt(2);
sex = cursor.getString(3);
score = cursor.getDouble(4);
address = cursor.getString(5);
}
//show.setText("学号:"+NO+" "+"姓名:"+name+" "+"年龄:"+age+" "+"性别"+sex+" "+"分数:"+score+" "+"地址:"+address);
show.setText(NO+" "+name+" "+age+" "+sex+" "+score+" "+address);
cursor.close();
db.close();
}
});
//sqlite删除
btn5.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sql = "delete from Student where stuNO= '"+etx.getText().toString()+"'";//删除操作的SQL语句
db.execSQL(sql);
}
});
//sqlite更新学号为3的学生姓名
btn6.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String sql = "update Student set name= '"+etx.getText().toString()+"'"+" where stuNO = '3' ";//删除操作的SQL语句
db.execSQL(sql);
}
});
queryListViewItem();
adapter = new StudentsAdapter(students);
lvStudents.setAdapter(adapter);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if(v == lvStudents)
position = ((AdapterContextMenuInfo)menuInfo).position;
menu.add(0,MENU_VIEW, 0, "查看");
menu.add(0,MENU_EDIT, 0, "更新");
menu.add(0,MENU_DELETE,0,"删除");
super.onCreateContextMenu(menu, v, menuInfo);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_VIEW:
viewListViewItem(position);
break;
case MENU_EDIT:
editListViewItem(position);
break;
case MENU_DELETE:
deleteListViewItem(position);
break;
default:
break;
}
return super.onContextItemSelected(item);
}
/**
* 查询记录项
*/
private void queryListViewItem(){
try {
stuDao = getHelper().getStudentDao();
//查询所有的记录项
students = stuDao.queryForAll();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 查看记录项
* @param position
*/
private void viewListViewItem(int position){
mStudent = students.get(position);
Intent intent = new Intent();
intent.setClass(mContext, MainActivity.class);
intent.putExtra("action", "viewone");
intent.putExtra("entity", mStudent);
startActivity(intent);
}
/**
* 编辑记录项
*/
private void editListViewItem(int position){
mStudent = students.get(position);
Intent intent = new Intent();
intent.setClass(mContext, MainActivity.class);
intent.putExtra("action", "edit");
intent.putExtra("entity", mStudent);
startActivity(intent);
}
/**
* 删除记录项
* @param position
*/
private void deleteListViewItem(int position){
final int pos = position;
AlertDialog.Builder builder2 = new AlertDialog.Builder(StudentListActivity.this);
builder2.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("警告")
.setMessage("确定要删除该记录");
builder2.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Student mDelStudent = (Student)lvStudents.getAdapter().getItem(pos);
try {
stuDao.delete(mDelStudent); //删除记录
queryListViewItem();
} catch (SQLException e) {
e.printStackTrace();
}
}
});
builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder2.show();
}
class StudentsAdapter extends BaseAdapter{
private List<Student> listStu;
public StudentsAdapter(List<Student> students){
super();
this.listStu = students;
}
@Override
public int getCount() {
return listStu.size();
}
@Override
public Student getItem(int position) {
return listStu.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.studentitem, null);
holder = new ViewHolder();
holder.tvNO = (TextView)convertView.findViewById(R.id.itemno);
holder.tvName = (TextView)convertView.findViewById(R.id.itemname);
holder.tvScore = (TextView)convertView.findViewById(R.id.itemscore);
holder.tvAge = (TextView)convertView.findViewById(R.id.itemage);
holder.tvSex = (TextView)convertView.findViewById(R.id.itemsex);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
Student objStu = listStu.get(position);
holder.tvNO.setText(objStu.getStuNO());
holder.tvName.setText(objStu.getName());
holder.tvScore.setText(String.valueOf(objStu.getScore()));
holder.tvAge.setText(String.valueOf(objStu.getAge()));
holder.tvSex.setText(objStu.getSex());
return convertView;
}
}
static class ViewHolder{
TextView tvNO;
TextView tvName;
TextView tvScore;
TextView tvAge;
TextView tvSex;
}
}
项目较为简单,具体每个类的功能有大概介绍。详细代码已贴出,代码中有具体方法的注释,如有问题欢迎探讨。